Compare commits
24 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| c7cda38235 | |||
| 7124750874 | |||
| 319e7082cc | |||
| 279faa4541 | |||
| 9e4374b678 | |||
| 32c2302c91 | |||
| 61cbe6905d | |||
| 95479ebe77 | |||
| c3d64555d9 | |||
| ac29735d20 | |||
| e780c5246c | |||
| 0d925c7cb9 | |||
| ff26f26e60 | |||
| ac55dc96a4 | |||
| 4148df8fcb | |||
| fa934ccdc6 | |||
| cebd54c978 | |||
| 13eb2c4a15 | |||
| db3dbba294 | |||
| 9740841820 | |||
| df971df135 | |||
| 53c0e095cf | |||
| 47af46fd09 | |||
| c1817607b4 |
+24
-14
@@ -1,22 +1,36 @@
|
||||
# Festipod — variables d'environnement (exemple)
|
||||
#
|
||||
# Copier en `.env` (chargé automatiquement par Bun) et renseigner les valeurs.
|
||||
# Copier en `.env` 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é.
|
||||
#
|
||||
# REQUIS POUR LES TESTS. La suite Cucumber tourne sous `node` (pas sous Bun), qui
|
||||
# ne charge pas `.env` tout seul : le harness le lit explicitement et LÈVE UNE
|
||||
# ERREUR NOMMÉE si le mot de passe ou le fichier manquent. Or `.env` ET `*.ngw`
|
||||
# sont tous deux gitignorés — un clone frais n'a donc ni l'un ni l'autre et ne
|
||||
# peut pas exécuter `@data`/`@e2e` tant que ces deux valeurs ne sont pas fournies.
|
||||
|
||||
# ── 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.
|
||||
# VIDE => rien n'est passé à `configure({ sharedWallet })` => le SDK refuse de
|
||||
# signer l'entrée et l'app affiche son panneau d'erreur au lieu de démarrer.
|
||||
# REQUIS en staging (onboarding d'un appareil sans wallet) ET pour les tests.
|
||||
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.
|
||||
# Chemin vers le fichier portefeuille partagé (.ngw), absolu ou relatif à la
|
||||
# racine. Servi en téléchargement à /shared-wallet.ngw. C'est la forme du DEV
|
||||
# LOCAL et du harness de TESTS : le fichier vit sur le disque de la machine.
|
||||
FESTIPOD_SHARED_WALLET_FILE=/chemin/absolu/vers/festipod-wallet.ngw
|
||||
|
||||
# Contenu du portefeuille partagé (.ngw), encodé en base64 — deuxième source
|
||||
# pour le même fichier. C'est la forme des DÉPLOIEMENTS (conteneur) : *.ngw est
|
||||
# gitignoré, donc `COPY . .` n'en embarque aucun et rien n'en monte un ; le
|
||||
# fichier n'étant pas un secret (l'app le sert à quiconque ouvre l'app), il
|
||||
# voyage comme une variable de config. `FESTIPOD_SHARED_WALLET_FILE` est
|
||||
# prioritaire quand les deux sont renseignées — voir le commentaire dans
|
||||
# src/index.ts. Générer la valeur avec, p.ex., `base64 -w0 festipod-wallet.ngw`.
|
||||
FESTIPOD_SHARED_WALLET_FILE_BASE64=
|
||||
|
||||
# ── 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.
|
||||
@@ -30,11 +44,7 @@ PORT=3000
|
||||
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.
|
||||
# Override du chemin local du polyfill @ng-eventually/sdk pour `pnpm run
|
||||
# overlay:polyfill` (overlay local réactif). Défaut = ../nextgraph/ng-eventually-js/packages/sdk.
|
||||
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=
|
||||
|
||||
@@ -44,3 +44,6 @@ storybook-static
|
||||
dist-staging/
|
||||
*.ngw
|
||||
.tasks/
|
||||
|
||||
# Per-developer contract access map (canonical provider → local checkout) — never committed.
|
||||
.project/contracts.local.yaml
|
||||
|
||||
@@ -19,7 +19,8 @@ How the app's code is **structured** and **assembled**. *Feature-based* architec
|
||||
- [[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
|
||||
- [[caveat_identity-ids-in-screens]] — `currentUserId` is empty until my profile document resolves, and an ownership answer can be UNKNOWN; neither means "no"
|
||||
- [[caveat_boot-unverified-outside-broker]] — the unconditional `ensureIdentity()` await is verified inside the broker iframe; standalone/top-level boot is unverified
|
||||
- [[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,25 @@
|
||||
---
|
||||
type: caveat
|
||||
summary: The standalone boot (app opened directly, not in the broker iframe) is covered by NO test, and it broke SILENTLY once — a blank page with no error, because nothing started a session and ensureIdentity() then settled neither way. Fixed by making the session start unconditionally; still untested, so break it and you will not hear about it.
|
||||
last_checked: 2026-08-10
|
||||
---
|
||||
|
||||
# Pitfall: nothing tests the app booting outside the broker iframe
|
||||
|
||||
## What happened, VERIFIED
|
||||
|
||||
`AuthGate` awaits `ensureIdentity()` and renders **nothing** until it settles. `NextGraphProvider` used to start the NextGraph session **only inside the broker iframe** — standalone, the session was started by the user pressing "Entrer" on the app's own access screen.
|
||||
|
||||
That screen was deleted the same day (the SDK shows the barrier now, see [[decision_2026-08-10_sdk-renders-the-barrier]]), and the iframe-only condition survived it. Standalone, the result was: no session ever started → the `getSession` thunk never returned → `ensureIdentity()` **neither resolved nor rejected** → `AuthGate` returned `null` forever. **A blank page with nothing in the console.**
|
||||
|
||||
Note the shape of the failure, because it is the instructive part: a rejection would have been *shown* (`AuthGate` renders a named error panel). What produced silence was a promise that never settled at all — the one outcome no error path catches. Found by a human opening the app, not by any suite.
|
||||
|
||||
The fix: the session starts unconditionally, in the iframe and standalone alike, through one `startSession()` in `NextGraphContext`. Standalone, `initNg()` redirects to the broker — that redirect **is** the sign-in flow now that nothing is left to click.
|
||||
|
||||
## What is still true
|
||||
|
||||
**No test exercises this path.** `@data` runs the harness inside the broker iframe; `@e2e` drives the real app inside the broker iframe too. The standalone top-level boot — the one a developer uses every day with `bun run dev`, and the one a first-time visitor hits — is covered by nothing.
|
||||
|
||||
So: a change to `AuthGate`, to `NextGraphProvider`, or to what `configure()` receives can break the app's entry completely while every suite stays green. If you touch any of them, **open the app yourself** before believing the tests — and drive a whole flow rather than looking at the page, which is what a throwaway probe is for (`bdd-testing` → [[cookbook_live-probe]]).
|
||||
|
||||
Two related pieces: [[caveat_first-time-entry-untested]] (the wallet-import journey, same blind spot seen from the user's side) and [[caveat_shared-wallet-global-before-gate-import]] (a missing wallet password now makes `ensureIdentity()` throw, which at least fails loudly).
|
||||
@@ -1,28 +1,36 @@
|
||||
---
|
||||
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
|
||||
summary: Values a screen must not read as data once — currentUserId is EMPTY until my profile document resolves, an ownership answer can be UNKNOWN, and a useState seeded from an unresolved read (UpdateEventScreen) freezes blank; all look like ordinary values, none mean "no"
|
||||
last_checked: 2026-08-17
|
||||
---
|
||||
|
||||
# Pitfall: two ids for the current user inside a screen
|
||||
# Pitfall: "not answered yet" looks exactly like an answer
|
||||
|
||||
`useFestipodData()` exposes **two** identifiers for the current user. They live in **different spaces** and are **never equal in connected mode**:
|
||||
Two things a screen receives can be *unresolved*, and in both cases the unresolved form reads like an ordinary value. Nothing throws.
|
||||
|
||||
| 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 |
|
||||
## `currentUserId` is empty until my profile resolves
|
||||
|
||||
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.
|
||||
`currentUserId` **is** `currentUser?.id`: the NURI of **the profile document I own**. It is not derived from the signed-in identity and shares no id space with it — the identity the session signed in as is opaque, is never rendered, and never travels into a data call (`data-layer` → [[knowledge_context-internals]]). A screen never sees it except as an attribution string.
|
||||
|
||||
## The rule
|
||||
Until that profile document resolves — the owned-document listing has to land, and a profile may have to be created — `currentUserId` is **`''`**, a perfectly ordinary empty string.
|
||||
|
||||
- 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`.
|
||||
- A **query** keyed on it (`getUserEvents`, `isParticipating`, `getFriends`, all defaulting to it) returns an **empty result**, which renders as "you have nothing" instead of "not ready yet".
|
||||
- A **mutation** that needs it now **rejects** rather than writing a malformed entity: `joinEvent` and `leaveEvent` throw, naming the cause. A caller must therefore *await* them and handle the rejection — the confirmation belongs **after** the write, never beside the call. A screen that fires and forgets shows a success it did not get.
|
||||
|
||||
## What the mistake costs (observed)
|
||||
**The rule**: treat an empty `currentUserId` as *not ready*, never as *no data*.
|
||||
|
||||
- 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.
|
||||
## An ownership answer can be UNKNOWN
|
||||
|
||||
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]].
|
||||
`getEventOwnership(eventId)` returns `'mine' | 'not-mine' | 'unknown'`, and `unknown` is a **real third answer** — the listing has not landed, or it failed (`data-layer` → [[knowledge_write-rights-are-ownership]]).
|
||||
|
||||
Rendering it as "not yours" silently denies an owner their own event. Rendering it as a **disabled twin** of the real control is no better: a greyed pencil reads as "edit, broken" and invites a dead click. The slot stays occupied by a distinct *pending* mark, so the layout does not jump and nobody is told a wrong verdict — `app-security` → [[decision_2026-08-16_write-rights-are-the-owned-list]].
|
||||
|
||||
Never derive permission from `unknown` either. A screen that opens an editor because the answer "was not a refusal" is editing on a guess; the edit route consults the same three-state answer the control does, and renders `unknown` as its own pending state — [[knowledge_screen-pattern]].
|
||||
|
||||
> The participation→profile join is **not** the screen's business — it is done in the provider (`resolveParticipantUser`). Full mechanics: `data-layer` → [[knowledge_context-internals]].
|
||||
|
||||
## A `useState` seed freezes on whatever the first render saw
|
||||
|
||||
`UpdateEventScreen` reads `const event = eventId ? getEvent(eventId) : undefined;` from the reactive data plane, then seeds every editable field from it: `useState(event?.title ?? '')`, and likewise for `startDate`, `endDate`, `startTime`, `endTime`, `location`, `description`. A `useState` initializer runs **once**, at mount — unlike a value read directly in the render body, it does not track `event` afterwards.
|
||||
|
||||
If the screen mounts before the event has landed in the reactive set — a direct navigation to the edit route, a slow reconnect — every field seeds to `''` and **stays blank**: the later, successful read of `event` never reaches state that already initialized. Nothing throws and nothing looks wrong; the form is simply empty. Same hazard as `currentUserId` and the ownership answer above — "not ready yet" reads as an ordinary value — just caught by `useState` instead of by a query result. Pre-existing, not fixed.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
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
|
||||
summary: src/app/ is the app's real shell — App.tsx stacks the providers (Theme > NextGraph > FestipodData > Router), AuthGate makes the one unconditional ensureIdentity() await and renders nothing of its own until it settles, and the shell switches screens according to the route
|
||||
last_checked: 2026-08-10
|
||||
---
|
||||
|
||||
# App shell
|
||||
@@ -16,28 +16,22 @@ last_checked: 2026-07-27
|
||||
|
||||
```
|
||||
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
|
||||
└ NextGraphProvider (NextGraph connection cycle — concept data-layer)
|
||||
└ FestipodDataProvider (data, connected/demo mode — concept data-layer)
|
||||
└ RouterProvider (current route + navigate)
|
||||
└ div.app-container
|
||||
├ AuthGate (the one ensureIdentity() await; renders nothing of its own)
|
||||
│ └ AppContent (switch route.page → screen)
|
||||
└ ToastContainer
|
||||
```
|
||||
|
||||
`AppContent` reads `useRouter()` to resolve `route.page` → the screen to render.
|
||||
`AppContent` reads `useRouter()` to resolve `route.page` → the screen to render. **There is no identity provider**: the app names no identity of its own (concept `app-security`, [[decision_2026-08-10_the-barrier-names-no-identity]]), so there is nothing to hold above the data provider.
|
||||
|
||||
### 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`).
|
||||
- **`AuthGate` sits INSIDE the router**: it reads `useRouter()`/`useNavigate()` to leave the logged-out landing route once identified. Moving it out of `RouterProvider` breaks it.
|
||||
- **`AuthGate` wraps EVERY routed screen**, and it holds them behind **one** condition: the single `await ensureIdentity()` (`@ng-eventually/polyfill`) it fires unconditionally on mount has resolved. Until it does, `AuthGate` renders **nothing at all** — there is no Festipod screen standing in for `AppContent` while it waits (concept `app-security`, [[decision_2026-08-10_sdk-renders-the-barrier]]). `AuthGate` does not read `useNextGraph()` — no `status`, no `connect()`, no error branch of its own. The identity await is not decoration: `ensureIdentity()` also does the connection work (restoring what others shared with us), so a screen mounted before it resolves would read as an identity that is not yet settled. Consequence: **no screen may assume it is reachable without a settled identity**, and there is no longer a way to disable the barrier — see [[caveat_boot-unverified-outside-broker]] for the one path this leaves unverified.
|
||||
- **`ToastContainer` sits OUTSIDE `AuthGate`** (but inside `.app-container`): it is mounted regardless of whether identity has settled.
|
||||
|
||||
## Entry points
|
||||
|
||||
@@ -45,6 +39,6 @@ ThemeProvider
|
||||
|---|---|
|
||||
| `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 />` |
|
||||
| `src/app/frontend.tsx` | React root — pulls the runtime config, sets the wallet global, **then** dynamically imports and renders `<App />`; the order is the point (`tech-stack` → [[knowledge_build-pipeline]], `app-security` → [[caveat_shared-wallet-global-before-gate-import]]) |
|
||||
|
||||
The build and the bundler (Bun + Tailwind, alias `@/* → ./src/*`) are documented in the `tech-stack` concept.
|
||||
|
||||
@@ -30,11 +30,11 @@ Each module may contain:
|
||||
| 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]] |
|
||||
| `context/` | `ThemeContext`, `NextGraphContext`, `FestipodDataContext` (concept `data-layer`); their **stacking order** is constrained, see [[knowledge_app-shell]]. There is no identity context — the app names no identity of its own (concept `app-security`) |
|
||||
| `data/` | User stories, `features.ts` (auto-generated), `seedData.ts`, `types.ts` |
|
||||
| `hooks/` | `useShapeWithDefaults` (NextGraph) |
|
||||
| `hooks/` | empty — the reactive read binding lives in `data/useShapeQuery.ts` (concept `data-layer`) |
|
||||
| `shapes/` | SHEX + ORM bindings (see concept `data-layer`) |
|
||||
| `utils/` | `ngSession.ts`, `ngBootstrap.ts`, `ngGraph.ts` |
|
||||
| `utils/` | `ngSession.ts`, `ngBootstrap.ts`, `ngGraph.ts`, `storeRegistry.ts`, `connections.ts`, `identifier.ts`, `resolveOnce.ts` (single-flight resolution per key, unit-tested), `serialTask.ts` (a task that never runs concurrently with itself, unit-tested) |
|
||||
| `steps/`, `support/` | Shared Cucumber step definitions and hooks (concept `bdd-testing`) |
|
||||
| `lib/` | Helpers (`cn`, etc.) |
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
---
|
||||
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
|
||||
summary: Canonical anatomy of a screen — named function with no props, everything through useFestipodData/useNavigate/useParams, flex column layout, hard-coded French labels; the confirmation FOLLOWS the write, and a write affordance is decided by the three-state ownership answer
|
||||
last_checked: 2026-08-16
|
||||
---
|
||||
|
||||
# Canonical screen pattern
|
||||
@@ -17,9 +18,10 @@ export function MyScreen() { // named function, NEVER any props
|
||||
const [local, setLocal] = useState(…); // screen-local state (steps, selections)
|
||||
|
||||
const handleAction = () => {
|
||||
// …mutate through useFestipodData
|
||||
showToast('Message', 'success'); // feedback
|
||||
navigate('/path');
|
||||
// THE CONFIRMATION FOLLOWS THE WRITE — never beside the call.
|
||||
void Promise.resolve(mutate(…))
|
||||
.then(() => { showToast('Message', 'success'); navigate('/path'); })
|
||||
.catch((err: unknown) => { console.error(…); showToast('Échec…', 'error'); });
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -34,10 +36,10 @@ export function MyScreen() { // named function, NEVER any props
|
||||
|
||||
## 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.
|
||||
- **Zero props, no exception left**: every registered screen receives nothing; everything comes from context/hooks (`useFestipodData`, `useNavigate`, `useParams`). `WelcomeScreen` does not use `useFestipodData` (intro) — but still takes no props. (`LoginScreen`/`ConnexionScreen`/`AccessGateScreen` no longer exist — Festipod renders no access screen of its own; see [[knowledge_screens]] and [[knowledge_app-shell]].)
|
||||
- **Identity: the current user may not be there yet.** `currentUserId` is the NURI of the profile document this session **owns**, so it is **empty until that document resolves** — see [[caveat_identity-ids-in-screens]] before keying anything on it.
|
||||
- **The confirmation FOLLOWS the write.** Mutations reject rather than returning quietly, so a screen must `await` (or `.then`) before announcing anything: success toast and navigation on resolve, an error toast on reject, and the user kept on their edits. A toast fired beside the call announces a write that may never have happened — the pattern that had to be corrected on the event and profile edit screens.
|
||||
- **A write affordance is decided by ownership, in three states.** Both the control that *offers* the write and the screen that *performs* it consult the same answer (`data-layer` → [[knowledge_write-rights-are-ownership]]). `unknown` is never folded into either side: showing the form lets a non-owner edit on a guess, and bouncing them out tells a genuine owner their thing is not theirs. Render it as its own pending state.
|
||||
- **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.
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
---
|
||||
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)
|
||||
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); the auth module now holds only WelcomeScreen, no access screen of its own
|
||||
last_checked: 2026-08-10
|
||||
---
|
||||
|
||||
# Screens and components
|
||||
@@ -30,11 +31,9 @@ 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]]).
|
||||
- **auth/**: `WelcomeScreen` (intro, routed at `/`) is the only screen left in this module. Festipod renders **no access screen of its own** any more: `AccessGateScreen`, its route and its registration are deleted, along with the `LoginScreen`/`ConnexionScreen` that preceded it. Signing in is `src/app/AuthGate.tsx`'s single `await ensureIdentity()`; whatever a user sees or does while that resolves is drawn entirely by the SDK, outside the registry, outside routing, and outside this app's component tree (concept `app-security`, [[decision_2026-08-10_sdk-renders-the-barrier]]).
|
||||
|
||||
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.
|
||||
> The path → screen mapping lives in [[knowledge_routing]]. Most screens consume `useFestipodData()` (concept `data-layer`); the exception is `WelcomeScreen`.
|
||||
|
||||
## Pitfall: incomplete registry
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
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]
|
||||
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, identité, login, scope, isolation]
|
||||
paths: ["src/modules/auth/**", "src/shared/context/NextGraphContext.tsx"]
|
||||
---
|
||||
|
||||
@@ -10,17 +10,22 @@ triggers:
|
||||
|
||||
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]].
|
||||
- **Enforced model** — **isolation between scopes** (public / protected / private) is **enforced by the data SDK** (`@ng-eventually/polyfill`), 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]].
|
||||
- **Write rights** — only a document's owner writes it, and the owned-document listing is the whole answer; the app reads it to decide what to *offer*, never to enforce. Settled: [[decision_2026-08-16_write-rights-are-the-owned-list]].
|
||||
- **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")
|
||||
## Pitfalls
|
||||
|
||||
- [[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)
|
||||
- [[caveat_shared-wallet-global-before-gate-import]] — a wallet-password global set **after** `sharedWallet.ts` has been imported makes `ensureIdentity()` throw and the app render nothing, silently
|
||||
|
||||
> **Before designing anything "anonymous"**, read the closing section of [[knowledge_trust-model]]: the contract guarantees isolation, never anonymity, so a Festipod action that circulates a reference to someone's document is pseudonymous at best.
|
||||
|
||||
## 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
|
||||
- [[knowledge_authentication]] — wallet-based auth, everyone authenticated, no anonymous access, no screen of Festipod's own
|
||||
- [[decision_2026-08-10_the-barrier-names-no-identity]] — the app names no identity: the barrier takes nothing, signing in is one `ensureIdentity()`
|
||||
- [[decision_2026-08-10_sdk-renders-the-barrier]] — Festipod renders no access screen of its own; the SDK draws whatever a first-time device needs to see
|
||||
- [[decision_2026-08-16_write-rights-are-the-owned-list]] — may-I-write is the owned-document listing and nothing else; no capability probe is planned
|
||||
- [[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)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
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
|
||||
summary: Target authorization matrix per data type (meeting point, registration, event, profile, connection) mapped onto the public/protected/private/dialog scopes; framing decisions settled and event update now settled as owner-only; host identity and event deletion still open
|
||||
last_updated: 2026-05-18
|
||||
---
|
||||
|
||||
@@ -68,10 +68,10 @@ Notes: no `C` differentiation (connections are a UI display filter, not a right,
|
||||
|---|---|---|---|
|
||||
| create | ✓ (becomes declarer) | — | ✓ (becomes declarer) |
|
||||
| read / subscribe | ✓ | ✓ | ✓ |
|
||||
| update | ? **to be decided** | ? **to be decided** | ? **to be decided** |
|
||||
| update | ✓ (owner, sole writer) | ✗ | ✗ |
|
||||
| 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)?
|
||||
**Update is settled — owner only**, and forced rather than chosen: only a document's owner writes it and no call adds a writer, so "wiki" is not expressible ([[decision_2026-08-16_write-rights-are-the-owned-list]]). It constrains deduplication (concept `functional-domain`, [[brief_2026-06-15_event-deduplication]]). **Open:** who may **delete** an event, and what becomes of the grafted meeting points (orphaned/cascade/marked deleted)?
|
||||
|
||||
### User profile
|
||||
|
||||
|
||||
@@ -1,21 +1,22 @@
|
||||
---
|
||||
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
|
||||
summary: The wallet password is captured at the EVALUATION of src/shared/utils/sharedWallet.ts — a value set after that first import is never re-read, and the fetch that sets it must never be gated on NODE_ENV (production serves from src/). Missing it: ensureIdentity() throws, AuthGate shows the reason.
|
||||
last_checked: 2026-08-16
|
||||
---
|
||||
|
||||
# Pitfall: set the shared-wallet global BEFORE importing the barrier
|
||||
# Pitfall: set the wallet-password global BEFORE the module is first imported
|
||||
|
||||
**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.
|
||||
The contract requires a deployment to **serve a wallet file and pass its URL and password to `configure`** ([[contract_polyfill-surface]]). Festipod does that from one module, and *when* that module is evaluated decides whether the value arrives at all.
|
||||
|
||||
**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.
|
||||
**The invariant.** `src/shared/utils/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. This module used to be `src/modules/auth/sharedWallet.ts`; that file, and `AccessGateScreen` which was its only reason to sit in the `auth` module, are both deleted — the surviving copy lives in `shared/utils/` and is imported by `src/shared/utils/ngSession.ts`, which reads `hasSharedWallet()` to decide whether to pass a `sharedWallet` config into the SDK's `configure()`.
|
||||
|
||||
**Why it still matters, and how the consequence changed.** `hasSharedWallet() === false` is a **misconfiguration**, not a degraded mode: the contract makes serving a wallet file and passing its URL and password a deployment requirement, so an app without them cannot sign anyone in. With no `sharedWallet` passed, `ensureIdentity()` **throws**, and `AuthGate` shows its named error panel — loud, which is the point. What must never come back is a silent fallback that renders screens anyway: a session that failed looks exactly like an account that owns nothing.
|
||||
|
||||
## 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.
|
||||
- **Static import = trap.** A static `import` reaching `ngSession.ts` (hence `sharedWallet.ts`) from an entry point that sets the global itself is **hoisted above the assignment** → empty password → the failure mode above, with no JS error at the import site to signal it. The remedy is a **dynamic import** (`await import(...)`) executed after setting the global.
|
||||
- **The real entry point that must get this right**: the frontend served from `src/` (`src/app/frontend.tsx` fetches `/festipod-config.json`, sets the global, then imports `App` dynamically — mechanics in `tech-stack` → [[knowledge_build-pipeline]]). That fetch may be skipped on **one** condition: the global is already set, which only a `build.ts` bundle's `define` does. **Never on an `NODE_ENV` test** — this project's production serves from `src/` exactly like dev, so gating the fetch on "production" is what removed the wallet from the deployed app and left it unable to sign anybody in.
|
||||
- **`@ui` reaches the module too, but harmlessly today.** `screens/index.ts` eagerly imports every screen including `SettingsScreen`, which imports `ngSession.ts` — so any `@ui` test already evaluates `sharedWallet.ts` with the global unset. This does not currently break anything because no `@ui` path calls `ensureIdentity()` (`renderScreen()` bypasses `AuthGate`/`NextGraphProvider` entirely); see `bdd-testing` → [[knowledge_ui-layer]] for the detail and for what would make it stop being harmless.
|
||||
- **Operations**: a server without `FESTIPOD_SHARED_WALLET_PASSWORD` cannot sign anyone in, and it **says so** — `ensureIdentity()` rejects and `AuthGate` renders its named error panel carrying the reason. Verified live on a rejected sign-in: a refusal shows the reason, not a blank page (`bdd-testing` → [[cookbook_live-probe]]). The failure mode still worth fearing is the **silent** one: a promise that never settles either way renders nothing at all and logs nothing — `app-architecture` → [[caveat_boot-unverified-outside-broker]].
|
||||
|
||||
**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.
|
||||
**Verified (2026-08-10)**: capture at evaluation time in `src/shared/utils/sharedWallet.ts`; the `sharedWallet: hasSharedWallet() ? {...} : undefined` branch in `ngSession.ts`'s `configure()` call; the `throw` in `ensureIdentity()` when no `sharedWallet` config is present; `AuthGate`'s `.catch(err => console.error(...))` with no fallback UI.
|
||||
|
||||
@@ -1,41 +0,0 @@
|
||||
---
|
||||
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]]).
|
||||
@@ -1,29 +0,0 @@
|
||||
---
|
||||
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]].
|
||||
@@ -1,32 +0,0 @@
|
||||
---
|
||||
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,26 @@
|
||||
---
|
||||
type: decision
|
||||
summary: Festipod deleted its own access-gate screen (AccessGateScreen, its route, its wallet module) and relies entirely on the SDK's ensureIdentity() to show whatever a first-time device needs to see; cost accepted: the app can no longer test that path itself, from any layer
|
||||
---
|
||||
|
||||
# Decision (2026-08-10): the SDK renders the barrier, Festipod renders none
|
||||
|
||||
## Context
|
||||
|
||||
[[decision_2026-08-10_the-barrier-names-no-identity]] settled *what* the barrier asks (nothing — no identifier). It left open a separate question: *who draws the screen* a device sees while `ensureIdentity()` resolves — a Festipod component still fed by SDK state, or nothing on Festipod's side at all.
|
||||
|
||||
## Decision
|
||||
|
||||
**Festipod renders no access screen of its own.** `AccessGateScreen`, its route, its registration, and `src/modules/auth/sharedWallet.ts` (the wallet re-export whose only consumer it was) are deleted. `src/app/AuthGate.tsx` makes a single unconditional `await ensureIdentity()` and renders nothing until it settles — it no longer couples to `useNextGraph()`'s status, `connect()`, or error state. Whatever a user has to see or do while the wallet loads onto a first-time device belongs to the SDK, which shows it: the library owns that flow end to end and absorbed it precisely so consumer applications can delete theirs (see [[contract_polyfill-surface]] on `ensureIdentity`). `src/shared/utils/sharedWallet.ts` keeps the one surviving copy of the wallet material (file URL, password, import URL) and hands it to the SDK through `configure({ sharedWallet })` — Festipod's only remaining involvement is supplying those three values, never displaying them.
|
||||
|
||||
## Cost accepted
|
||||
|
||||
Festipod now has **no test at all** proving a first-time device can get in. The contract publishes no testid, no DOM contract and no call for a test to interact with the SDK's barrier, so the scenario that used to drive `AccessGateScreen`'s own DOM ("Parcours humain — le testeur importe le portefeuille fourni par Festipod et se connecte", `workshop/multibrowser-harness.feature`) had nothing left to assert and was deleted rather than rewritten. See [[caveat_first-time-entry-untested]] (concept `bdd-testing`). Raised with the provider.
|
||||
|
||||
## Rejected alternative
|
||||
|
||||
**Keep a thin Festipod wrapper around the SDK's state** (a `status`/`error`/`onEnter`-driven screen, still Festipod-rendered). Rejected: it would recreate the exact code the library moved out of consumer applications, for a flow already declared owned by the SDK — a wrapper an application must still write, test and delete at migration is not an absorption, it is the old cost with new labels.
|
||||
|
||||
## Scope
|
||||
|
||||
Distinct from [[decision_2026-08-10_the-barrier-names-no-identity]] (that one settles *what* the barrier asks; this one settles *who draws it*). Current state of the flow: [[knowledge_authentication]].
|
||||
@@ -0,0 +1,34 @@
|
||||
---
|
||||
type: decision
|
||||
summary: The access barrier no longer takes an identifier — the SDK surface stopped letting an application name its own identity, so signing in is one ensureIdentity() call that takes nothing; supersedes the identifier half of the 2026-07-06 and 2026-07-20 arbitrations
|
||||
---
|
||||
|
||||
# Decision (2026-08-10): the barrier names no identity
|
||||
|
||||
## Context
|
||||
|
||||
Earlier arbitrations put an **identifier** at the access barrier: the user typed it in the same act that opened the wallet, and the application handed it to the data layer. They rested on a premise the provider has since withdrawn — that an application **names its own identity**. (Those leaves were deleted on 2026-08-16, with everything else that described the data layer's internals; `git log` has them.)
|
||||
|
||||
The pulled [[contract_polyfill-surface]] removes that premise explicitly. `ensureIdentity()` takes **no identifier**, and the contract states why: naming your own identity is *"the gesture that inverts the model"*, so a "set my identity" call was removed rather than renamed. There is no successor call — the capability is gone, not relocated.
|
||||
|
||||
## Decision
|
||||
|
||||
**Festipod does not name, persist or switch its own identity.** Concretely:
|
||||
|
||||
- The barrier asks for nothing but the wallet: « Entrer » triggers the broker redirect and nothing else.
|
||||
- Signing in is **one await on `ensureIdentity()`**, in `src/app/AuthGate.tsx`, before any screen renders.
|
||||
- All app-side identity machinery is deleted: the identity context, the `?id=` URL param that carried it across the broker round-trip, the localStorage key, the app-level (faux) logout. The only logout left is the **wallet session** one.
|
||||
- **Who the current user is** is no longer derived from an input; it is **the profile document read back in the app's own protected scope**.
|
||||
|
||||
## Consequences accepted with it
|
||||
|
||||
- **Multi-identity on one page is no longer expressible**, and that is correct rather than missing: it was a property of *one wallet hosting several identities*, i.e. emulation scaffolding. Multi-user is exercised as it is lived — several browser contexts, each signing in as itself ([[rule_tests-validate-festipod-not-the-sdk]] in bdd-testing).
|
||||
- **The `@data` layer lost its per-scenario determinism**, which the app used to provide by planting a fresh identity per scenario. The app cannot restore it — choosing which identity comes up is exactly what the surface no longer allows. Open, with the provider: [[caveat_data-scenarios-share-one-wallet]].
|
||||
|
||||
## Rejected alternative
|
||||
|
||||
**Keeping an app-side identifier and mapping it onto the SDK behind the scenes.** Rejected: it would teach the application a model it must unlearn, and it would convert a deliberate provider decision into an app-side workaround nobody revisits ([[rule_app-uses-sdk-surface-only]]).
|
||||
|
||||
## Scope
|
||||
|
||||
Supersedes every earlier arbitration that put an identifier at the barrier. Current state of the flow: [[knowledge_authentication]].
|
||||
@@ -0,0 +1,30 @@
|
||||
---
|
||||
type: decision
|
||||
summary: May-I-write is answered by the list of documents this session owns, and by nothing else — no "may I write this?" call is planned, now or later; the residual window this leaves open is accepted rather than closed
|
||||
---
|
||||
|
||||
# Decision (2026-08-16): write rights are the owned list, permanently
|
||||
|
||||
## Context
|
||||
|
||||
Screens need to know whether this session may **write** an event's document, in order to offer an edit affordance at all. [[contract_polyfill-surface]] leaves exactly one reading of write rights: *"Only a document's owner writes to it. Holding its read key never grants a write"*, and, under non-guarantees, *"No delegated writing. A received key never grants a write, and no call adds a writer to a document."* Owning a document and being able to write it are therefore the same fact, and `storeRegistry.listMyEntityDocs(scope)` is the only call that reports it. No call answers "may I write this?" — the surface publishes none.
|
||||
|
||||
## Decision
|
||||
|
||||
**Ownership, read from the owned-document listing, IS the write right — and that is the permanent answer.** The project owner has ruled that **no capability probe is planned**: Festipod will not ask the provider for a "may I write this?" call, and no future one is being waited on. `listMyEntityDocs('public')` says which events are this session's, and a screen asks nothing else.
|
||||
|
||||
The answer a screen receives is **three-state** — `mine` / `not-mine` / `unknown` — never a boolean. A rejected or not-yet-landed listing means **UNKNOWN**, and the contract is explicit that *"a rejection means 'unknown', never 'absent'"*. Collapsing it into "not mine" is how an owner gets silently told their own event is not theirs.
|
||||
|
||||
## Consequences accepted with it
|
||||
|
||||
- **UNKNOWN renders neither the control nor a greyed twin of it.** A disabled look-alike reads as "edit, broken" and invites a dead click; the slot stays occupied by a distinct pending mark, so an owner is never silently told the event is not theirs. Screen-side rule: `app-architecture` → [[caveat_identity-ids-in-screens]].
|
||||
- **"Not mine" is inferred from ABSENCE**, and absence is not authoritative. The reactive read and the listing are two separate mechanisms, so an event can be on screen a moment before a listing can see it; ruled out in that window, it is only re-examined when some other unclassified event triggers a fresh listing. This residual is **deliberate and stated**, not an oversight.
|
||||
- **The window is not closed**, because closing it needs either a timer — polling, forbidden by `bdd-testing` → [[rule_no-broker-polling]] — or the probe call this decision rules out. Accepting a bounded wrong answer is the arbitration; do not "fix" it with a poll.
|
||||
|
||||
## Rejected alternative
|
||||
|
||||
**Raise the missing probe as a contract gap and wait for it.** Rejected by the project owner: the contract's ownership rule is not an omission, it is the model — a document has one writer, and a list of one's own documents is a complete answer to who that is. Treating it as a gap would keep an affordance permanently provisional against a call that is not coming.
|
||||
|
||||
## Scope
|
||||
|
||||
Applies to every write-affordance question the app asks, not only the event edit pencil. How the answer is derived and where it lives: concept `data-layer` → [[knowledge_write-rights-are-ownership]].
|
||||
@@ -1,24 +1,37 @@
|
||||
---
|
||||
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
|
||||
summary: A user's identity = their NextGraph wallet; every user is authenticated (no anonymous access); the app never names, persists or switches its own identity, and renders no access screen of its own — AuthGate awaits ONE unconditional ensureIdentity() before anything renders
|
||||
last_checked: 2026-08-10
|
||||
---
|
||||
|
||||
# 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.
|
||||
**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/polyfill`): opening your session means opening your wallet.
|
||||
|
||||
## Flow
|
||||
## The flow — one act, no screen of Festipod's own
|
||||
|
||||
- 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`.
|
||||
**Signing in is `src/app/AuthGate.tsx`'s single, unconditional `await ensureIdentity()`.** It fires on mount, with no dependency on `NextGraphContext`'s connection status. **Nothing of the app renders before it resolves**: `ensureIdentity()` settles who we are *and* does the connection work (restoring what others shared with us). A screen mounted earlier would read as an identity that is not yet settled.
|
||||
|
||||
**Festipod renders no access screen of its own.** `AccessGateScreen`, its route and its registration are deleted; whatever a user has to see or do while the SDK resolves — opening the shared wallet, loading it onto a first-time device — is drawn entirely by the SDK. The library owns that flow and absorbed it precisely so consumer applications can delete theirs. See [[decision_2026-08-10_sdk-renders-the-barrier]].
|
||||
|
||||
**The application never names, persists or switches its own identity.** `ensureIdentity()` takes **no identifier**, deliberately, and the contract states that **no other call takes one either** ([[contract_polyfill-surface]]). There is consequently **no** app-side identity state at all: no identity context, no `?id=` URL param, no localStorage identity key, no "set my identity" call. See [[decision_2026-08-10_the-barrier-names-no-identity]].
|
||||
|
||||
**Festipod's only remaining involvement is supplying the wallet material, never displaying it.** `src/shared/utils/sharedWallet.ts` holds the one copy of the file URL, password and import URL this deployment hands out, and passes them to the SDK through `configure({ sharedWallet })` in `src/shared/utils/ngSession.ts` — the contract makes that a deployment requirement. The one hazard left around that module is an evaluation-order trap, [[caveat_shared-wallet-global-before-gate-import]]. Misconfiguration (no password set) makes `ensureIdentity()` throw, and `AuthGate` shows its named error panel instead of any screen.
|
||||
|
||||
**Signing out.** The only logout left is the **wallet session** one (`logoutNg`, offered as « Quitter l'environnement de test » in the settings screen): it stops the shared-wallet session so the next access goes back through the broker. There is no app-level sign-out, because there is no app-level identity to sign out of.
|
||||
|
||||
## Who the current user IS — the identity and the profile are two things
|
||||
|
||||
**The identity** is what `ensureIdentity()` returns, and nothing else derives it. The contract calls it **opaque**: do not parse it, split it, or render it as a readable name. Festipod holds it for display attribution and logging only, and **never passes it to a data-layer call** — no call takes one.
|
||||
|
||||
**The profile** — pseudo, name, initials — is **Festipod's own object**, not something the SDK knows about. "My profile" is the profile **document I own**, resolved from the owned-document listing; a failed listing leaves the answer UNKNOWN, never "none", and the app never presents somebody else's profile as mine. When a person has no profile, one is created at sign-in with placeholders that read as unset — never a plausible name, never anything derived from the identity.
|
||||
|
||||
The two share no id space and there is **no join between them**. The profile value is therefore empty until that document resolves — the mechanics and the hazard that follows live in concept `data-layer`, [[knowledge_context-internals]] and `app-architecture` → [[caveat_identity-ids-in-screens]].
|
||||
|
||||
**Vocabulary.** `username` designates the profile handle `UserProfile.username` and nothing else. `normalizeIdentifier` (`src/shared/utils/identifier.ts`) is a **pure string normalization** of that handle, applied only to `UserProfile.username` — the join between a profile and the person it belongs to, and the name given when sharing a document with a neighbour. It is never applied to the identity: normalising an identity belongs to the data layer, which the contract states outright, and no configuration hook takes it from us. It names no space, account or session.
|
||||
|
||||
## 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 `@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. Since no call takes an identifier, a scenario cannot choose which identity it comes up as: every scenario in a run shares that one wallet, which keeps growing — [[caveat_data-scenarios-share-one-wallet]] (bdd-testing).
|
||||
|
||||
> The authorization model that will build on this identity (bilateral connections, personal data = network, host anonymity) is incubating: [[brief_2026-05-18_authorization-matrix]].
|
||||
|
||||
@@ -1,21 +1,27 @@
|
||||
---
|
||||
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
|
||||
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, and the only thing it declares is which of its own documents it shares with whom
|
||||
last_checked: 2026-08-10
|
||||
---
|
||||
|
||||
# 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`).
|
||||
**Stance:** the app reads data through the ORM subscriptions of the `@ng-eventually/polyfill` 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 one thing the app *does* read is **write rights**, and it reads them to decide what to **offer**, never to enforce: only a document's owner writes it, so the owned-document listing is the whole answer, in three states ([[decision_2026-08-16_write-rights-are-the-owned-list]]). Enforcement stays below — a screen that got the affordance wrong offers a doomed action, it does not open a hole.
|
||||
3. **The relationship between users ("connections") is an application-level notion.** The contract publishes no connection or friendship primitive: it models reading as **key possession**, and giving someone that key is **one act** — `inbox.share(doc, toUser)`, naming the document and the person. The app therefore **owns** its relationship graph (`src/shared/utils/connections.ts`) and, once a link is two-sided, **shares its own protected documents** with that neighbour. It does not delegate the notion of a relationship, only the **enforcement** of the isolation that follows from it.
|
||||
|
||||
What the app declares to the SDK is now **only those shares**: it declares **no identity** ([[decision_2026-08-10_the-barrier-names-no-identity]]), and it **never handles a key or an inbox address** — neither exists in app code. Sharing is also **irreversible**: the contract publishes no revocation, so an act of sharing is permanent ([[contract_polyfill-surface]]).
|
||||
|
||||
## 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**.
|
||||
|
||||
**And never promise anonymity.** The contract guarantees isolation per document; it guarantees **no anonymity** — nothing per reader on a public document, no revocation, and a reference that names a person's document remains comparable wherever it travels. So a Festipod action that circulates such a reference (a sign-up, an invitation, a mention, an index entry) is **pseudonymous at best**: do not label it "anonymous" in the interface, and count the contexts in which you expose the same reference.
|
||||
|
||||
> To check when in doubt: `useNgData` in `FestipodDataContext.tsx` contains no identity-filtering branch — that is intentional, isolation comes from below.
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
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"]
|
||||
keywords: [cucumber, gherkin, bdd, feature, scenario, scénario, step, steps, "@ui", "@data", "@e2e", playwright, broker, harness, wallet, world, hooks, renderHelper, multibrowser, multi-navigateur, "@multibrowser", "@shared-wallet", storageState, "@wip", "@humain"]
|
||||
paths: ["src/modules/*/features/**", "src/modules/*/steps/**", "src/shared/steps/**", "src/shared/support/**", "src/shared/test-harness/**", "cucumber.json"]
|
||||
---
|
||||
|
||||
@@ -10,7 +10,7 @@ triggers:
|
||||
|
||||
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.
|
||||
**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. And [[rule_tests-validate-festipod-not-the-sdk]] — which decides *whether the assertion belongs here at all*.
|
||||
|
||||
## The 3 layers
|
||||
|
||||
@@ -26,12 +26,17 @@ BDD tests written in **Cucumber/Gherkin in French** (`Etant donné`, `Quand`, `A
|
||||
## Links
|
||||
|
||||
- [[rule_test-layer-contracts]] — what to test at each layer (the contract)
|
||||
- [[rule_tests-validate-festipod-not-the-sdk]] — the subject under test is Festipod's behaviour, never the SDK's; no shortcut past the published surface
|
||||
- [[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
|
||||
- [[knowledge_multibrowser-harness]] — several isolated browsers on the shared wallet (storageState injection); the only way multi-user is exercised
|
||||
- [[caveat_data-scenarios-share-one-wallet]] — a scenario cannot choose its identity, so all of them share one wallet that nothing empties: no per-scenario isolation
|
||||
- [[caveat_data-suite-has-no-fixtures]] — **known, not fixed**: the fixture seed writes nothing into a connected wallet, so `@data` scenarios that assumed seeded data have none
|
||||
- [[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
|
||||
- [[caveat_first-time-entry-untested]] — **open**: no test proves a first-time device can get into Festipod any more; the SDK's replacement barrier publishes nothing to test against
|
||||
- [[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`)
|
||||
- [[cookbook_live-probe]] — verifying a flow for real when the suite cannot answer: a throwaway Playwright probe on the real app, what it must collect, and why its findings must be written down the same day
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
---
|
||||
type: caveat
|
||||
summary: A @data scenario cannot choose which identity it comes up as — no published call takes an identifier — so every scenario in a run shares one identity and one physical wallet, which nothing empties. Per-scenario isolation is GONE, and the wallet grows for the whole run.
|
||||
last_checked: 2026-08-10
|
||||
---
|
||||
|
||||
# Pitfall: one wallet, one identity, nothing that empties it
|
||||
|
||||
## What is verified
|
||||
|
||||
**No scenario can name the identity it opens as.** [[contract_polyfill-surface]] is explicit: `ensureIdentity()` takes no identifier, *"and no other call takes one"*. So a scenario gets whatever identity the wallet in `.playwright-profile` resolves to — the same one, every time.
|
||||
|
||||
Machinery from when this was not true is still in the tree and is now **inert**: the `Before` hook mints a unique identifier (`freshScenarioIdentifier`, `src/shared/support/hooks.ts`) and injects it via `addInitScript` into `localStorage['festipod.account.identifier']`, and several steps re-inject it. Nothing consumes that key. **Do not build new setup on it, and do not "repair" it** by making the app read it again — naming your own identity is exactly what the surface refuses.
|
||||
|
||||
## What follows, and gets worse
|
||||
|
||||
**Everything a run writes lands in ONE wallet, and nothing removes it.** There is no per-scenario reset: the old one (`resetDataState()`, a SPARQL DELETE on the anchor graph) was dropped for cost and its helper is gone. So each scenario leaves its documents behind for every later scenario to carry — within a run, and across runs. That is the source of [[caveat_wallet-bloat-hang]].
|
||||
|
||||
The practical signature: hook timeouts on `__testData.ready` that appear **partway through a run** and get worse the longer the profile has lived, **with no console error at all**. Silence is the tell — a wallet that has stopped answering just stops answering.
|
||||
|
||||
So: a scenario failing on **stale data from an earlier scenario** is expected, not a surprise — scenarios are not isolated. A scenario **timing out in `Before`**, especially the fifth one onward, is the wallet, not the assertion. Move the profile aside and re-measure before diagnosing anything else ([[caveat_wallet-bloat-hang]]).
|
||||
|
||||
## What is missing
|
||||
|
||||
A way to start a scenario from a clean slate. The surface publishes no teardown and no throwaway-wallet call, and there is nothing to fake here: it is a **gap to raise with the provider**, stated as the need — *a scenario must be able to begin on an empty space*. Until then, per-scenario determinism is not available at the `@data` layer, and scenarios must be written so they do not depend on it.
|
||||
@@ -0,0 +1,29 @@
|
||||
---
|
||||
type: caveat
|
||||
summary: Known, not fixed — the fixture seed is off for connected wallets, so every @data scenario that assumed seeded events or profiles now runs against whatever the shared wallet happens to hold; "load test data" is a no-op that reports success
|
||||
last_checked: 2026-08-16
|
||||
---
|
||||
|
||||
# Caveat: the `@data` suite lost its fixtures
|
||||
|
||||
## What changed under it
|
||||
|
||||
No fixture is written into a connected wallet any more, by any route — a product decision enforced in one place (`concept data-layer`, [[knowledge_seed-data]]). The `@data` layer did not ask for that and was not adapted to it.
|
||||
|
||||
## What that does to the suite
|
||||
|
||||
The bridge's `loadTestData()` still resolves, and it reports **`seeded: false`** with no documents created. So:
|
||||
|
||||
- Scenarios that **load test data and then assert on it** (`auth/connexion-nextgraph.feature`: loading the fixtures, the "not reloaded twice" idempotence check, "the events have NextGraph identifiers") no longer have anything to assert on. The call succeeds; nothing is written.
|
||||
- Scenarios whose background **assumes a seeded wallet** ("le portefeuille contient des données de test", "un événement {string} existe" — which seeds on demand when the wallet reads empty) now depend entirely on what the shared wallet happens to already hold.
|
||||
- Nothing raises. A no-op seed reports success, which is the failure mode to expect: a green step followed by an assertion that finds nothing.
|
||||
|
||||
## What NOT to do about it
|
||||
|
||||
**Do not re-enable the seed for the tests, and do not add a test-only bypass of the enforcement point.** The switch is enforced at `bootstrapWallet` precisely so no caller can walk around it, and a harness is a caller like any other. **Do not weaken the affected scenarios into something that passes** either.
|
||||
|
||||
The suite needs scenarios that **create what they need through the app's own path** (the same `createEvent` / `joinEvent` a user drives), rather than a background that assumes a pre-populated wallet. That is the direction; it is not done.
|
||||
|
||||
## Related
|
||||
|
||||
This compounds [[caveat_data-scenarios-share-one-wallet]] — scenarios already could not choose their identity or start from a clean slate, and now they cannot furnish that slate either. Both are open.
|
||||
@@ -0,0 +1,29 @@
|
||||
---
|
||||
type: caveat
|
||||
summary: No test proves a first-time device can get into Festipod — the scenario that drove AccessGateScreen's own DOM was deleted with the screen, and the SDK's replacement barrier publishes no testid or contract to write a new one against
|
||||
last_checked: 2026-08-10
|
||||
---
|
||||
|
||||
# Caveat: first-time entry has no test, and none can be written from here
|
||||
|
||||
## What is gone
|
||||
|
||||
`workshop/multibrowser-harness.feature` used to carry « Parcours humain — le testeur importe le portefeuille fourni par Festipod et se connecte »: a fresh browser opened the staging app, `AccessGateScreen` offered the wallet file and password, the file was downloaded **from the screen** (`[data-testid=shared-wallet-download]`), the password checked against the wallet's own (`[data-testid=shared-wallet-password]`), imported on `nextgraph.eu`, then an identifier typed (`[data-testid=identifier-input]`) and « Entrer » clicked — landing on the connected home screen. Every step drove **Festipod's own DOM**.
|
||||
|
||||
`AccessGateScreen` is deleted (concept `app-security`, [[decision_2026-08-10_sdk-renders-the-barrier]]), and with it every testid the scenario asserted on, the steps that drove them (`src/modules/workshop/steps/data/multibrowser.steps.ts`), and the helpers built only for this scenario (`pool.ensureStagingApp`, `pool.importWalletViaFile`, `findE2eWalletFile`, the `dist-staging` build in `hooks.ts`).
|
||||
|
||||
## Why it cannot be rewritten, not just why it was deleted
|
||||
|
||||
The scenario was not migrated to assert against something else, because there is nothing to migrate it to: `ensureIdentity()` (`@ng-eventually/polyfill`) is a plain async function with no published testid, no documented DOM contract, and no call a test could make to drive or observe what it shows a first-time device. [[contract_polyfill-surface]] (concept `data-layer`) states only the call's signature and behaviour, not a UI shape — by design, since that UI is exactly the part the SDK owns and Festipod must not couple to.
|
||||
|
||||
## What is true today
|
||||
|
||||
**No test at all — `@ui`, `@data`, `@e2e`, or `@humain` — proves that a first-time device can sign into Festipod.** The `@shared-wallet` multi-browser scenario ([[knowledge_multibrowser-harness]]) injects the wallet via `storageState`, bypassing the import entirely; every `@data`/`@e2e` scenario runs on a persistent profile that is already signed in before `ensureIdentity()` ever runs ([[caveat_data-scenarios-share-one-wallet]]), so none of them exercises the path a genuinely new user takes either.
|
||||
|
||||
## What would close it
|
||||
|
||||
A test contract published by the SDK for its own barrier (a testid, an event, a promise a test can await) — this is a gap in what Festipod consumes, not in what Festipod tests. Raised with the provider. Until one exists, this path is verified only by hand.
|
||||
|
||||
## Links
|
||||
|
||||
[[knowledge_multibrowser-harness]] — where the deleted scenario lived. Concept `app-architecture` → [[caveat_boot-unverified-outside-broker]] — the related, narrower question of whether the boot even completes outside the broker iframe.
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
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
|
||||
summary: A "fresh page" on the PERSISTENT context never proves broker durability — it re-reads the same profile's IndexedDB; only a non-persistent context spawned from freshBrowser, seeded solely by the BeforeAll storageState, settles broker-vs-local
|
||||
last_checked: 2026-08-10
|
||||
---
|
||||
|
||||
# Pitfall: a "fresh page" is not a cold start (local vs broker)
|
||||
@@ -12,7 +12,7 @@ last_checked: 2026-07-27
|
||||
|
||||
| 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** |
|
||||
| `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 and a full remount of the providers, with nothing carried over in memory | nothing about **broker durability**: the profile **still holds local data** in IndexedDB, so a "fresh" reader may well read **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).
|
||||
@@ -27,24 +27,21 @@ Three conditions, all met in `reconnexion-froide-sans-local.steps.ts`:
|
||||
|
||||
> **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
|
||||
## Reconnection vs isolation — the identifier no longer decides anything
|
||||
|
||||
`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:
|
||||
`isolation.steps.ts` and `reconnexion.steps.ts` set up **the same machinery** (fresh page plus an identifier written into `localStorage['festipod.account.identifier']` via `addInitScript`). That identifier used to be the **only** thing telling them apart — same value re-injected = reconnection, new value = a distinct identity B.
|
||||
|
||||
- **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.
|
||||
**It decides nothing now**: nothing reads that key, so both setups yield the **same** identity. The reconnection sense still holds (a fresh page on the same wallet is genuinely a reconnection); the **isolation** sense is gone — the setup can no longer produce a second identity at all, which is why `event/isolation-deux-identites.feature` is `@wip`. Proving isolation now needs **two genuinely separate browser contexts**, each signing in for itself ([[rule_tests-validate-festipod-not-the-sdk]]). Background: [[caveat_data-scenarios-share-one-wallet]].
|
||||
|
||||
## 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*.
|
||||
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 = a new mount, hence a fresh attempt at reaching a synced state): 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**.
|
||||
> This leaf describes **the test setup that produces a readable verdict**, and nothing else. What a write has to clear to be durable is not this repo's to explain — if a verdict comes back negative, that is a finding to raise with the provider, not a mechanism to write up here.
|
||||
|
||||
## Links
|
||||
|
||||
|
||||
@@ -1,21 +1,37 @@
|
||||
---
|
||||
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
|
||||
summary: The @data suite degrades within a run and across runs, silently — later scenarios time out in Before with nothing in the console. Moving .playwright-profile aside does NOT reset the data (the served wallet file is what holds it), so two "fresh profile" runs measure the same accumulated state; the only real lever is serving a new wallet file, which nothing here does yet.
|
||||
last_checked: 2026-08-16
|
||||
---
|
||||
|
||||
# Pitfall: the test wallet bloats and makes @data reads hang
|
||||
# Pitfall: the test wallet saturates — within a run, and across runs
|
||||
|
||||
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`, …).
|
||||
The persistent Chromium profile `.playwright-profile` (at the root of the working tree) carries the **wallet** the whole `@data`/`@e2e` suite opens. Every scenario reads and writes through it, so anything that slows that wallet down slows everything.
|
||||
|
||||
**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.
|
||||
Two distinct phenomena, and the first is the one that bites today.
|
||||
|
||||
**Workaround.** Move the bloated profile aside and let the auth hook (beforeAll) recreate a fresh one:
|
||||
## Within a single run — the binding constraint
|
||||
|
||||
```bash
|
||||
mv .playwright-profile /tmp/festipod-bloated-$(date +%s)
|
||||
```
|
||||
**Symptom, VERIFIED.** On a **fresh** profile, on an idle machine, per-scenario duration climbs monotonically (observed 7 s → 53 s across the six that pass), then every later scenario dies in the `Before` hook on `frame.waitForFunction` at its 30 s cap. **Silently** — no error, no rejection, nothing in the console. Reproduced twice with identical results (6 of 14 passing, 8 min 34 s and 8 min 37 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.
|
||||
**What it is NOT.** Runs that never exit leave a Chromium and two servers resident (see below), and it was reasonable to suspect that pressure. **Ruled out by measurement**: one of the two runs above happened with four leaked browsers and two leaked servers alive, the other on a cleaned machine — same pass count, same duration. Leaked processes are a real defect and not this cause.
|
||||
|
||||
> 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.
|
||||
**The likely mechanism, INFERRED.** Every scenario in a run writes into the **same wallet**, and nothing removes what it wrote ([[caveat_data-scenarios-share-one-wallet]]) — so each one leaves behind documents that every later scenario carries. That is not something tidying the test code can fix. What would settle it is a reset the surface does not publish (a teardown call, or a throwaway wallet per run): raise it with the provider rather than faking one here.
|
||||
|
||||
**Practical reading.** A `Before` timing out, especially from roughly the sixth scenario onward, is the wallet — not the assertion below it, and not the step definition. Diagnose the run's shape before diagnosing the scenario.
|
||||
|
||||
## Moving the profile aside does NOT reset the data — corrected 2026-08-16
|
||||
|
||||
The reset this leaf used to prescribe (`mv .playwright-profile …`) gives a fresh **browser profile**, not fresh **data**. The suite's data lives in the wallet file the deployment serves (`FESTIPOD_SHARED_WALLET_FILE`, a fixed `.ngw` at the working-copy root), which is the same file on every run and whose state persists outside the profile entirely. Recreating the profile makes the harness build a new broker-side wallet to get *into* the broker; the app then opens the same served wallet as always.
|
||||
|
||||
This matters beyond the inconvenience: two measurements taken "on a fresh profile" are **not** two measurements on fresh data. A pair of identical numbers from them proves reproducibility and nothing about accumulation — a conclusion drawn from exactly that mistake had to be withdrawn.
|
||||
|
||||
**The lever we actually have** is the served wallet file: it is the application's own deployment parameter, not something the provider controls. Serving a new one gives genuinely empty data. Nothing in this repo does that yet.
|
||||
|
||||
Until it does, treat any `@data` number as **relative to whatever that wallet already holds**, and do not compare two runs taken days apart as if they measured the same thing.
|
||||
|
||||
## The leak that makes it worse
|
||||
|
||||
A Cucumber run prints its summary and then **does not exit**, leaving a Chromium and two servers alive (runs observed still resident 2-3 hours after reporting). It does not cause the degradation above, but it fills the machine and forces manual cleanup. Kill the process after reading the summary until the teardown releases what it opens.
|
||||
|
||||
> This caveat describes only what is observable on the test side. Why a saturated wallet stops answering is not this repo's to explain.
|
||||
|
||||
@@ -22,8 +22,15 @@ summary: How to add a BDD scenario/step — a tagged French .feature, steps per
|
||||
```
|
||||
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.
|
||||
6. **⚠️ `waitForFunction` timeout goes in the THIRD slot, not the second.** Playwright's signature is `waitForFunction(pageFunction, arg, options)`. Passing `{ timeout: N }` where `arg` belongs is **not an error**: it is accepted as the page function's *argument*, no options are supplied, and the wait silently uses the **30 s default** while the source reads 5, 10 or 60. When there is no argument to pass, the slot must be filled explicitly:
|
||||
```ts
|
||||
// ❌ await frame.waitForFunction(fn, { timeout: 10000 }) // waits 30 s
|
||||
// ✅ await frame.waitForFunction(fn, undefined, { timeout: 10000 }) // waits 10 s
|
||||
```
|
||||
This had gone unnoticed on **seventeen** calls at once, nine of which meant to wait *less* than the default. It is worth honouring the written number: a wait that is too short fails loudly and names its step, whereas thirty seconds obtained by accident hides a real slowness and makes the source lie. Same family as the pitfall above — both are Playwright argument slots that accept the wrong thing without complaining.
|
||||
|
||||
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`).
|
||||
7. **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.
|
||||
|
||||
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]]).
|
||||
8. **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`).
|
||||
|
||||
9. **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,30 @@
|
||||
---
|
||||
type: cookbook
|
||||
summary: How to verify a flow for real when the suite cannot answer — a throwaway Playwright probe that boots the REAL app in a real browser against the real broker and drives the UI as a user does; what it must collect, and why its findings must land in doctrine the same day.
|
||||
last_checked: 2026-08-16
|
||||
---
|
||||
|
||||
# Driving the real app with a throwaway probe
|
||||
|
||||
A **probe** is a one-off Playwright script, outside Cucumber — no World, no hooks, no fixtures — that boots the **real app** in a real browser against the **real broker** and drives its interface the way a user does. You write it, you run it, you read it, you delete it.
|
||||
|
||||
## When to reach for one
|
||||
|
||||
Before believing a flow works. The create-and-participate flow had been declared *correct by construction* on typecheck, build and reading; the first probe ever run against it found **three defects** none of those could see — all three now fixed, though one left a residual one-connection display lag whose cause sits outside the app ([[caveat_participant-count-one-connection-lag]] in `data-layer`).
|
||||
|
||||
Reach for it when the suite cannot answer the question: the `@data` run dies silently from around its sixth scenario ([[caveat_wallet-bloat-hang]]), its scenarios have no fixtures ([[caveat_data-suite-has-no-fixtures]]), and entry paths are covered by nothing ([[caveat_first-time-entry-untested]], `app-architecture` → [[caveat_boot-unverified-outside-broker]]).
|
||||
|
||||
## Method
|
||||
|
||||
1. **Drive the app's own interface, never a bridge.** A probe that calls into the data context proves the data context. The whole point is the collaboration between the layers, so the only inputs are the ones a user gives — clicks, typing, waiting — and the only outputs are the ones a user sees.
|
||||
2. **Reuse the boot the `@e2e` layer already documents** ([[knowledge_e2e-layer]]) rather than inventing one: the app server on its own port, the broker round-trip, the app in its iframe. Do not build a second way in.
|
||||
3. **Collect `pageerror` and `console` from the first navigation.** The findings that matter surface as a rejection raised *inside a layer you never called* — invisible on screen except as a panel saying something failed.
|
||||
4. **Time the steps you assert on.** "The toast landed after the write" and "1.8 s" are two different findings; the second is what makes a later regression legible.
|
||||
5. **Keep watching after the confirmation, then reconnect.** A step that reports honestly can still leave the flow wrong. Give the state a real interval (minutes, not a tick), then come back through a fresh load — most of what a probe finds lives after the point where a test would have asserted green.
|
||||
6. **Say what state you started from.** A **brand-new origin with a brand-new identity** is what separates a real defect from accumulated wallet state, and a finding reported without it is not yet a finding. Report the run count too (*"3 of 3"*).
|
||||
|
||||
## What a probe is not
|
||||
|
||||
It is **not a regression guard**: nothing re-runs it, and a deleted script protects nothing. Its whole value is converted at the end of the run, into doctrine or a `bug_` leaf, the same day — a probe run that is not written down bought nothing. Recording an observation, mark **VERIFIED** (seen, with the run count) apart from **INFERRED** (the explanation you reached for); a real symptom does not certify its diagnosis.
|
||||
|
||||
> **The lesson that pays for the method: honest steps do not add up to an honest flow.** Every step of the sign-up reports truthfully — the mutation rejects rather than lying, the confirmation follows the write — and the flow as a whole still announces a success it does not obtain. No layer can see that from inside itself; only exercising the whole thing end to end shows it.
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
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
|
||||
summary: The @data layer — Playwright drives Chromium (persistent profile) into the real broker, which loads harness-ng.tsx in an iframe; automated wallet lifecycle, window.__testData bridge, mock fallback; the harness signs in as the app does, per-scenario isolation is ABSENT and the seed now writes nothing
|
||||
last_checked: 2026-08-16
|
||||
---
|
||||
|
||||
# The `@data` layer (real broker)
|
||||
@@ -33,10 +33,10 @@ Cucumber → Playwright (Chromium, persistent profile)
|
||||
- **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.
|
||||
- **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. It reads `appData` through a **live ref** (a captured snapshot goes stale after a seed re-render).
|
||||
- **The harness signs in exactly as the app does.** It mounts `NextGraphProvider > FestipodDataProvider` — **no identity provider, no default login** — and awaits the single `ensureIdentity()` before exposing the bridge, mirroring the order `AuthGate` imposes (concept `app-security`, [[decision_2026-08-10_the-barrier-names-no-identity]]). Nothing may read before it resolves. The low-level probes that used to reach past the app path are **gone**, along with the scenarios whose subject was the SDK rather than Festipod ([[rule_tests-validate-festipod-not-the-sdk]]).
|
||||
- **Identity before writing.** A `Participation` has a mandatory `fp:user`, and what goes in it is **the profile document this session owns** — resolved from the owned-document listing, and created at sign-in when there is none, so it lags behind the public events. Steps wait for `ensureCurrentUser()` before `joinEvent`, then wait (`waitForFunction`) for the participation to be read back. Waiting is no longer optional politeness: `joinEvent` and `leaveEvent` now **reject** when the profile is unresolved, so a step that fires too early fails loudly instead of passing over a write that never happened.
|
||||
- **Per-scenario isolation is currently ABSENT — read [[caveat_data-scenarios-share-one-wallet]] before trusting a green run.** The `Before` hook still mints `this.freshIdentifier` and injects it into `localStorage['festipod.account.identifier']`, and several steps re-inject it, but **nothing reads that key any more**: no published call takes an identifier. Every scenario therefore runs as the same identity on one accumulating wallet. That machinery is inert, not load-bearing — do not build new setup on it, and do not "repair" it by making the app honour the key again.
|
||||
- The old per-scenario reset (`resetDataState()`, a SPARQL DELETE on the anchor graph) was dropped for cost (up to 10 s of the `Before` hook's 60 s budget, already eaten by the broker login) and its helper is gone too.
|
||||
- The **physical** growth of the shared wallet was never bounded by any of this — see [[caveat_wallet-bloat-hang]] (profile to be moved aside when reads start to hang).
|
||||
- **The bridge's `loadTestData` no longer writes anything.** No fixture reaches a connected wallet by any route, and the enforcement point is deliberately un-bypassable — so the call resolves, reports nothing seeded, and every scenario that assumed seeded events or profiles is now running on whatever the shared wallet already holds. Read [[caveat_data-suite-has-no-fixtures]] before diagnosing an empty assertion, and do not re-enable the seed for the tests.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
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
|
||||
summary: The @e2e layer — Playwright boots the REAL app inside the broker iframe, driven through appFrame.evaluate()/locator(); no mock fallback; there is no more access-gate-disable flag, and no scenario has had to drive the SDK's own barrier because the persistent profile comes up already signed in
|
||||
last_checked: 2026-08-10
|
||||
---
|
||||
|
||||
# The `@e2e` layer (real app)
|
||||
@@ -43,21 +43,20 @@ Navigation: `window.history.pushState` plus a `popstate` dispatch (path-based ro
|
||||
|
||||
> **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
|
||||
## Scenario identity, and why no scenario drives the SDK's barrier
|
||||
|
||||
Two settings applied by the `Before` hook in `hooks.ts` govern **every** `@e2e` scenario:
|
||||
The `Before` hook still plants `this.freshIdentifier` — a unique identifier minted per scenario (`freshScenarioIdentifier`) and injected via `addInitScript` into `localStorage['festipod.account.identifier']` on the **persistent** context. **Nothing consumes it**: no published call takes an identifier, so a scenario cannot choose who it opens as. Treat it as inert machinery, not as a determinism lever — [[caveat_data-scenarios-share-one-wallet]].
|
||||
|
||||
- **`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.
|
||||
**There is no more access-gate-disable flag.** `AccessGateScreen` and the `__FESTIPOD_ACCESS_GATE_DISABLED__` global it used to check are both gone. What keeps every `@e2e` scenario from having to drive the SDK's barrier is simply that the **persistent profile already carries an open wallet session** — the automated broker login in the shared `@data`/`@e2e` setup put it there. **Fresh** contexts (multi-browser, see [[knowledge_multibrowser-harness]]) carry no such session, but no scenario left loads the real app through a fresh context — and none could assert against that barrier anyway ([[caveat_first-time-entry-untested]]).
|
||||
|
||||
> **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.
|
||||
> **Impact:** any page opened by hand inside a step (`ctx.newPage()`) does **not** inherit page-level init scripts — `addInitScript` applies only to the pages of the context it was called on.
|
||||
|
||||
## 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.
|
||||
2. **Reopening** — a second page on the **same** persistent context, replanting `this.freshIdentifier` on it (page-level `addInitScript` only covers the page it is called on), then `pool.setupBrokerPage(page, pool.appUrl!)` → new broker login, same identity.
|
||||
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.
|
||||
|
||||
@@ -1,26 +1,22 @@
|
||||
---
|
||||
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
|
||||
summary: Multi-browser harness — isolated contexts spawned from a non-persistent freshBrowser, all carrying the shared wallet by storageState injection (test-only); the scenario that once drove the real access screen end to end is gone with the screen, and nothing replaces it
|
||||
last_checked: 2026-08-10
|
||||
---
|
||||
|
||||
# Multi-browser harness (private-wallet vs shared-wallet)
|
||||
# Multi-browser harness (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 ability of the `@data`/`@e2e` harness to drive **several isolated browsers** within a single scenario. This is also the **only** way multi-user is exercised now: each browser context signs in **as itself**, since nothing lets a single page hold two identities ([[rule_tests-validate-festipod-not-the-sdk]]). That capability is not yet fully used: `isolation-deux-identites.feature` needs exactly this — two real contexts, each connecting for itself — and is currently `@wip` because it still assumes the old single-page identity switch (product-level statement of the gap: concept `functional-domain` → [[knowledge_roadmap]]).
|
||||
|
||||
## The two axes (orthogonal)
|
||||
|
||||
| Axis | What it decides | Expressed by |
|
||||
| Concern | 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) |
|
||||
| **Wallet model** | which wallet a context carries | the `WalletModel` argument (`'own'` \| `'shared'`) |
|
||||
|
||||
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 — one is exercised, one is dormant
|
||||
|
||||
## 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`.
|
||||
- `Étant donné un navigateur "A" avec le wallet partagé` → **shared** model, tag `@shared-wallet`. This is what every scenario uses.
|
||||
- The **own-wallet** model (`'own'`, an empty partition with no wallet) still exists in `spawnContext`, but **no scenario exercises it**: the two `@private-wallet` scenarios were **deleted** because what they proved — Playwright's storage partitioning — is a property of the tooling, not a Festipod behaviour. Keep the machinery, do not re-add scenarios whose subject is the isolation of the tooling.
|
||||
- Umbrella tag `@multibrowser` (whole feature).
|
||||
|
||||
## Architecture (where things live)
|
||||
@@ -34,25 +30,21 @@ Do **not** confuse `@multibrowser` (several browsers) with `@shared-wallet` (sam
|
||||
- **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.
|
||||
> This provisioning is **test-only** — distinct from the **product** mechanism (FILE-assisted import). The shared-wallet scenario using storageState **bypasses the import**, and nothing left validates that import end to end: see [[caveat_first-time-entry-untested]] (concept `bdd-testing`).
|
||||
|
||||
## Human journey — e2e of the product mechanism (green)
|
||||
## No scenario left drives the real app through a fresh context
|
||||
|
||||
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).
|
||||
There used to be a `@humain` scenario here that drove `AccessGateScreen` end to end on a fresh context: download the wallet file from the screen, import it on `nextgraph.eu`, come back, type an identifier, land connected. `AccessGateScreen`, its testids (`shared-wallet-download`, `shared-wallet-password`, `identifier-input`), and every helper built only for that scenario (`pool.ensureStagingApp`, `pool.importWalletViaFile`, `findE2eWalletFile`, the `dist-staging` build) are **deleted** along with the screen itself (concept `app-security`, [[decision_2026-08-10_sdk-renders-the-barrier]]) — nothing of Festipod's own is left to assert against. What this leaves unproven: [[caveat_first-time-entry-untested]].
|
||||
|
||||
- **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 `@shared-wallet` scenario above is unaffected — it never drove the import, and it loads the **harness** (`loadAppInBrowser(name, 'harness')`), not the real app, so it never touched `AccessGateScreen` or `ensureIdentity()` either.
|
||||
|
||||
> **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)
|
||||
## Isolation of the contexts (a property of the harness, not a tested behaviour)
|
||||
|
||||
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).
|
||||
3. That holds on the **local** origin (`127.0.0.1`) and on the **broker origin** `nextgraph.net` **where the wallet actually lives**.
|
||||
|
||||
These three are what makes a cold-start verdict meaningful ([[caveat_reconnexion-froide-local-vs-broker]]). They are **no longer asserted by scenarios** — they were, and those scenarios were deleted: their subject was the tooling.
|
||||
|
||||
## Files
|
||||
|
||||
@@ -68,3 +60,4 @@ The `@humain` scenario validates the REAL wallet distribution flow **end to end,
|
||||
|
||||
- [[knowledge_data-layer-broker]] — the single-browser `@data` layer (persistent profile) that this capability extends.
|
||||
- [[cookbook_add-scenario]] — the `@wip` convention, step pitfalls.
|
||||
- [[caveat_first-time-entry-untested]] — the hole left by the deleted `@humain` scenario.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
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
|
||||
summary: The @ui layer — renderHelper.tsx renders a screen inside LocalDataProvider + happy-dom, assertions run against the rendered DOM; there is no access screen left to render, and a dormant module-evaluation-order trap around sharedWallet.ts survives, currently harmless
|
||||
last_checked: 2026-08-10
|
||||
---
|
||||
|
||||
# The `@ui` layer
|
||||
@@ -10,6 +10,7 @@ last_checked: 2026-07-27
|
||||
|
||||
- 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.
|
||||
- **`@ui` is untouched by the connected-wallet seed switch.** No fixture may be written into a *wallet* any more, but `@ui` renders the fixtures straight into React state through `LocalDataProvider` and writes to nothing — so these fixtures are unchanged and stay the layer's ground ([[caveat_data-suite-has-no-fixtures]] is a `@data` problem only).
|
||||
|
||||
## Good assertion patterns
|
||||
|
||||
@@ -31,17 +32,10 @@ expect(labels.some(t => t.includes("Nom de l'événement *"))).to.be.true;
|
||||
- `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)
|
||||
## ⚠️ No `@ui` module renders an access screen — there is none left to render
|
||||
|
||||
`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").
|
||||
Festipod deleted its own access screen (`AccessGateScreen`) entirely; signing in is now one `ensureIdentity()` call, entirely SDK-owned (concept `app-security`, [[decision_2026-08-10_sdk-renders-the-barrier]]). The two features that used to cover the identifier field and its resolution were **deleted** with the screen — there is nothing left for a `@ui` scenario to render or assert here, and `renderElement()` (the helper `renderHelper.tsx` used to expose for prop-driven components like that screen) is gone too.
|
||||
|
||||
**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.
|
||||
**A dormant trap survives, unrelated to the screen's deletion.** `src/shared/utils/sharedWallet.ts` (the module used to be `src/modules/auth/sharedWallet.ts`, now deleted — the surviving copy moved) still **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**, and it reaches this module regardless of which screen a scenario renders: `screens/index.ts` eagerly imports every screen including `SettingsScreen`, which imports `src/shared/utils/ngSession.ts`, which imports `sharedWallet.ts` — so `hasSharedWallet()` is always `false` under `@ui`. This is currently **harmless**: `configure()` just runs with `sharedWallet: undefined`, and no `@ui` path ever calls `ensureIdentity()` (`renderScreen()` bypasses `AuthGate`/`NextGraphProvider` entirely). It stops being harmless the day a `@ui` scenario does call `ensureIdentity()` — full mechanics: `app-security` → [[caveat_shared-wallet-global-before-gate-import]].
|
||||
|
||||
> 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]].
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
---
|
||||
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.
|
||||
summary: NEVER poll the broker (re-reading in a loop "is it there yet?"). The read surface is push-based and says itself when a scope has finished syncing — `isPending` differs from `isSuccess` with empty `data`. App and tests wait for the push, 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 published read surface is **push-based**: `watchShape` resolves a scope, pushes on every change, and carries its own readiness — `isPending` (still syncing) is distinct from `isSuccess` with empty `data` (synced and genuinely empty). A read is therefore never "query in a loop until it shows up"; the surface already answers *"has it finished?"*, and a loop that re-asks the question is asking something the answer is already available for.
|
||||
|
||||
## The anti-pattern to ban
|
||||
|
||||
@@ -14,14 +14,14 @@ NextGraph is **subscription-based (reactive)**. A read is NOT "query in a loop u
|
||||
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.
|
||||
Any loop that **re-queries the broker** (repeated `authParticipationCount`, `listMyEntityDocs`, `sparqlQuery`) in order to "wait" for data is forbidden: it hides the real mechanism, makes the test brittle (guessed timeout), and contradicts the surface the app is built on. 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**.
|
||||
Wait for the **reactive push**. In practice (app AND test): the reactive state 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.
|
||||
|
||||
- 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.
|
||||
- App: the screen is already reactive (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 surface's own readiness flags, not from an added signal).
|
||||
- Test: **a helper that reliably waits for the push/readiness 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.
|
||||
See also [[caveat_wallet-bloat-hang]] (another source of `@data` flakiness, orthogonal to this one).
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
---
|
||||
type: rule
|
||||
summary: Festipod's tests validate FESTIPOD's behaviour — multi-user included — never the SDK's, and they take NO shortcut past the published surface. Multi-user is exercised the way it is lived, several browser contexts each signing in as itself, since no published call lets one page hold two identities.
|
||||
---
|
||||
|
||||
# The tests validate Festipod, not the SDK — and they take no shortcut
|
||||
|
||||
## The rule
|
||||
|
||||
Stated by the project owner on 2026-08-10, when the app moved onto the pulled [[contract_polyfill-surface]]:
|
||||
|
||||
1. **Festipod is a consumer entirely ignorant of how the SDK is implemented, and its tests may take no shortcut.** No deep import into the package, no reaching for a symbol the contract does not publish, no fixture that reaches past the published surface to get to a state faster.
|
||||
2. **The subject under test is Festipod's behaviour — multi-user included — never the SDK's.** An assertion whose subject is "the capability was learned", "the store served the key", "the inbox holds two deposits" is testing the provider. It does not belong here; if it is worth having, it belongs in the provider's own suite.
|
||||
3. **Multi-user is tested the way it is lived**: several browser contexts, each signing in as itself through `ensureIdentity()`. Each actor obtains what it consumes through the application, under its own session.
|
||||
|
||||
## Why
|
||||
|
||||
The contract publishes no way to name or switch identity: signing in is one call that takes **no identifier**, and *"no other call takes one"*. A session is one user's. So "play two identities on one page" is not a capability that went missing — it is something no published call offers, and a test that manufactured it would be exercising something below the surface and would keep passing while the real behaviour rotted; worse, it would hand one actor's values to another through a shared variable, which is exactly the shape that once hid a real bug behind a green test (see [[multi-actor-tests-obtain-not-receive]]).
|
||||
|
||||
The rule also protects the thing the contract exists for. Every shortcut past the surface is a place the app learns something it must unlearn, and it silently converts a **provider gap** — which should be written down and raised — into an app-side workaround nobody revisits.
|
||||
|
||||
## How to apply
|
||||
|
||||
The tell is mechanical: a test import that is not `@ng-eventually/polyfill`, or an assertion naming an SDK concept rather than something a Festipod user would observe.
|
||||
|
||||
When a scenario cannot be written without a shortcut, that is a finding, not an obstacle to route around: the missing thing is either a **product behaviour Festipod does not expose yet** (build it) or a **gap in the provider's contract** (raise it with the provider and leave the scenario unwritten or `@wip` meanwhile — [[rule_app-uses-sdk-surface-only]]). Deleting a scenario whose subject turns out to be the SDK is the correct outcome, not a loss of coverage.
|
||||
@@ -1,40 +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
|
||||
summary: How Festipod persists its data through the @ng-eventually/polyfill SDK — entities stored as documents placed by scope, direct SPARQL writes + reactive shape 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"]
|
||||
keywords: [nextgraph, "@ng-eventually", polyfill, watchShape, useShape, useShapeQuery, SHEX, shape, scope, "@graph", NURI, inbox, share, sparql, seed, wallet, FestipodData, ngSession, ngGraph, storeRegistry, bootstrap, document, entité, déconnexion, reconnexion]
|
||||
paths: ["src/shared/shapes/**", "src/shared/data/**", "src/shared/context/NextGraphContext.tsx", "src/shared/context/FestipodDataContext.tsx", "src/shared/utils/*", "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**.
|
||||
How Festipod **persists its data** through NextGraph (P2P, local-first, end-to-end encrypted). The data SDK is **`@ng-eventually/polyfill`**: every entity is a **document** placed in its **scope** (public / protected / private). A **write** is direct SPARQL into the entity's own document; a **read** is the SDK's **reactive shape surface** (`watchShape(shape, scope)` → the app's `useShapeQuery` binding), which resolves the scope itself and pushes on change — the app resolves, lists and re-queries nothing. 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 **how Festipod uses the surface**.
|
||||
|
||||
> **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]].
|
||||
> **SDK boundary.** `@ng-eventually/polyfill` is injected **exactly once** through `ngSession.configure(...)`. The pulled contract is the whole of what this repo knows about it: never describe here how the data layer is implemented underneath. See [[rule_app-uses-sdk-surface-only]].
|
||||
|
||||
## Interfaces (one folder per interface, engagement + our declaration)
|
||||
|
||||
Each external interface this concept consumes lives in **its own folder**, holding the provider's engagement (pulled, version-pinned) and — once Festipod actually consumes it — our own declaration beside it.
|
||||
|
||||
- `polyfill-surface/` — [[contract_polyfill-surface]], **the data contract, PULLED from the provider and version-pinned**: the `@ng-eventually/polyfill` surface the app codes against, what it guarantees and what it refuses to promise. The ONLY reference — never open the provider's own sources. Beside it, [[usage_festipod]] — what the app *actually* calls, the conditions it needs, and the frictions measured against the engagement. **Frictions are how a need reaches the provider**: put it there, then signal it out of band.
|
||||
- `indexing-layer/` — [[contract_indexing-layer]], the `@ng-helpers/indexing` engagement, PULLED and pinned on `v1.0.0`: creating an index, depositing references into it, curating it, reading it back. **Nothing consumes it yet** — no declaration is authored beside it, deliberately, since an empty one would say nothing.
|
||||
|
||||
## 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_nextgraph-stack]] — the SHEX shapes, the reactive ORM bindings, `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)
|
||||
- [[knowledge_entities]] — the `Fp*` types and their SHEX shapes; the generated ORM names carry no `Fp` prefix and are aliased at the import sites
|
||||
- [[knowledge_seed-data]] — the fixtures, and the master switch that keeps them out of any connected wallet
|
||||
- [[knowledge_context-internals]] — pitfalls of `FestipodDataContext` (identity vs profile, which profile is mine and when it arrives, no silent success, the legacy participation id space, `participantCount`, local no-op)
|
||||
- [[knowledge_write-rights-are-ownership]] — may I write this? is answered by the owned-document listing, in three states
|
||||
|
||||
## 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
|
||||
- [[rule_document-per-entity]] — every entity gets **its own document** (per scope), never one at store level; access is granted per document, so this is what makes isolation possible
|
||||
- [[rule_app-uses-sdk-surface-only]] — the pulled contract is the only reference; a gap in it is raised with the provider, never worked around here
|
||||
|
||||
## 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)
|
||||
## Pitfalls (read before touching deletions / the participant count)
|
||||
|
||||
- [[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
|
||||
- [[caveat_participant-count-one-connection-lag]] — `participantCount` lags one connection behind the write that produced it; cause is outside the app, no app-side compensation
|
||||
|
||||
> Confidentiality (scope isolation, trusting the SDK): concept `app-security`. Product scopes per entity + discovery: concept `functional-domain`.
|
||||
|
||||
@@ -1,186 +0,0 @@
|
||||
---
|
||||
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. P1–P3 can ship before P4–P6.
|
||||
- **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.
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
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).
|
||||
summary: Target model for sign-ups — a Participation READABLE by everyone (event ref + `active` boolean + a key-less reference to the participant's profile), deposited into the event's inbox; the creator processes the inbox, dedups 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 can read the profile and recognize the person. Supersedes the mutated counter + plaintext userId.
|
||||
---
|
||||
|
||||
# Brief (2026-07-20, revised 2026-07-27) — Set-based sign-ups
|
||||
@@ -9,10 +9,10 @@ summary: Target model for sign-ups — a Participation READABLE by everyone (eve
|
||||
|
||||
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**.
|
||||
1. The participant creates a **Participation** object, **readable by everyone**, holding: the **reference to the event**, an **`active` boolean**, and a **reference to their *protected* profile that carries no key**. **Nothing else** — no description for now.
|
||||
2. They deposit the **Participation's reference** 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.
|
||||
4. They **dedup** (see below) — **without knowing who the participant is**: they hold a name for the profile, not the key to read it.
|
||||
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.
|
||||
@@ -25,47 +25,40 @@ Three properties follow: **anonymous attendance by default** (even the creator c
|
||||
|
||||
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).
|
||||
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 the contract promises no authenticated sender.
|
||||
|
||||
### 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.
|
||||
Without the read key, a **deletion** cannot be told apart from "nothing was ever there". 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.
|
||||
No need for a second document per participation: the participant's **protected profile** already plays that role, and their connections **already** hold the key to read it — that is the very definition of being connected. A third party sees an opaque reference.
|
||||
|
||||
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.)*
|
||||
The advantage over an encrypted field inside the Participation: **adding a connection rewrites nothing**. The profile is shared with a new connection once, durably (and irreversibly — the contract publishes no revocation). An encrypted field would require re-encrypting to N recipients and rewriting the Participation on every new connection.
|
||||
|
||||
## What this rests on — facts established in NextGraph
|
||||
## What this rests on
|
||||
|
||||
Verified by reading `nextgraph-rs`. Details and pointers live on the polyfill side (`docs/readcap-and-nuri-model.md`) — see [[rule_capture-nextgraph-findings]].
|
||||
Two guarantees the contract publishes, and one thing it does not.
|
||||
|
||||
| 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 |
|
||||
| What the model needs | Where it stands |
|
||||
|---|---|
|
||||
| A reference can **name without granting read access** | Published: *"A returned reference carries no key… A reference found inside a document yields a name, not a key."* |
|
||||
| Sharing is **per document, durable and one-way** | Published: `inbox.share(doc, toUser)` — one act, no revocation, nothing per reader on a public document |
|
||||
| **Anyone may deposit, only the owner reads** the inbox | Published: `inbox.postToDocument` / `inbox.read` |
|
||||
| A **dedup key** letting the creator count distinct people without reading them | **NOT published.** See below — this is the open dependency. |
|
||||
|
||||
## The dedup: on exactly what
|
||||
## The dedup: the requirement, and the gap
|
||||
|
||||
**Validated by the PO (2026-07-27).**
|
||||
**The requirement, validated by the PO (2026-07-27)**: the creator must be able to tell two references from the *same* person apart from two references from *different* people, **without ever knowing who** — otherwise the count is not a count of people, and a participant could inflate it by creating several Participations.
|
||||
|
||||
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.**
|
||||
**The contract publishes nothing that does this.** A reference "yields a name, not a key", and no call answers "do these two references belong to one person?". So the mechanism is **not Festipod's to specify**: it is a **gap to raise with the provider**, stated as a need — *a stable, per-person discriminator that can be compared without reading the referenced document*.
|
||||
|
||||
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, whatever the mechanism turns out to be: the Set is **keyed by that discriminator** — at most one reference per person. `Set.size` = the number of distinct people.
|
||||
|
||||
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 reservation that must outlive this brief
|
||||
|
||||
### 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.
|
||||
Any such discriminator is by construction a **pseudonym**: it does not say *who*, but it is comparable across contexts, so whoever collects references can link them. **Never present a Festipod action as "anonymous"** when it circulates one — the contract guarantees no anonymity, and making the Participation public widens the surface on which it is collected. Whether the pseudonym can be rotated, or scoped, is part of the gap above.
|
||||
|
||||
## Trade-offs deliberately accepted (PO, 2026-07-27)
|
||||
|
||||
@@ -74,14 +67,14 @@ In short: this `:v:` is a **stable, permanent pseudonym** for the person, presen
|
||||
- **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 changes vs the current implementation
|
||||
|
||||
What exists today ([[brief_2026-07-06_reactive-reads-and-attendance]]) derives a `participantCount` **mutated in place** from inbox markers carrying the **plaintext `userId`**.
|
||||
What exists today ([[knowledge_context-internals]] §participantCount) derives a `participantCount` **written by the owner** 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.
|
||||
- **Drop the `userId`** from inbox deposits → only the **Participation's reference** remains.
|
||||
- **Count distinct people** through the discriminator above, no longer `userId`s.
|
||||
- **`event.participantCount` goes away**, replaced by `Set.size`.
|
||||
- **Identity resolution** now goes through **reading the profile** (hence through being connected), 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.
|
||||
@@ -89,16 +82,16 @@ Still valid as-is: **reactive reads**, **re-arming on reconnection**, and the **
|
||||
## 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.
|
||||
- **Recognition by connections** (step 7) — and what happens to a broken connection: the contract publishes **no revocation**, so sharing a profile is permanent. 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.
|
||||
- **Blocking — a contract gap**: no published way to **dedup without reading** (see above). Until the contract answers it, coding this model would produce a count that **claims** to be a count of people without being one. Raise it with the provider; do not emulate it here.
|
||||
- **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.
|
||||
The model is **settled** (PO, 2026-07-27). What remains gated is the **implementation**, waiting on the dependency above. **Do not remove the current owner-derived counter** in the meantime ([[knowledge_context-internals]]).
|
||||
|
||||
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`.
|
||||
Links: [[caveat_participation-deletion]], [[rule_document-per-entity]], [[rule_app-uses-sdk-surface-only]], app-security ([[brief_2026-05-18_authorization-matrix]], [[knowledge_trust-model]]).
|
||||
|
||||
@@ -1,17 +0,0 @@
|
||||
---
|
||||
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,37 @@
|
||||
---
|
||||
type: caveat
|
||||
summary: After a sign-up (or a withdrawal) the participantCount a bystander sees needs one connection more than the write itself — written on the first reconnect, displayed on the second. Cause is outside the app, in the layer not notifying you of your own actions; no app-side compensation, deliberately.
|
||||
last_checked: 2026-08-17
|
||||
---
|
||||
|
||||
# Caveat: the participant count lags one connection behind the write that produced it
|
||||
|
||||
In the create-and-participate flow — declare an event, sign up to it — the event's `participantCount` **stays at 0 for the rest of the session**, VERIFIED over two-minute intervals, while the button already reads « ✓ Je participe ». The count starting at 0 on creation is correct and is not this caveat ([[knowledge_context-internals]] §participantCount: no host baseline).
|
||||
|
||||
## The convergence, VERIFIED
|
||||
|
||||
The count does converge, but **one connection later than the write**: the first reconnect after the sign-up still reads 0; the count only reaches the true value on the **second** reconnect. The same one-connection lag applies to a withdrawal — earlier it looked like withdrawal converged immediately while sign-up never did, but that asymmetry was the multi-inbox race below, not a separate mechanism: with one inbox per document, both paths share this same lag.
|
||||
|
||||
## Two measured causes, both about the layer not notifying you of your own actions
|
||||
|
||||
- A deposit you make into an inbox **you watch** produces no push — so the owner's own materializer, sitting on its own inbox, is not woken by its own sign-up.
|
||||
- A write to **your own document** is not re-read by `watchShape` in the writing session — so the materializer's own count write does not come back on the load that made it, only on the one after.
|
||||
|
||||
Both are gaps in [[contract_polyfill-surface]], raised with the provider ([[rule_app-uses-sdk-surface-only]] in this concept) — not something to work around in the app.
|
||||
|
||||
## Why nothing is done about it here
|
||||
|
||||
Any retry or short-interval poll to paper over the gap is exactly what `bdd-testing` → [[rule_no-broker-polling]] forbids. The count is not lost — the materializer fires directly on connection, not only on a push, so it always catches up on the second reconnect — so there is nothing to compensate for beyond the one connection of delay.
|
||||
|
||||
## What this is not
|
||||
|
||||
Not data loss, not a race: [[knowledge_context-internals]] §participantCount describes the concurrency-safety the flow now has (one inbox per document, one materialize cycle at a time, a monotonic guard against a stale write). This caveat is the residual display delay that mechanism does not close, because its cause sits below it.
|
||||
|
||||
## Reproduce
|
||||
|
||||
1. Connect, declare an event (the count shows 0 — correct).
|
||||
2. Sign up to it; the button reaches « ✓ Je participe ».
|
||||
3. Stay on the page and watch the count for a couple of minutes — it stays at 0.
|
||||
4. Reconnect once — still 0. Reconnect a second time — now correct.
|
||||
|
||||
Method: `bdd-testing` → [[cookbook_live-probe]]. Watching *after* the confirmation, over a real interval, and across two reconnects, is what makes this visible at all.
|
||||
@@ -1,17 +0,0 @@
|
||||
---
|
||||
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,33 @@
|
||||
---
|
||||
type: decision
|
||||
summary: Public events become findable through a shared index (@ng-helpers/indexing) rather than a direct read of the public scope, which never actually unioned every user's store; the package's append-only, curation-gated, never-refreshed shape is accepted as-is, with four costs named rather than solved
|
||||
---
|
||||
|
||||
# Decision (2026-08-17): discovery through a shared index
|
||||
|
||||
## Context
|
||||
|
||||
[[knowledge_data-scopes-and-discovery]] (concept `functional-domain`) named "reading the `public` scope" as the primary discovery axis. [[contract_polyfill-surface]] shows why that never delivered cross-user discovery: `storeRegistry` places and lists documents **per session** (`listMyEntityDocs`, `resolveScopeGraph` — both scoped to "this session's own"), and no published call unions every user's public store into one readable set. A declared event was therefore reachable by its own declarer only, and the whole cross-user sign-up flow — the product's premise — was unreachable.
|
||||
|
||||
## Decision
|
||||
|
||||
Festipod adopts **`@ng-helpers/indexing`**, pinned at `1.0.0` ([[contract_indexing-layer]]), as the mechanism that makes a public event findable by someone other than its declarer.
|
||||
|
||||
An index is an ordinary public document that the package builds on top of the polyfill: nothing marks it as one, so Festipod will hardcode its reference in the app's own source. Depositing a reference to an event into the index (`refer`) is open to anyone; only the index's owner turns deposits into visible entries (`curate`); `read` returns those entries ordered by one declared field, compared **as strings**. Festipod indexes on the event's **ISO-8601 start date** specifically because string comparison then sorts entries chronologically for free — that field is being added to the event shape by other work in parallel and is not yet written by any create/update path.
|
||||
|
||||
**No code consumes the index today.** This decision records the arbitration and its accepted costs ahead of the wiring: which identity owns and curates Festipod's index, and where `refer`/`curate`/`read` are called from, are not yet decided.
|
||||
|
||||
## Consequences accepted with it
|
||||
|
||||
- **Curation is a role, not a line of code.** Nothing lands in the index until its owner curates the deposits, and the package schedules no curation run — there is "no timing and no delivery promise" ([[contract_indexing-layer]] → Non-guarantees). Someone, or something, must be relied on to curate; that is an operator commitment this decision takes on, not a gap left for later code to close.
|
||||
- **An event declared before its document could carry the indexed field can never be indexed.** `read` refuses a document that declares no field at all, and curating a reference to an object missing the field reports `skipped: "no-field"` — every run, forever, since a deposit is never consumed and an already-written document does not retroactively gain a field it was not written with. There is no way back into the index for those events short of a fresh index.
|
||||
- **A withdrawn or corrected event stays listed.** The package removes nothing "at any level, ever" — the only answer to a bad entry is a fresh index, not a fix to this one. Whatever eventually reads Festipod's index must tolerate an entry whose object no longer resolves, or resolves to something changed; that tolerance is the app's to build, the package provides none of it.
|
||||
- **An entry's position is frozen at the moment it was curated.** The index never re-reads an already-indexed object, so the value it sorts by is whatever that object held at curation time — a later correction to the real event's start date does not move its entry. `read`'s ordering is faithful to the index, not to the live object.
|
||||
|
||||
## Rejected alternative
|
||||
|
||||
**Wait for the polyfill to publish a cross-store read** — a call that would union every user's `public` scope into one set, restoring the assumption the app started on. Rejected: nothing in [[contract_polyfill-surface]] offers this and none is signalled as coming, and the app cannot leave its central discovery flow unreachable while waiting on a capability nobody has committed to.
|
||||
|
||||
## Scope
|
||||
|
||||
Applies to **event** discovery only — the axis this decision replaces. Meeting-point and profile discovery are unaffected. Product framing and the four costs restated for a domain reader: concept `functional-domain` → [[knowledge_data-scopes-and-discovery]]. Package surface and guarantees: [[contract_indexing-layer]].
|
||||
@@ -0,0 +1,158 @@
|
||||
---
|
||||
type: contract
|
||||
summary: The API @ng-helpers/indexing exposes to an application — creating an index, depositing references into it, curating it, and reading it back
|
||||
pulled_from: https://gitea.reconnexion.apps.gueraud.net/Sylvain/ng-helpers.git/.project/concepts/indexing/indexing-layer/contract_indexing-layer.md
|
||||
pulled_version: 2ce21131575f66af09f28ee109ad712aa41173ae
|
||||
pulled_at: 2026-08-17
|
||||
---
|
||||
|
||||
# contract_indexing-layer — `@ng-helpers/indexing`
|
||||
|
||||
## Scope
|
||||
|
||||
This package builds an **index** on top of NextGraph: an ordinary public document that holds one entry per indexed object, keyed by that object's NURI and carrying its value for a single declared field.
|
||||
|
||||
It covers creating an index, handing an index a reference to an object (open to anyone), the owner resolving those references and adding what it can, and reading the entries back in order.
|
||||
|
||||
It does not cover NextGraph itself — documents, identity, sharing, inboxes, transport — all of which reach it through a port you supply. It does not cover search, filtering, pagination, or querying by anything but the index's own field. It **never removes anything**, from anywhere, and that is a property of the engagement rather than a missing feature.
|
||||
|
||||
### Deployment requirements
|
||||
|
||||
An application using this package must:
|
||||
|
||||
- have a NextGraph session already open under the identity it wants to act as, and build the port from it — `polyfillPort({ sessionId })`, where `sessionId` is what `@ng-eventually/polyfill`'s own `init(…)` hands its callback;
|
||||
- reach a broker, since every operation here is a document read, a document write, or an inbox deposit;
|
||||
- **supply `@ng-eventually/polyfill` itself.** This package declares it a *peer*, not a dependency: the application names it among its own dependencies and decides which copy it gets. That copy must be the very one the application's own code calls, because everything this package does passes through it — and that package requires exactly one instance of itself in an application, for reasons its own contract states.
|
||||
- **hardcode the index's NURI in its own source.** Nothing marks a document as an index; the reference is what makes it one, and it is the only way anyone reaches it.
|
||||
|
||||
One handle is one identity: the port carries a session and no call takes an identifier. Two users mean two handles.
|
||||
|
||||
**Obtaining it.** This package is not published to npm, nor to any other package host, and it is not distributed as built output: its published entry point is TypeScript source, so whatever builds the application is what compiles it, and a toolchain that accepts only JavaScript cannot consume it as it stands. `@ng-eventually/polyfill` is distributed the same way. By which channel the source reaches a given application is agreed with that application rather than fixed here; what this contract fixes is the version you pin and what you must provide alongside it.
|
||||
|
||||
## Surface
|
||||
|
||||
Full typed shape: the package's `types` entry, `@ng-helpers/indexing`. The load-bearing signatures:
|
||||
|
||||
```ts
|
||||
// ── wiring: one handle, one identity ─────────────────────────────────────────
|
||||
export function polyfillPort(options: PolyfillPortOptions): NextGraphPort;
|
||||
export interface PolyfillPortOptions { readonly sessionId: string | number }
|
||||
export function indexing(port: NextGraphPort): Indexing;
|
||||
|
||||
// ── addressing (re-exported so you import them from here) ────────────────────
|
||||
export type Nuri = `did:ng:${string}`;
|
||||
export type NuriLike = Nuri | string;
|
||||
export type { PrincipalId, UnionSubject, NextGraphPort, IncomingDeposit, ObjectResolution };
|
||||
|
||||
// ── everything this package does ─────────────────────────────────────────────
|
||||
export interface Indexing {
|
||||
/** Creates an index in THIS identity's public store and opens its inbox. Any user may.
|
||||
* `field` is the predicate an indexed object must carry, declared once and for good;
|
||||
* an empty or blank one throws. Returns the NURI to hardcode. */
|
||||
createIndex(field: string): Promise<Nuri>;
|
||||
/** Deposits a bare reference into the index's inbox. Open to ANYONE. Nothing lands in
|
||||
* the index until its owner curates. Throws if the index has no inbox. */
|
||||
refer(index: NuriLike, object: NuriLike): Promise<void>;
|
||||
/** OWNER only — resolves the references received and adds what it can. */
|
||||
curate(index: NuriLike): Promise<CurationReport>;
|
||||
/** The entries, ordered by value. Sugar over `readUnion([index])`. */
|
||||
read(index: NuriLike): Promise<IndexEntry[]>;
|
||||
}
|
||||
|
||||
// ── what an index holds ──────────────────────────────────────────────────────
|
||||
export interface IndexEntry { readonly object: Nuri; readonly value: string }
|
||||
export interface IndexDescriptor { readonly field: string }
|
||||
|
||||
// ── what curating reports ────────────────────────────────────────────────────
|
||||
export type CurationOutcome =
|
||||
| { readonly result: "indexed"; readonly object: Nuri; readonly value: string }
|
||||
| { readonly result: "unchanged"; readonly object: Nuri }
|
||||
| { readonly result: "skipped"; readonly object: Nuri; readonly reason: SkipReason }
|
||||
| { readonly result: "unresolved"; readonly object: Nuri; readonly reason: string }
|
||||
| { readonly result: "foreign"; readonly reason: string };
|
||||
export type SkipReason = "no-field" | "several-values" | "self-reference";
|
||||
export interface CurationReport {
|
||||
readonly index: Nuri;
|
||||
readonly outcomes: readonly CurationOutcome[]; // one per deposit, in deposit order
|
||||
}
|
||||
|
||||
// ── what travels from a depositor to a curator ───────────────────────────────
|
||||
export type IndexDeposit = Nuri; // the reference IS the whole payload
|
||||
export function decodeReference(payload: unknown): Nuri | null; // untrusted input
|
||||
|
||||
// ── the IRIs, for a reader going straight to `readUnion` ─────────────────────
|
||||
export const INDEX_FIELD: string; // on the index's own subject: the field it indexes by
|
||||
export const ENTRY_VALUE: string; // on an entry: that object's value for the field
|
||||
```
|
||||
|
||||
## Guarantees
|
||||
|
||||
**An index is an ordinary public document, and nothing marks it as one.** It lives in its creator's public store, so any reader opens it from the reference alone; its creator owns it, and any user may create one.
|
||||
|
||||
**The field is declared once, inside the document, and cannot be changed.** `createIndex` refuses an empty or blank field at the door, because nothing here deletes and an index created on a useless field is useless for good. Declaring it in the document rather than in an application's source is what stops two applications curating the same index on two different fields.
|
||||
|
||||
**`createIndex` opens the index's inbox itself.** Only the owner can, and creation is the one moment the owner is present, so it is not left to a later call to remember.
|
||||
|
||||
**Depositing is open to anyone; writing is the owner's alone.** `refer` is a deposit into the index document's inbox — not a write — so a stranger can contribute to an index they do not own. `curate` reads that inbox and writes the document, and both are refused to anyone but the owner. The deposit is a **bare reference**: it carries no operation, no index reference (the inbox address already identifies the index), and no copy of the indexed value. What the object itself says is what goes in.
|
||||
|
||||
**An index ONLY EVER GROWS.** There is no call that removes an entry, for anyone including the owner, and none is planned. This package cannot express a removal at all. The only answer to "this entry must go" is a fresh index.
|
||||
|
||||
**Curation is convergent and order-independent.** Deposits are never consumed, so every run sees every deposit again; re-applying one re-resolves the reference and lands on the same result. An already-indexed object is skipped outright as `unchanged`. Nothing depends on the order references arrived in.
|
||||
|
||||
**A reference that does not resolve costs nothing and is reported.** It comes back as `unresolved`, nothing is written for it, and nothing already in the index is touched — a later deposit adds it. Every unresolved reference appears in `CurationReport.outcomes`: harmless is not the same as invisible.
|
||||
|
||||
**Reading is per-entry tolerant.** `read` returns entries ordered by value, ties broken on the object NURI, so two readers of the same index always see the same order. Values are compared **as strings** — an index whose field holds ISO-8601 dates therefore comes out in chronological order. A subject that is not a NURI is skipped, never thrown on, and only own properties are read: one stray triple cannot make every real entry unreadable.
|
||||
|
||||
**An entry carrying several values keeps the smallest, deterministically** — which two curation runs racing each other can produce. The entry stays visible and every reader agrees on it.
|
||||
|
||||
**`read` refuses a document that declares no field at all**, rather than answering "an empty index". An unreadable document and an empty one arrive as the same empty result, so an empty answer would be a failure wearing the shape of a fact. Retry before concluding the document is malformed.
|
||||
|
||||
**An index declaring SEVERAL fields refuses to CURATE, loudly and permanently — and stays readable.** Picking one would leave a single list ordered by two different properties, because entries already written are never re-read. Existing entries stay visible and correct; nothing new is added. The refusal cannot be undone, and it says so instead of suggesting a retry.
|
||||
|
||||
**Reading needs nothing from this package.** An application that knows the NURI can call the polyfill's `readUnion([index])` and get the entries as subjects — one per indexed object, keyed by its NURI — plus the index's own subject declaring its field, which `read` drops. `INDEX_FIELD` and `ENTRY_VALUE` are published for exactly that reader.
|
||||
|
||||
**Every inbox payload is untrusted.** Anyone may deposit anything; `decodeReference` returns `null` for everything that is not a reference, and such a payload is reported as `foreign` rather than crashing curation.
|
||||
|
||||
## Non-guarantees
|
||||
|
||||
**No removal, at any level, ever.** Not an oversight and not "not yet": it was deliberately never built. Do not design around a future delete.
|
||||
|
||||
**No refresh.** An already-indexed object is never re-read, so an object whose field value changes later keeps its original value in the index, indefinitely.
|
||||
|
||||
**No private data.** Indexing is limited to objects the curator can open itself. An object the index's owner cannot read is simply `unresolved`.
|
||||
|
||||
**`unresolved` does not tell you why.** Gone, unreadable, and "the read failed" arrive identically and are deliberately not distinguished. Never read it as "the object does not exist".
|
||||
|
||||
**The narrow behaviours are open questions, not promises.** An object carrying nothing for the field is `skipped: "no-field"`; one carrying several values is `skipped: "several-values"`; a raced entry keeps the smallest value. Each is implemented in its narrowest form and reported rather than generalised, and each may change.
|
||||
|
||||
**No stable error text.** What a throw or an `unresolved` reason reads is for a human reading a report. Do not parse it or branch on it.
|
||||
|
||||
**No timing and no delivery promise.** A deposit is not in the index until the owner curates, and nothing here schedules curation. There is no notification, no queue depth, and no ordering between a deposit and a read.
|
||||
|
||||
**The report grows with the inbox.** Since deposits are never retired, `CurationReport.outcomes` has one entry per deposit ever made, not per change.
|
||||
|
||||
**No cross-broker reach.** A NURI resolves for users of the same broker.
|
||||
|
||||
**No depositor authentication or rate limit.** Anyone may deposit any number of payloads into any index's inbox.
|
||||
|
||||
## Change policy
|
||||
|
||||
**Semver, and majors are the normal case.** This layer sits on a polyfill that is itself converging on a NextGraph that does not ship yet, and several of its own behaviours are declared above as open questions. Settling one of them narrows this surface — the major number will move often, and that frequency is the honest signal about this package, not an apology. Refusing to version would not slow the churn down; it would only take away the one tool you have for managing it. Pin a version, upgrade deliberately, and re-pull this contract each time.
|
||||
|
||||
What each level means here, in this package's own terms:
|
||||
|
||||
- **major** — an exported symbol is removed or renamed, **or** an existing call narrows: it now throws where it returned, or reports a state you did not have to handle before. Settling an open question counts, and so does adding a `CurationOutcome` variant or a `SkipReason` — an exhaustive `switch` in your code stops being exhaustive. A signature change a caller must react to counts; one that only accepts more than before does not.
|
||||
- **minor** — a symbol is added and nothing existing moves: a new read helper, a new optional option.
|
||||
- **patch** — a fix that changes neither the exported surface nor anything above under `## Guarantees`, including the text of a throw, which is explicitly disclaimed above.
|
||||
|
||||
**A tag says where it comes from.** A release cut on `main` carries a **full version** (`1.0.0`), and the three rules above govern what changes between two full versions. Work still on a branch carries a **pre-release** of the version it is heading for (`1.0.0-dev.3`), which sorts *below* that version by construction — so you can pin what exists today while the tag itself tells you the surface has not been released and may still move before it is. Between two pre-releases of the same version nothing is promised: re-pull and read this leaf again. When the branch lands, the full version appears alongside; the pre-release keeps resolving, so no reference you pinned is ever withdrawn from under you.
|
||||
|
||||
**The tag is bare — `v1.0.1` — because this repository publishes exactly one engagement**, so there is nothing for a prefix to disambiguate. Should a second one ever ship here, tags take the package name from that point on (`indexing/v…`), because a bare tag stops saying which surface it froze the day two versions move independently. Bare tags already laid stay valid as history.
|
||||
|
||||
`1.0.0` was a baseline, not a claim of maturity: it was the number that made your pin mean something. Nothing was released before it. **It could not be installed, however**, and `1.0.1` supersedes it. `1.0.0` declared `@ng-eventually/polyfill` as a dependency resolved through a path that existed only in one working copy, so every attempt to install it from anywhere else failed outright — not on some operations but at the install itself, which is why no application ever ran it. `1.0.1` declares that package a peer, which the application supplies. Nothing exported moved, which is what makes this a patch and not a major: the only thing that changed for a caller is a requirement it could never have satisfied before, so there is no working arrangement for it to break.
|
||||
|
||||
**`1.0.0` is superseded, not withdrawn.** The tag stays where it is and keeps resolving, because no pinned reference is ever taken away from under you — this contract's policy holds even for a version that never worked. Nothing forces an upgrade; it is simply that an installation pinned there cannot have succeeded, so there is nothing to migrate.
|
||||
|
||||
This engagement is cut on `main`, so `1.0.1` is what you pin, and your `usage_` leaf anchors `against:` on that exact string — `against: @ng-helpers/indexing@1.0.1`. Had you pinned a pre-release, `against:` would carry that string, pre-release suffix included.
|
||||
|
||||
There is no changelog file and no deprecation window: **the sections above are the release note.** A removal or a narrowing lands in `## Surface` and `## Guarantees` in the same version that ships it. Diff this leaf between two pulls — `## Guarantees` and `## Non-guarantees` before `## Surface`, because that is where a narrowing shows up first.
|
||||
@@ -1,98 +1,95 @@
|
||||
---
|
||||
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
|
||||
summary: Internal pitfalls of FestipodDataContext — the signed-in identity and the profile are two unrelated things, "my profile" is the profile document I own, mutations reject instead of succeeding silently, participantCount is derived by the event's owner, and local mode is a no-op
|
||||
last_checked: 2026-08-17
|
||||
---
|
||||
|
||||
# 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)
|
||||
## Identity and profile are TWO things — never join them
|
||||
|
||||
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.
|
||||
**The identity** is what `ensureIdentity()` returns: an opaque value, published to the tree by `src/shared/utils/currentPrincipal.ts` (a module store, not a context — the component that awaits sits *inside* the data provider, so a context it published would be invisible to its own consumer). It is **for display and log attribution only**. It is never parsed, never rendered as a name, never written into an entity, and **never passed to a data-layer call** — placement is named by scope alone, so handing it back would recreate the parameter the surface deliberately removed ([[contract_polyfill-surface]]).
|
||||
|
||||
## TWO id spaces meet — joining a participation to its profile
|
||||
**The profile** — pseudo, name, initials — is **Festipod's own object**, in a document the app creates and writes. `currentUserId` is that document's NURI, the same value as `currentUser?.id`, and the only value a mutation may write into a `Participation`'s `fp:user`.
|
||||
|
||||
**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.
|
||||
**There is no join between the two, and there must not be one.** The identity says nothing about the profile. Never compare the principal to an entity id, and never match it against a profile field to decide who the current user is.
|
||||
|
||||
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.
|
||||
## "My profile" is the profile document I OWN
|
||||
|
||||
**`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.
|
||||
`listMyEntityDocs('protected')` answers *which documents are mine*, and the UserProfile among them is mine. **No field of any profile takes part**: no username comparison, no normalization, no positional pick.
|
||||
|
||||
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.
|
||||
A failed listing is **UNKNOWN, never "none"** — the set stays unresolved, no profile is chosen and none is created, and the failure is retried then said loudly. Reading a rejection as "I own nothing" would create a second profile for someone who already has one.
|
||||
|
||||
> **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.
|
||||
Four outcomes, and *somebody else's profile* is not one of them:
|
||||
|
||||
### Which space each query expects (the `buildQueries` contract)
|
||||
|
||||
| Query | What it expects / returns |
|
||||
| Owned profiles | Answer |
|
||||
|---|---|
|
||||
| `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 |
|
||||
| listing unresolved | UNKNOWN — nothing resolved, nothing created |
|
||||
| none | I have no profile yet → one is created (below) |
|
||||
| exactly one | that is me |
|
||||
| several, none created by this session | the **first by document reference** — stable across reloads, openly arbitrary, warned about once |
|
||||
|
||||
**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]].
|
||||
The last row is a reloaded wallet carrying a fixture seed. The pick carries no meaning, so it is logged as demo data rather than presented as you; **every candidate is a document I own**, which is what separates it from the impersonation that was removed — that one reached for a profile by *name* and could land on a stranger's document. Delete the branch the day a profile is really created and known.
|
||||
|
||||
## Reads = `watchShape` (the SDK surface), no more bespoke machinery
|
||||
> **Two impersonation fallbacks are gone**, including one in `updateProfile` that would have written your pseudo into a stranger's document. Having no profile now resolves to *having no profile*. Do not reintroduce a "pick something plausible" fallback anywhere on this path.
|
||||
|
||||
**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]].
|
||||
## A profile is created at sign-in when there is none
|
||||
|
||||
**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.
|
||||
Gated on **both** the protected read having settled (`isSuccess` — synced-and-empty, not still-syncing) **and** the owned-document set being known, because "I have no profile" is only true when both have answered. Single-shot per session; on failure the guard is released so a later change retries.
|
||||
|
||||
## Dev auto-seed
|
||||
The UserProfile shape makes `name`, `initials` and `username` **mandatory**, so the profile cannot be written empty. The three fields carry **placeholders that read on screen as "not filled in yet"** — never a plausible human name, never a handle, and **never anything derived from the opaque identity**. The user replaces them through `updateProfile`.
|
||||
|
||||
**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]]).
|
||||
## Nothing succeeds in silence
|
||||
|
||||
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`.
|
||||
Mutations on the create/participate path **reject** rather than returning quietly, and the screen's confirmation **follows** the write:
|
||||
|
||||
## `participantCount` — derived and owned by the owner (Option B)
|
||||
- `joinEvent` refuses when no profile of mine is resolved: a `Participation` needs `fp:user`, and one written without it is dropped on read — a sign-up that wrote nothing, threw nothing, and let the screen congratulate the user. It now throws, naming the cause. `leaveEvent` likewise, because withdrawal must be authoritative ([[caveat_participation-deletion]]).
|
||||
- Idempotence is checked **authoritatively against the broker**, not against the reactive set, which can lag a just-written participation. A **failed** count is UNKNOWN and is deliberately *not* swallowed — reading it as zero is exactly how a duplicate gets written.
|
||||
- **The deposit IS the delivery.** A host-facing notification is no longer minted at join time. It used to be written into the *joiner's* own protected scope with `recipient` set to the event — a document the host can never read — and pushed into the joiner's own list, so the joiner saw a "new participant" notice addressed to someone else. Both are gone: `inbox.postToDocument(doc, …)` carries the news, and the owner builds the notification from the deposits it reads on its own event's inbox.
|
||||
- The creator signs up through the **common path** — no owner branch, no special case, the same deposit and the same derived count.
|
||||
|
||||
> ✅ **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]]).
|
||||
## The legacy participation id space — resolved on READ only
|
||||
|
||||
**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.
|
||||
A `Participation` written **today** carries the profile document's NURI in `fp:user`, so the direct join `u.id === userId` matches. Participations written under the **earlier** scheme carry `urn:festipod:user:<normalized-handle>`, which matches nothing directly.
|
||||
|
||||
### Id-form invariant: match on the CANONICAL form of the event id
|
||||
**`resolveParticipantUser`** is the single join point and tries, in order: (1) the direct id match — today's writes, and the demo seed's bare `user-1` space; (2) failing that, strip `USER_PRINCIPAL_PREFIX` and compare the remainder to `normalizeIdentifier(profile.username)`. Never join by direct comparison at a call site: getting it wrong renders every participant as « participant inconnu », which shipped once. `USER_PRINCIPAL_PREFIX` is **read-side only** — nothing mints it any more; it is not a shape to write against. The inbox deposit `uid` (`mint…`) is a third space that takes **no** part: it identifies a deposit for the counter, never a user.
|
||||
|
||||
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.
|
||||
> **Horizon.** The target model drops the plaintext `userId` and resolves identity by reading the profile — [[brief_2026-07-20_attendance-set-model]], gated. The id-space fix is noted there as still valid: do not undo it in anticipation.
|
||||
|
||||
**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.)
|
||||
## Reads = `watchShape`, writes = an optimistic overlay
|
||||
|
||||
**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.
|
||||
Reads go through `useShapeQuery(shape, scope)` — three scoped reads (events/public, profiles/protected, participations/protected) mapped by `shapeAdapters.ts`; `ready` combines their `isSuccess` flags. The app resolves, lists and re-queries nothing ([[rule_document-per-entity]] §Reads).
|
||||
|
||||
## Identity change = a fresh session (isolation)
|
||||
**Immediate visibility of a mutation is a pure optimistic overlay**: `createEvent`/`joinEvent`/`leaveEvent`/profile creation feed `pendingAdd*` / `pendingRemoveIds`; the exposed state is merge(reactive, adds) minus removes, deduped by id. Reconciliation is automatic on push — never a poll ([[rule_no-broker-polling]]).
|
||||
|
||||
> **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.
|
||||
## `participantCount` — derived, and written only by the event's owner
|
||||
|
||||
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`).
|
||||
The counter is **not** incremented by whoever joins: only a document's owner writes to it. The flow is deposit → owner-materialization.
|
||||
|
||||
**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.
|
||||
- A participant writes their **own** participation document (protected), then **deposits** a marker into the event's inbox (`depositRegistration` / `depositLeave`, `src/shared/data/registration.ts`).
|
||||
- The event **owner's** session watches the inboxes of the events it owns (`inbox.watch`, no polling) and **recomputes** `participantCount` on its own event document. It is the counter's only writer, and it reads through `inbox.readSynced` — the synced view — not `inbox.read`.
|
||||
- **One inbox per document, whatever the concurrency.** `openDocumentInbox` (`storeRegistry.ts`) resolves at most once per document per session (`resolveOncePerKey`, `src/shared/utils/`, unit-tested): several callers racing for the same event's inbox — create, materializer, watch wiring, watch callback — all await the same in-flight resolution instead of minting a second address. A rejection is not memoized (unknown, not absent), so a later call genuinely retries.
|
||||
- **One materialize cycle at a time.** The owner's connection trigger and its inbox-push trigger both call into a `createSerialTask` (`src/shared/utils/`, `serialTask.ts`, unit-tested): a cycle in flight absorbs every request that arrives during it into a single follow-up, so two read-derive-write passes never race on the same document. Each cycle carries a monotonic sequence number, and a write only lands if no fresher cycle has already written — a stale cycle can no longer clobber a newer value.
|
||||
- **Derived, not incremented**: `materializeAttendance` computes the set of distinct active sign-ups (deposits deduped by `uid`, minus those cancelled). `participantCount = |active set|`. There is **no host baseline** — an event has no host, the declarer is not required to attend, so the counter starts at **0** on creation and moves only on real sign-ups. Being a pure function of the inbox, a replay is *designed* to converge: no double count, no phantom decrement. The write is guarded so it only fires on a genuine change, and lands in **one** SPARQL statement (`updateEntityField`: `DELETE … INSERT … WHERE`), closing a window where a reader could see the field briefly absent and read zero.
|
||||
- **Owner offline = eventual.** While the owner is disconnected the count does not move for anyone else; nothing is lost. The materializer fires directly on connection, not only on a push, and it never locks in a premature 0.
|
||||
- The counter is an **aggregate**, not the list of named participants — `getEventParticipants` is governed by what the protected scope hands back.
|
||||
|
||||
**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()`.
|
||||
> A live run still shows the count **one connection later** than this design implies — not a race, not data loss, a layer that does not notify you of your own actions: [[caveat_participant-count-one-connection-lag]].
|
||||
|
||||
> **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.
|
||||
Which event a deposit belongs to is matched on the **canonical id-form** — see [[knowledge_write-rights-are-ownership]] §Matching, which governs every event-id comparison in this file.
|
||||
|
||||
**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).
|
||||
## Logging convention — identity-first, and the counter before→after
|
||||
|
||||
## `useShapeQuery` instrumentation — global spinner + timing
|
||||
Every DATA log goes through **`logPrefix`**: `[<currentUserId or principal>][app][data]`. A run often drives several sessions at once and their lines are read side by side, so a line must say *whose* it is. Adding a DATA log means reusing `logPrefix`, not a bare `console.log`.
|
||||
|
||||
`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.
|
||||
Two measurement points are laid down **as a pair**: the owner's materializer logs `participantCount` before → after its write, and the display read logs the value as exposed to the render. Together they separate a **data** problem (never incremented) from a **display** problem (incremented but not re-read). Do not remove one without the other — alone they diagnose nothing.
|
||||
|
||||
## Logging convention — identity-first prefix, and counter before→after
|
||||
## There is no identity switch, and nothing to reset
|
||||
|
||||
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.
|
||||
The app settles its identity once, before anything renders, and offers no way to change it (`app-security` → [[decision_2026-08-10_the-barrier-names-no-identity]]). One page hosts exactly one identity for its whole life, so there is no identity-change reset: no `useEffect([identifier])`, no cap reset, no registry-cache reset. Do not reintroduce a reset for a transition that cannot happen. Cross-identity **isolation** is still a real requirement, but proving it needs two genuinely separate browser contexts (`bdd-testing` → [[rule_tests-validate-festipod-not-the-sdk]]).
|
||||
|
||||
## 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.
|
||||
In local/demo mode (`useLocalData`), `createEvent`/`joinEvent`/`leaveEvent`/`updateEvent` are **no-ops** (a log, no state change) — yet the screens still show a success toast. Misleading UX, unchanged. See [[knowledge_data-modes]].
|
||||
|
||||
@@ -1,19 +1,19 @@
|
||||
---
|
||||
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()
|
||||
summary: Two modes (connected = the @ng-eventually/polyfill 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)
|
||||
1. **Connected** — ORM shapes from the `@ng-eventually/polyfill` 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).
|
||||
- That status is what the data provider below keys on; the app holds no session of its own.
|
||||
|
||||
## FestipodDataContext (`src/shared/context/FestipodDataContext.tsx`)
|
||||
|
||||
@@ -25,4 +25,6 @@ The app has **two modes**, both consumed through the `useFestipodData()` hook:
|
||||
- `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]]).
|
||||
> Mutations are **genuinely persisted** in connected mode: `joinEvent` writes a Participation into its own document and **deposits** into the event's inbox (the deposit is the delivery — no notification is written for the host), `leaveEvent` deletes authoritatively (see [[caveat_participation-deletion]]). Both **reject** rather than returning quietly when they cannot write, and the screen's confirmation follows the write. In local/demo mode they are **no-ops that still show a success toast** — see [[knowledge_context-internals]].
|
||||
>
|
||||
> **Per-call honesty is not flow-level honesty.** Every one of those calls tells the truth about itself; the sign-up flow driven end to end still shows a bystander a stale `participantCount` for one connection longer than the write itself — not a lie, a layer that neither pushes you your own deposit nor re-reads your own write in the same session, see [[caveat_participant-count-one-connection-lag]]. Do not read the paragraph above as "the count updates instantly".
|
||||
|
||||
@@ -1,24 +1,34 @@
|
||||
---
|
||||
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
|
||||
summary: The Fp* app types and their SHEX shapes — Event (no host), UserProfile, Participation, MeetingPoint and Notification are persisted, Friendship stays local-only; the generated ORM names carry NO Fp prefix and are aliased at the import sites
|
||||
last_checked: 2026-08-17
|
||||
---
|
||||
|
||||
# Data entities
|
||||
|
||||
`src/shared/data/types.ts`:
|
||||
`src/shared/data/types.ts` holds the app's own types; `src/shared/shapes/shex/festipodShapes.shex` holds what is actually persisted.
|
||||
|
||||
| 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 |
|
||||
| `FpEventData` | SDK (Event shape) | title, date, startDate, endDate, startTime, endTime, location, distance, participantCount, coverImage |
|
||||
| `FpUserData` | SDK (UserProfile shape) | name, initials, username, role, isPublic |
|
||||
| `FpParticipationData` | SDK (Participation shape) | event + user + isConfirmed |
|
||||
| `FpMeetingPointData` | SDK (MeetingPoint shape) | event, host, title, place, time |
|
||||
| `FpNotificationData` | SDK (Notification shape) | recipient, type, ref, payload, timestamp, isRead |
|
||||
| `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`).
|
||||
**An event has no host.** `hostName`/`hostInitials` are gone from the type and the shape alike — the event is only the anchor, and the host lives one level down on the meeting point (`FpMeetingPointData.hostId`, SHEX `fp:MeetingPoint.host`). See concept `functional-domain`, [[knowledge_actors-and-concepts]].
|
||||
|
||||
`Friendship` has **no** SHEX shape and no persistence — it stays app-TS-only (see [[knowledge_nextgraph-stack]]).
|
||||
**A Notification is no longer created when someone signs up.** The joiner deposits into the event's inbox and the **owner** builds the notification from what it reads there — see [[knowledge_context-internals]] §Nothing succeeds in silence.
|
||||
|
||||
> 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]].
|
||||
`Friendship` has **no** SHEX shape and no persistence — it stays app-TS-only ([[knowledge_nextgraph-stack]]).
|
||||
|
||||
## The generated ORM names carry no `Fp` prefix
|
||||
|
||||
The generator emits `Event`, `UserProfile`, `Participation`, `MeetingPoint`, `Notification` (and `EventShapeType`, `UserProfileShapeType`, …) — **without** the `Fp` prefix earlier bindings had.
|
||||
|
||||
**It cannot be restored at the generator.** The emitted name derives from the shape IRI, and those IRIs are the **persisted RDF classes**: renaming them to regain a prefix would rename the data. So the app **aliases at its import sites** (`… as FpEvent`, `… as FpEventShapeType`) — three of them, in the data context and the two test harnesses. That keeps the downstream names unchanged and, just as importantly, stops the DOM's own `Event` and `Notification` from being shadowed.
|
||||
|
||||
Alias at the import; never rename in the generated files, which `bun run build:orm` overwrites ([[knowledge_nextgraph-stack]]).
|
||||
|
||||
> `themes` is on `FpEventData` and the seed but **not** on the Event shape: a repeated value needing a cardinality decision before it can be one more optional string. Nothing reads it back today, in any mode, so its absence in connected mode is not yet observable — see [[knowledge_nextgraph-stack]] for the shape's actual field list.
|
||||
|
||||
@@ -1,36 +1,32 @@
|
||||
---
|
||||
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
|
||||
summary: The data SDK is @ng-eventually/polyfill, injected exactly once through ngSession.configure; reads go through the reactive useShape/watchShape surface over the festipodShapes SHEX shapes, whose ORM bindings are regenerated with build:orm
|
||||
---
|
||||
|
||||
# Data stack (the `@ng-eventually/client` SDK)
|
||||
# Data stack (SHEX shapes over the `@ng-eventually/polyfill` surface)
|
||||
|
||||
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)
|
||||
```
|
||||
Festipod persists through **`@ng-eventually/polyfill`**. What that surface offers, and what it refuses to promise, is written down in one place: [[contract_polyfill-surface]], pulled into this repo and version-pinned. See [[rule_app-uses-sdk-surface-only]].
|
||||
|
||||
## 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**.
|
||||
- The app **depends on `@ng-eventually/polyfill` only** for data.
|
||||
- It 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 it.
|
||||
- **Never describe here how the data layer is implemented underneath.** This concept covers only **how Festipod uses the surface**.
|
||||
|
||||
## 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
|
||||
- **Event** — title, description, date, startDate, endDate, startTime, endTime, location, distance, participantCount, coverImage, plus an **inbox** field. **No host**: an event is only the anchor ([[knowledge_entities]]). `startDate`/`endDate`/`startTime`/`endTime` are the ISO/HH:MM values the form collects, carried end to end alongside `date` (the display label); they are all optional, so an event written before these fields existed reads as one without them rather than one with blank strings. `themes` is **not** on the shape: a repeated value needing a cardinality decision before it can be one more optional string, and nothing reads it back today. `inbox` is a **vestige** and must stay unused: a deposit **names the document** (`inbox.postToDocument(doc, …)`) and the owner opens its own with `openDocumentInbox(doc)` — writing an address into the entity would put back exactly what the surface removed ([[rule_document-per-entity]]).
|
||||
- **UserProfile** — name, initials, username, role, isPublic. The first three are **mandatory**, which is why a new profile is written with placeholders rather than empty.
|
||||
- **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)
|
||||
- **MeetingPoint** — a meeting point (event, host, title, place, time)
|
||||
- **Notification** — recipient, type, ref, payload, timestamp, isRead
|
||||
|
||||
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.
|
||||
> **Regenerating an unchanged `.shex` reproduces the committed bindings byte-for-byte** — verified by running the generator twice: once before touching the shape, to confirm a no-op diff, then again after the shape edit, so what shows up is the shape change alone. Run it that way on every `.shex` change — it is what keeps an ORM diff reviewable, since nothing separates your edit from a generator side effect if you only ever run it once. And the emitted names carry **no `Fp` prefix**; the app aliases at its import sites instead, because the name derives from the shape IRI and those IRIs are the persisted RDF classes ([[knowledge_entities]]). Never hand-edit the generated files.
|
||||
|
||||
> **The canonical way to read is the reactive hook.** `useShape`/`watchShape`: you subscribe to a shape on a scope, you get the current value, and the component re-renders on every change — subscription/push, never polling; one-shot reads are the exception. The read/reactivity contract is [[contract_polyfill-surface]] and nothing else.
|
||||
|
||||
> `Friendship` has **no** SHEX shape and no persistence — it stays app-TS-only (see [[knowledge_entities]]).
|
||||
|
||||
@@ -1,95 +0,0 @@
|
||||
---
|
||||
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]]).
|
||||
@@ -1,17 +1,26 @@
|
||||
---
|
||||
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
|
||||
summary: seedData.ts holds deterministic fixtures (14 users with CURRENT_USER_ID = 'user-1', 5 events) used by demo mode and the @ui tests; no fixture reaches a CONNECTED wallet by any route any more — bootstrapWallet is the single enforcement point of that master switch
|
||||
last_checked: 2026-08-16
|
||||
---
|
||||
|
||||
# Seed data
|
||||
|
||||
`src/shared/data/seedData.ts` provides **deterministic** fixtures:
|
||||
`src/shared/data/seedData.ts` holds **deterministic** fixtures: 14 users (`CURRENT_USER_ID = 'user-1'`, Marie Dupont), 5 events, participations, meeting points and friendships.
|
||||
|
||||
- 10 users — **Marie Dupont = the current user**, `user-1`
|
||||
- Several events (dates, locations, themes)
|
||||
- Participations, meeting points, friendships
|
||||
- `CURRENT_USER_ID = 'user-1'`
|
||||
## Where they are still used
|
||||
|
||||
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`).
|
||||
- **Demo / disconnected mode** — `LocalDataProvider` reads them straight into React state ([[knowledge_data-modes]]).
|
||||
- **The `@ui` rendering tests** — they render screens against this predictable data (`Marie Dupont`/`@mariedupont` is the current user, `Jean Durand`/`@jeandurand` exists…). 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 »).
|
||||
Neither path writes to a wallet, which is why both are untouched by the switch below.
|
||||
|
||||
## No fixture reaches a CONNECTED wallet, by any route
|
||||
|
||||
A **master switch** — `fixtureSeedEnabled()` in `src/shared/utils/autoSeed.ts` — is **off**, a product decision: no fixture is written into a connected wallet at all, neither by the opt-in automatic seed nor by an explicit "load test data" action.
|
||||
|
||||
**`bootstrapWallet` (`src/shared/utils/ngBootstrap.ts`) is the single enforcement point.** Every route into a wallet funnels through that one function, so the switch cannot be walked around by a screen, a bridge or a test harness; a caller simply gets the ordinary "nothing was seeded" answer, which is exactly true. Call sites consult the switch too, but only so they neither log nor await work that will not happen — the enforcement is not theirs. A unit test fails if a document is created after all.
|
||||
|
||||
**Off, not deleted.** The fixtures and the seeding code stay, because the two paths above need them and neither writes to a wallet. If the switch is ever turned back on, what follows still applies: the seed is **linear in the number of documents** (one document per entity, each a serial round trip), so the connected seed writes only what is needed — all events, a few profiles, and no participations, which the sign-up scenarios create live. Events are the only entities whose inbox is opened at seed time, because events are what people deposit into.
|
||||
|
||||
> **Consequence, live now**: the `@data` suite has lost its fixtures — concept `bdd-testing`, [[caveat_data-suite-has-no-fixtures]].
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
---
|
||||
type: knowledge
|
||||
summary: getEventOwnership answers mine / not-mine / unknown from listMyEntityDocs('public') — owning a document IS being able to write it, the ruling is rebuilt on every listing rather than accumulated, and UNKNOWN is a real third answer callers must handle
|
||||
last_checked: 2026-08-16
|
||||
---
|
||||
|
||||
# Write rights are ownership, read from the owned list
|
||||
|
||||
The app never asks whether it may write a document; it asks whether it **owns** one, because [[contract_polyfill-surface]] makes those the same fact. Only an owner writes, a read key never grants a write, and no call adds a writer — so `listMyEntityDocs('public')` is the whole answer, and no probe call will be added (`app-security` → [[decision_2026-08-16_write-rights-are-the-owned-list]]).
|
||||
|
||||
## The answer is three-state
|
||||
|
||||
`getEventOwnership(eventId)` (`FestipodDataContext`) returns `'mine' | 'not-mine' | 'unknown'`:
|
||||
|
||||
- **`mine`** — the event is in the owned set, either because a listing returned it or because this session created it and claimed it directly. Checked **first**, so a fresh creation is authoritative before any listing has answered and never loses to a stale miss.
|
||||
- **`not-mine`** — a listing has *resolved* and did not return this event, so it was genuinely looked past.
|
||||
- **`unknown`** — everything else: no listing has landed, the listing failed, or the event arrived after the last one. A rejection means UNKNOWN, never "this session owns nothing"; reading it as `not-mine` is how an owner is silently denied their own event.
|
||||
|
||||
**Callers must treat `unknown` as its own case.** It is not a polite `not-mine`, and it is not a boolean waiting to settle.
|
||||
|
||||
## The ruling is REBUILT, never accumulated
|
||||
|
||||
Every listing **re-adjudicates every visible event**: the ruled-out set is recomputed from scratch, so a later listing can overturn an earlier one. An earlier version latched the verdict into a boolean, which denied an owner their own event forever once a single listing had missed it. Do not reintroduce accumulation — add to the owned set, but rebuild the ruled-out set.
|
||||
|
||||
Re-listing is driven by **arrivals, not by time**: while some visible event is neither owned nor ruled out, one more listing is taken; the set then empties and the effect falls silent. That is a push-driven retry, not a poll ([[rule_no-broker-polling]] in `bdd-testing`).
|
||||
|
||||
## Known residual — accepted, do not paper over
|
||||
|
||||
"Not mine" is inferred from **absence**, and the reactive read and the listing are **separate mechanisms**. An event can therefore be on screen a moment before a listing can see it, and it is ruled out for exactly that window; it is re-examined only if some other unclassified event later triggers a listing. Closing the window needs a timer (forbidden) or a capability probe (ruled out). It is left visible and stated on purpose.
|
||||
|
||||
## Matching is on the canonical id-form
|
||||
|
||||
An event's `@id` is its document NURI, and the same event can be reached under two overlays (`:v:<overlay>`). Every ownership comparison — the owned set, the ruled-out set, the lookup — runs on the **canonical** form (`canonicalEventId`, `src/shared/data/registration.ts`): the base repo id with any overlay suffix stripped. **Matching only.** A stripped id is never a write target nor an anchor; the counter is always written to the real owned NURI.
|
||||
|
||||
> Two screen-side consumers, one answer: the control that **offers** the write and the route that **performs** it ask the same question and treat `unknown` the same way — `app-architecture` → [[knowledge_screen-pattern]]. Why the answer is this and will stay this: `app-security` → [[decision_2026-08-16_write-rights-are-the-owned-list]].
|
||||
@@ -0,0 +1,150 @@
|
||||
---
|
||||
type: contract
|
||||
summary: The API @ng-eventually/polyfill exposes to an application — signatures, guaranteed behaviour, and what it does not offer
|
||||
pulled_from: https://gitea.reconnexion.apps.gueraud.net/Reconnexion/ng-eventually.git/.project/concepts/app-contract/contract_polyfill-surface.md
|
||||
pulled_version: a33fb8a21464194227668fd703edd35f685bb3c1
|
||||
pulled_at: 2026-08-16
|
||||
---
|
||||
|
||||
# contract_polyfill-surface — `@ng-eventually/polyfill`
|
||||
|
||||
## Scope
|
||||
|
||||
This package is a polyfill of NextGraph's SDK.
|
||||
|
||||
This package covers placement (creating and listing an application's documents by scope), reading (a document's subjects, one-shot or reactive), sharing a document with a named user, and depositing into inboxes. It does not cover user management, display names, transport, or the operation of a deployment.
|
||||
|
||||
### Deployment requirements
|
||||
|
||||
An application using this package must:
|
||||
|
||||
- serve a wallet file (`.ngw`) from its own bundle, and pass its URL and password to `configure` as `sharedWallet: { fileUrl, password }`;
|
||||
- call `init(…)` — this package's, not the one it passed to `configure` — and then await `ensureIdentity()`, in a browser context, before rendering its interface. `ensureIdentity()` resolves once a session is open, and a session arrives only through `init`: awaited before `init` has been called, it throws and names the call to make first.
|
||||
|
||||
## Surface
|
||||
|
||||
Full typed shape: the package's `types` entry, `@ng-eventually/polyfill`. A type is published only when a published signature uses it. The load-bearing signatures:
|
||||
|
||||
```ts
|
||||
// ── bootstrap ────────────────────────────────────────────────────────────
|
||||
export function configure(c: EventuallyConfig): void;
|
||||
export interface EventuallyConfig {
|
||||
ng: NgLike; // the `ng` object from @ng-org/web
|
||||
useShape: UseShapeLike; // `useShape` from @ng-org/orm
|
||||
sharedWallet?: SharedWalletConfig; // { fileUrl, password, importUrl? }
|
||||
debugAccessLog?: boolean;
|
||||
init?: (...args: any[]) => any;
|
||||
initNg?: (...args: any[]) => any;
|
||||
}
|
||||
|
||||
// ── identity — one await before the application renders ──────────────────
|
||||
export async function ensureIdentity(): Promise<PrincipalId>; // returns who you are
|
||||
|
||||
// ── addressing ───────────────────────────────────────────────────────────
|
||||
export type Nuri = `did:ng:${string}`;
|
||||
export type NuriLike = Nuri | string;
|
||||
export type Scope = "public" | "protected" | "private";
|
||||
|
||||
// ── placement: where an application's documents live ─────────────────────
|
||||
export const storeRegistry: { // no identity parameter — a session is one user's
|
||||
createEntityDoc(scope: Scope): Promise<Nuri>;
|
||||
listMyEntityDocs(scope: Scope): Promise<Nuri[]>;
|
||||
resolveScopeGraph(scope: Scope): Promise<Nuri>;
|
||||
resolveWriteGraph(scope: Scope): Promise<Nuri>;
|
||||
openDocumentInbox(doc: NuriLike): Promise<Nuri>;
|
||||
};
|
||||
|
||||
// ── reading ──────────────────────────────────────────────────────────────
|
||||
export async function readUnion(docs: NuriLike[]): Promise<UnionSubject[]>;
|
||||
export interface UnionSubject { subject: string; graph: Nuri; props: Record<string, string[]> }
|
||||
export function useShape(shapeType: unknown, scope: unknown): unknown; // read-filtered view
|
||||
export function watchShape(query: ShapeQuery): ShapeObservable;
|
||||
export function subscribeDoc(nuri: NuriLike, onChange: (r: DocChange, t: DocChangeType) => void): Unsubscribe;
|
||||
export function subscribeDocs(nuris: NuriLike[], onChange: (r: DocChange, t: DocChangeType) => void): Unsubscribe;
|
||||
|
||||
// ── low-level document / SPARQL primitives ───────────────────────────────
|
||||
export const docs: {
|
||||
// `sessionId` is `string | number` — upstream's own declared type (`Session.session_id`).
|
||||
// It is RELAYED, never converted: the wasm side deserializes a `u64`, and stringifying it
|
||||
// fails for real (`Deserialization error of session_id JsValue("1")`).
|
||||
docCreate(sessionId: string | number, crdt: string, cls: string, dest: string, store?: unknown): Promise<Nuri>;
|
||||
sparqlQuery(sessionId: string | number, query: string, base?: string, anchor?: NuriLike, label?: string): Promise<unknown>;
|
||||
// Returns the commits the update produced, as upstream does (it typed this `void` until
|
||||
// 2026-08-14 while already relaying the value). A caller that ignores it is unaffected.
|
||||
sparqlUpdate(sessionId: string | number, query: string, anchor?: NuriLike, label?: string): Promise<unknown>;
|
||||
};
|
||||
|
||||
// ── inbox: giving to read, and depositing ────────────────────────────────
|
||||
export const inbox: {
|
||||
share(doc: NuriLike, toUser: string): Promise<void>; // give a reader the key
|
||||
post(targetInbox: NuriLike, opts: PostOptions): Promise<void>;
|
||||
postToDocument(doc: NuriLike, opts: PostOptions): Promise<void>;
|
||||
read(targetInbox: NuriLike): Promise<Deposit[]>; // only your own
|
||||
readForDocument(doc: NuriLike): Promise<Deposit[]>;
|
||||
readSynced(targetInbox: NuriLike): Promise<Deposit[]>;
|
||||
processInbox(targetInbox: NuriLike): Promise<Deposit[]>;
|
||||
watch(targetInbox: NuriLike, onDeposits: (d: Deposit[]) => void): () => void;
|
||||
// `materialize` (a second published name for `read`) was REMOVED on 2026-08-14 —
|
||||
// an alias with no call site, and no counterpart upstream. Use `read`.
|
||||
};
|
||||
export interface Deposit { from: PrincipalId | null; payload: unknown; ts: number }
|
||||
|
||||
// ── the wrapped SDK objects ──────────────────────────────────────────────
|
||||
export const ng: NG; // call this instead of the `ng` passed to `configure`
|
||||
// `NG` is upstream's own type (`@ng-org/web`), 88 typed
|
||||
// members; it was `Record<string, any>` until 2026-08-14
|
||||
export function init(...args: any[]): any; // likewise — not the `init` passed to `configure`
|
||||
export function initNg(...args: any[]): any;
|
||||
```
|
||||
|
||||
## Guarantees
|
||||
|
||||
Every entry accepts `NuriLike` and validates at the door; what it returns is a precise `Nuri`. No type guard is published.
|
||||
|
||||
A returned reference carries no key — not `createEntityDoc`, not `listMyEntityDocs`, not `UnionSubject.subject` / `.graph`. A reference found inside a document yields a name, not a key.
|
||||
|
||||
You read a document whose key you hold: you created it, it was shared with you, or it sits in a public store, which serves its read key to whoever asks. No call answers "may I read this?".
|
||||
|
||||
What was shared with you becomes readable after `ensureIdentity()`.
|
||||
|
||||
`readUnion` returns one entry per distinct subject present in a document. `subject` is that subject's IRI exactly as written, and is a `string`, because a subject may be any IRI; `graph` is the document reference you passed in, and is the `Nuri` to hand back to this surface. Properties of different subjects are never merged, and the same subject IRI found in two documents stays two entries, told apart by `graph`. Several objects in one document are allowed. Recommended placement is one document per business entity: access is granted per document.
|
||||
|
||||
`urn:ng-eventually:` is reserved. Triples whose **subject** falls under that prefix are dropped on read and never returned by `readUnion`; every other IRI is returned.
|
||||
|
||||
Only a document's owner writes to it. Holding its read key never grants a write.
|
||||
|
||||
`inbox.share(doc, toUser)` names the document and the person; the recipient calls nothing. It refuses a recipient nobody has signed in as, rather than creating them.
|
||||
|
||||
`inbox.post` refuses a target that is not an inbox; to reach a document's owner, use `inbox.postToDocument(doc, …)`. Anyone may deposit into an inbox; only its owner reads it.
|
||||
|
||||
`ensureIdentity()` settles the identity, completes the connection work it starts, and returns the identity. It takes no identifier, and no other call takes one.
|
||||
|
||||
It resolves **only once that work has actually completed**: if what was shared with you could not be restored, or a queue could not be drained, it throws instead of returning. So a resolved call means everything shared with you is readable — and a rejected one must not be rendered past, since the interface would show an empty account rather than an empty screen.
|
||||
|
||||
`ensureIdentity()` mounts a full-screen barrier on every top-level load, and takes it down itself — past the broker round-trip it never appears. A person who comes back to the page from that round-trip finds the barrier live again, prefilled, and confirming it hands the page over a second time. The application's own page is never reloaded and nothing outside the barrier is touched.
|
||||
|
||||
**The session is the package's, not yours.** You never build one, and no call takes one. Call this package's `init` (not the one you passed to `configure`): it captures the session the SDK delivers to `init`'s callback and keeps it, then calls your callback with that same event untouched — so an application that wants the `session_id` for the `docs` primitives reads it there, and one that does not may pass no callback at all. Identity normalisation is the package's too: `@Alice`, `alice ` and `ALICE` are one person.
|
||||
|
||||
Where a call must first find out whether something already exists — a document's record in its store, a user's inbox — it throws when it could not find out, instead of proceeding as though the answer were "nothing". So `createEntityDoc` throws if the document cannot be recorded in its store, and resolving an inbox throws rather than handing back a second one. **A rejection means "unknown", never "absent"** — retry it or surface it, but do not read it as an empty result.
|
||||
|
||||
## Non-guarantees
|
||||
|
||||
**No display name.** `ensureIdentity()` returns an opaque identifier: do not parse it, split it, or render it as a readable name.
|
||||
|
||||
**No revocation.** `inbox.share` cannot be undone.
|
||||
|
||||
**Nothing per reader on a document in a public store.** No grant, no revocation, no audience list.
|
||||
|
||||
**No delegated writing.** A received key never grants a write, and no call adds a writer to a document.
|
||||
|
||||
**No mailbox model.** Do not build on the raw deposit list.
|
||||
|
||||
**No cross-broker reference.** A returned reference resolves for users of the same broker.
|
||||
|
||||
**No unfiltered read through `useShape`.** Members that yield items are filtered and mutations pass through; anything else throws. A document reached through that view alone, read nowhere else first, does not appear.
|
||||
|
||||
## Change policy
|
||||
|
||||
This surface changes, and shrinks. The package does not offer semantic-version stability.
|
||||
|
||||
Re-pull this contract at every upgrade.
|
||||
@@ -0,0 +1,84 @@
|
||||
---
|
||||
type: usage
|
||||
summary: What the Festipod application actually calls in @ng-eventually/polyfill, the conditions it needs beyond the call list, and the five frictions it has measured against the engagement
|
||||
against: a33fb8a21464194227668fd703edd35f685bb3c1
|
||||
---
|
||||
|
||||
# usage_festipod — Festipod on `@ng-eventually/polyfill`
|
||||
|
||||
Festipod is a mobile-first web application: users create **meeting points** grafted onto public events, and sign up to them. Its entire persistence goes through this package — there is no second data path, no server of its own, and no direct use of the SDK underneath. Two kinds of caller live in this repo and both are declared here: the **application** (screens, data context, write helpers) and the **test harness** (a browser-side bridge the BDD suites drive). The harness is a caller like any other; what it calls is part of what we consume.
|
||||
|
||||
The list below is what we actually call, derived from the call sites, not from what the engagement offers. Anything not listed is offered-but-unused and free to evolve without us.
|
||||
|
||||
## Consumed surface
|
||||
|
||||
### Bootstrap and session
|
||||
|
||||
- `configure(c)` — **one call site**, once per page load, with every published field: `ng`, `useShape`, `init`, `initNg`, `debugAccessLog`, and `sharedWallet: { fileUrl, password, importUrl }`. All three `sharedWallet` fields are supplied, `importUrl` included.
|
||||
- `init(callback, true, [])` — this package's `init`, not the one handed to `configure`. We read `event.session` off the callback and keep it for the whole page.
|
||||
- From that session object we read **two** members: `session_id`, relayed unconverted (`string | number`) into every `docs` call, and **`session.user`**, a string user id passed to `ng.session_stop`. `session.user` reaches us only through the session's open index signature — the engagement names `session_id` and nothing else, so this is a **declared dependency on an unpublished member**: if the session stops carrying `user`, our sign-out breaks.
|
||||
- `initNg(ng, session)` — called from inside that same callback.
|
||||
- `ng` — exactly one member: `ng.session_stop(userId)`. Nothing else of the 88 is touched.
|
||||
- `ensureIdentity()` — awaited before the interface renders (auth gate and app entry), and again by the data context, the principal resolver, and the harness. Its return is treated as opaque: never parsed, split, or rendered.
|
||||
|
||||
### Placement — `storeRegistry`
|
||||
|
||||
- `createEntityDoc(scope)` — one document per entity, on create.
|
||||
- `listMyEntityDocs(scope)` — the owned-document listing; it is also **how we answer "may I write this?"**, since no call answers that question.
|
||||
- `resolveScopeGraph(scope)` — the anchor for every SPARQL call.
|
||||
- `openDocumentInbox(doc)` — through **one app-side wrapper** that collapses concurrent calls for the same document into a single resolution, keyed on the document's canonical form, for the session's lifetime. The raw entry is deliberately not re-exported, so no call site can reach it directly. That wrapper exists only because of friction 1.
|
||||
- `resolveWriteGraph` — **imported and re-exported, never called.** Declared because the import is real: removing the symbol breaks our build even though no behaviour depends on it.
|
||||
|
||||
### Reading
|
||||
|
||||
- `watchShape<T>(shapeType, scope)` — **two positional arguments plus a type parameter** (see friction 5). Wrapped once, in the single React binding that couples the app to the reactive read; every screen reads through that binding. `ShapeObservable`'s `getSnapshot`, `subscribe` and the `ShapeQuery` state it yields are all consumed.
|
||||
- `useShape(shapeType, scope)` — the read-filtered view, in the write path and in the `@data` step definitions.
|
||||
- `UnionSubject` — its `subject`, `graph` and `props` are read and adapted into the app's own entity types.
|
||||
- **Not consumed:** `readUnion`, `subscribeDoc`, `subscribeDocs`.
|
||||
|
||||
### Low-level document / SPARQL primitives
|
||||
|
||||
- `docs.sparqlUpdate(sessionId, query, anchor, label)` — every write the app makes, always anchored, always labelled.
|
||||
- `docs.sparqlQuery(sessionId, query, base, anchor, label)` — authoritative re-reads on the write path (what a reactive read must not be asked to settle) and in the harness.
|
||||
- **Not consumed:** `docs.docCreate` — documents are created through `storeRegistry.createEntityDoc`.
|
||||
|
||||
### Inbox
|
||||
|
||||
- `inbox.share(doc, toUser)` — granting a connection the read of a protected document.
|
||||
- `inbox.postToDocument(doc, { from, payload, ts })` — reaching a document's owner. We pass `from: null` **deliberately** (a sign-up is unnamed unless the host is already a connection), a structured `payload`, and our own `ts`.
|
||||
- `inbox.read(targetInbox)` and `inbox.readSynced(targetInbox)` — the owner materialising its deposits; `readSynced` is what the count path uses, because a read before the sync barrier returns a premature empty.
|
||||
- `inbox.watch(targetInbox, onDeposits)` — subscribed by the owner; the returned unsubscribe is called on teardown.
|
||||
- `inbox.readForDocument(doc)` — harness only.
|
||||
- `Deposit` — **all three fields** consumed: `payload`, `ts` (sorting and identity), `from`.
|
||||
- **Not consumed:** `inbox.post` (we always address a document, never a raw inbox), `inbox.processInbox`.
|
||||
|
||||
### Types imported
|
||||
|
||||
`Nuri`, `NuriLike`, `PrincipalId`, `NG`, `UnionSubject`, `ShapeQuery`, `ShapeObservable`, `DeepSignalSet`.
|
||||
|
||||
Two of these are not underwritten by the engagement document as it stands. `ShapeQuery` and `ShapeObservable` are *named* by `watchShape`'s published signature but never defined there, and we use both **generically** (`ShapeQuery<T>`, `ShapeObservable<T>`) while the published signature is not generic. `DeepSignalSet` is named by **no** published signature at all — the harness imports it on the strength of the package exporting it, which by the engagement's own rule ("a type is published only when a published signature uses it") means we depend on something unpublished.
|
||||
|
||||
## Constraints
|
||||
|
||||
- **The session is the package's, and there is exactly one identity per page.** No call of ours takes an identifier, and we never build a session. Anything that made a page carry two identities would break the whole app, starting with the inbox wrapper's session-long memo.
|
||||
- **`ensureIdentity()` must reject rather than resolve early.** We render the entire interface past that await. A resolve that did not actually finish restoring what was shared would show a signed-in user an empty account — worse than an error — so we rely on the rejection being real and we never render past one.
|
||||
- **The barrier is the package's to mount and take down.** The app renders nothing of its own around sign-in and does not reload its own page; a barrier that leaked past the broker round-trip, or one the app had to dismiss itself, would need app-side machinery we deliberately do not have.
|
||||
- **A rejection means "unknown", never "absent".** Every place we ask whether something exists (a document's record, a document's inbox) treats a throw as unknown and retries or surfaces it. A call that quietly returned "nothing" instead of throwing would make us provision a second set of documents for a user who already has them.
|
||||
- **`sessionId` is relayed, never converted.** We pass through whatever the session carries, `string | number`, because stringifying it fails for real downstream.
|
||||
- **Isolation is the package's, not ours.** No screen and no data helper implements an access check: we place each entity in its scope and trust the scope. If reading stopped being "possession of the key", the app would have no barrier of its own to fall back on.
|
||||
- **Writes must be authoritative on our own document.** A withdrawal must not come back. We re-read with `sparqlQuery` rather than trusting a reactive read to settle it — the reactive surface is a view, not the authority.
|
||||
- **We do not poll the broker.** No retry loop and no short-interval re-read papers over a missing push. So every gap in the reactive path stays visible as a delay in the product, which is why the frictions below matter rather than being absorbed.
|
||||
- **A public store must serve its read key to whoever asks.** Discovery of other people's events is a plain read of the public scope, with no grant step. If that stopped holding, the product's primary discovery axis would be gone.
|
||||
- **One deployment parameter is ours, not yours:** the wallet file we serve and its password. We pass them; the package reads no environment of its own.
|
||||
|
||||
## Frictions
|
||||
|
||||
**1. Resolving a document's inbox is not idempotent under concurrency.** The engagement states that resolving an inbox "throws rather than handing back a second one". It does not. **Four concurrent calls for one document produced three inboxes.** The four are ordinary and unavoidable: creating an event opens its inbox, the materialiser opens it to read, the watch opens it to subscribe, and the watch callback re-enters the materialiser — all within a fraction of a second, none aware of the others. The consequence is silent and total: the owner watches one inbox while sign-ups land in another, and a sign-up is simply never seen. We now funnel every call through one wrapper that de-duplicates in-flight resolutions per document for the session's lifetime. That wrapper is compensation for this friction, not a design of ours, and it only protects a single session — two sessions racing are still unprotected, because nothing on this surface makes the resolution idempotent where it actually lives.
|
||||
|
||||
**2. A deposit into an inbox you watch yourself produces no push. Verified twice.** The depositor's own session never materialises it. This is the normal case for us, not an edge: the host of a meeting point is often also the actor whose deposit must be processed, and its materialiser sits on its own inbox. So the owner is not woken by its own action, and the deposit waits for the next connection.
|
||||
|
||||
**3. A write to your own document is not re-read by the reactive read in the writing session.** Three observations of sixty seconds each: the value stays stale for the whole session. Combined with friction 2, this is what makes a participant count lag **one full connection** behind the write that produced it — the first reconnect after a sign-up still reads the old value, and only the second reads the true one. We compensate nowhere: papering over it would mean polling, which we forbid.
|
||||
|
||||
**4. There is no way to reset a test wallet.** The suite's data lives in the wallet file the deployment serves; nothing on this surface empties it, and recreating the browser profile does not touch it — two runs "on a fresh profile" measure the same accumulated state. Every scenario writes into that wallet and nothing removes what it wrote, so per-scenario duration climbs monotonically within a run and later scenarios die in their setup hook at its cap, silently, with nothing in the console. **The suite degrades to zero passing scenarios.** No reset primitive is published — no teardown call, no throwaway wallet — so there is nothing to call, and we will not fake one by bypassing our own enforcement point. This is the friction that costs us the most: it makes the `@data` layer's results non-reproducible, which is a property of the harness we cannot fix from here.
|
||||
|
||||
**5. The published signature of `watchShape` does not match the call that works.** It is published as `watchShape(query: ShapeQuery): ShapeObservable` — one argument, non-generic, and naming two types (`ShapeQuery`, `ShapeObservable`) that the engagement document never defines. What works, and what every read in the app goes through, is the **two-positional-argument** form with a type parameter: `watchShape<T>(shapeType, scope)`. Lower than the four above — we have a working call — but the document as written cannot be coded against for the single most-used read on the surface.
|
||||
@@ -1,35 +1,25 @@
|
||||
---
|
||||
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".
|
||||
summary: The app codes against the engagement the provider publishes — [[contract_polyfill-surface]], pulled into this repo and version-pinned — and that copy is the ONLY reference. Never open the provider's sources or its node_modules copy; never describe or reason about how the data layer is implemented; what the contract does not answer is a GAP, raised with the provider and never worked around here.
|
||||
---
|
||||
|
||||
# The app uses the SDK surface only — never the polyfill's internals
|
||||
# The app uses the published surface only
|
||||
|
||||
## The rule
|
||||
|
||||
The Festipod app treats `@ng-eventually/client` as a **finished, flawless NextGraph SDK**. Concretely:
|
||||
Festipod is a consumer of **one published contract** and is entirely ignorant of how it is honoured.
|
||||
|
||||
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.
|
||||
1. **The pulled contract is the only reference.** [[contract_polyfill-surface]] is the provider's engagement, version-pinned in this repo. An agent working here reads that file and **never opens the provider's repo or its `node_modules` copy** — not to check a signature, not to settle a doubt.
|
||||
2. **What the contract does not answer is a gap.** Raise it with the provider and leave the app's call site as it is. An app-side workaround is a doctrine violation *even when it works*, because it hard-codes a passing state into code meant to outlive it.
|
||||
3. **No description of how the data layer works underneath**, in code, in comments or in this repo's doctrine. Nothing of the form "we do X because a read behaves like Y". From the app's point of view there is only the contract and what it promises.
|
||||
4. **No shortcut, in the app or in its tests.** Deep imports into the package are refused by its `exports` map, and that refusal is correct — see [[rule_tests-validate-festipod-not-the-sdk]].
|
||||
|
||||
## The contract is the SDK as it SHOULD BE — written down here, in this repo
|
||||
## The surface shrinks, and that is normal
|
||||
|
||||
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.
|
||||
The contract's own change policy states that this surface **changes, and shrinks**, and that it must be re-pulled at every upgrade. A removal is therefore never a regression to absorb defensively — it is work the app deletes.
|
||||
|
||||
**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.
|
||||
## What the app reads through
|
||||
|
||||
## The polyfill's mission: COMPENSATE THE GAP
|
||||
Reactive reads go through `useShapeQuery` (a `useSyncExternalStore` binding over `watchShape`) plus the Fp adapters in `src/shared/data/`. The app mounts no reactivity of its own and keeps no bespoke read model.
|
||||
|
||||
`@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]].
|
||||
What the app **does** rely on is the distinction the observable carries: `isPending` (sync in progress) is not the same as `isSuccess` with empty `data` (synced and genuinely empty). Code that needs "is it really empty?" — the auto-seed gate, the `ready` flag — uses that distinction and nothing finer.
|
||||
|
||||
@@ -1,33 +0,0 @@
|
||||
---
|
||||
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]].
|
||||
@@ -1,48 +1,49 @@
|
||||
---
|
||||
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.
|
||||
summary: Festipod persists EVERY entity as ITS OWN document (through the SDK), placed in its scope — never several entities in a store-level document. The document is the unit of sharing and of rights: access is granted 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.
|
||||
When Festipod creates an entity (event, meeting point, profile, participation, notification), it writes it as **its own document**, through the surface'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.
|
||||
The **document is the unit of sharing and of rights**: the contract states that **access is granted 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.
|
||||
Isolation itself is **entirely the surface's business** ([[knowledge_trust-model]] in the `app-security` concept) — the app carries no access logic; it declares **no identity at all**, only which of its own documents it shares with whom, then trusts whatever it gets back. 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.
|
||||
- At creation time: ask the SDK for **a document for the entity, in its scope** — `createEntityDoc(scope)`. Placement is named by **scope alone** — the session belongs to one user, so there is no identity to pass, and a creation that cannot be recorded **throws** rather than handing back a reference that would read empty forever. Write the entity into it. Do not reuse a document from another scope, nor a store-level document.
|
||||
- **A document only HAS an inbox if its owner opened one** (`openDocumentInbox(doc)`). Festipod opens one on the documents meant to **receive** deposits — its **events** — not on every entity. A deposit then **names the document**: `inbox.postToDocument(doc, …)`, never an address the app resolved itself.
|
||||
- For reads: go through the **reactive shape surface** (see below) — the app names a SHEX shape and a **logical scope**, and the surface resolves that scope to the documents to read, 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".
|
||||
1. `watchShape(shapeType, scope)` returns an **observable** — `{ data, isPending, isSuccess, isError }` — which resolves the scope itself 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`.
|
||||
3. `FestipodDataContext` mounts exactly three of them — events (`public`), profiles (`protected`), participations (`protected`) — and maps the returned `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.
|
||||
**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 surface'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 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).
|
||||
**Writing** an entity happens **directly into its own document** (through the surface'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). The observable symptom when you try: an `add` on an empty scope raises "Set is readonly because scope is empty".
|
||||
|
||||
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`.
|
||||
**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 shape read queries that same anchored default graph. This is the **canonical** form — to be kept for `writeEntity`, `updateEntityField` and `registration.ts`. It is a choice of **simplicity and uniformity**, not a round-trip necessity: an explicit `GRAPH` wrapper anchored to the same document does round-trip, so a "0 entities" symptom is never evidence of a graph mismatch — look at the test wallet first (`bdd-testing/caveat_wallet-bloat-hang`).
|
||||
|
||||
> **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`: one `DELETE … INSERT … WHERE` update, not a DELETE followed by a separate INSERT — the latter left a window where a reader could see the field briefly absent) 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:…`.
|
||||
|
||||
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 value (the entity would be discarded on read). What goes in it is `currentUserId`, i.e. the NURI of **the profile document this session OWNS** — never the identity it signed in as, which is opaque and never written into an entity ([[decision_2026-08-10_the-barrier-names-no-identity]] in `app-security`). It therefore **arrives late**: a mutation fired before that document resolves must **reject** rather than write, which is what `joinEvent` and `leaveEvent` do — they throw, and the screen's confirmation follows the write. See [[knowledge_context-internals]].
|
||||
|
||||
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.
|
||||
Sharing keys off a different space: `inbox.share(doc, toUser)` names a **person**, so bilateral connections (`declareConnections`) are declared with **normalized profile handles**, not document NURIs — the data context maps each peer IRI to that key before declaring, and skips peers whose profile it cannot read (they cannot be named).
|
||||
|
||||
@@ -1,42 +0,0 @@
|
||||
---
|
||||
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]].
|
||||
@@ -13,7 +13,7 @@ Vocabulary reference. Every actor is a specialization of an authenticated **user
|
||||
|---|---|
|
||||
| **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. |
|
||||
| **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"** — and this now holds all the way down: the event carries no host field at all, in the shape or in the app type (`data-layer` → [[knowledge_entities]]). 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 signs up and withdraws through the same path as anyone else. The declarer is nonetheless the event document's **owner**, hence its only writer (`app-security` → [[decision_2026-08-16_write-rights-are-the-owned-list]]). The "host" is an actor at the **meeting point** level (next row), never 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. |
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
---
|
||||
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
|
||||
summary: The product model of confidentiality and discovery — every entity lives in the SCOPE matching who must read it; other users' events are found through a shared index, not by reading the public scope
|
||||
---
|
||||
|
||||
# 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**.
|
||||
The **product** model of who sees what, and of how events are found. This is **domain**: the technical *how* is the `@ng-eventually/polyfill` data SDK's business — the app only states **the business intent**.
|
||||
|
||||
## Three scopes per piece of data
|
||||
|
||||
@@ -27,17 +27,26 @@ Guiding principle: **the "public" side (meeting point, event) and the "personal"
|
||||
- **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`).
|
||||
Festipod **places each entity in 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…").
|
||||
Reading the `public` scope only ever returns **this session's own** public documents — there is no call that unions every user's public store (concept `data-layer`, [[contract_polyfill-surface]]). A declared event was therefore reachable by its declarer alone, which made the whole cross-user sign-up flow — the product's premise — unreachable.
|
||||
|
||||
> **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.
|
||||
**A user discovers events they did not create through a shared index**: an ordinary public document, indistinguishable from any other, that the app reaches by a reference it hardcodes. Anyone may deposit a reference to their event into it; only the index's owner curates those deposits into visible entries, ordered by the event's start date. This is the **primary** discovery axis, settled as [[decision_2026-08-17_discovery-through-a-shared-index]] (concept `data-layer`) — **no code consumes the index yet.** A **secondary**, relational axis stays layered on top: the connections' *protected* participations ("my friends are attending…").
|
||||
|
||||
Four costs come with it, accepted rather than solved: an event becomes findable only once **someone curates** the index, on no fixed schedule — curation is an operator role, not a feature that runs itself; an event declared before its document could carry the field the index reads never becomes findable through it, permanently; a withdrawn or later-corrected event **stays listed** — nothing here removes an entry, so a reader of the index must tolerate a reference that no longer resolves, or resolves to something changed; and an event's position in the list is **frozen at the moment it was curated** — correcting its date afterwards does not move it. Full mechanics and the rejected alternative: [[decision_2026-08-17_discovery-through-a-shared-index]].
|
||||
|
||||
> **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, **unnamed otherwise**. This "identified if known, unnamed otherwise" falls out of scope placement — the host can read the sign-up, but not the *protected* profile it points at unless they are connected. The app states the intent; it implements no filter of its own.
|
||||
|
||||
## Settled: the event write model is OWNER-ONLY
|
||||
|
||||
Who may update a declared event was long open — owner, wiki, or immutable. It is **owner: the declarer alone**, and not as a free product choice. The data model leaves no other reading: only a document's owner writes it, a read key never grants a write, and no call adds a writer, so "wiki" is not expressible at all. The declarer's own listing of their documents is what says which events are theirs, permanently (`app-security` → [[decision_2026-08-16_write-rights-are-the-owned-list]]).
|
||||
|
||||
This constrains **deduplication**: two declarations of the same real-world event cannot be merged by one declarer editing the other's document ([[brief_2026-06-15_event-deduplication]]).
|
||||
|
||||
## 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**.
|
||||
|
||||
|
||||
@@ -15,9 +15,13 @@ summary: What is implemented today (event + meeting point lifecycle, profiles, c
|
||||
- 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.
|
||||
> **Signing up is wired step by step, and the count a bystander sees lags the flow by one connection.** Each step is honest: `joinEvent` persists a Participation and deposits into the event's inbox, where its owner reads it; `leaveEvent` deletes the Participation authoritatively (concept `data-layer`, [[caveat_participation-deletion]]); neither succeeds in silence, and the confirmation the user sees follows the write. Driven end to end in a real browser, the signer's own confirmation is instant and correct, but the `participantCount` a bystander sees stays at 0 through the session and the first reconnect, only catching up on the second — a known layer limitation, not data loss (concept `data-layer`, [[caveat_participant-count-one-connection-lag]]). Nothing short of exercising the whole thing end to end shows this kind of gap (concept `bdd-testing`, [[cookbook_live-probe]]). Treat the bullet above as *screens reachable*, not as an instantly-consistent journey. **Public discovery does not work yet**: a user sees another user's public event only once a shared index exists and is curated (concept `data-layer`, [[decision_2026-08-17_discovery-through-a-shared-index]]; concept `functional-domain`, [[knowledge_data-scopes-and-discovery]]) — no code consumes it today.
|
||||
|
||||
> **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`).
|
||||
> **Updating an event is reserved to its declarer**, and the interface says so rather than discovering it late: the edit route is decided by ownership, and the confirmation follows the write instead of preceding it (concept `app-architecture`, [[knowledge_screen-pattern]]). Owner-only is not a policy choice here — it is the only reading the data model allows ([[knowledge_data-scopes-and-discovery]]).
|
||||
|
||||
> **The reconnection promise is guarded, not assumed.** "I come back later and my events and sign-ups are still there" is a product promise like any other, and it is the one whose failure would be least visible — nothing on screen distinguishes "you have nothing" from "it did not come back". The `src/modules/event/features/reconnexion-*.feature` scenarios of the `event` module are its non-regression guard; keep them meaningful, and read [[caveat_reconnexion-froide-local-vs-broker]] (concept `bdd-testing`) before trusting one of them green, because the natural setup proves less than it looks.
|
||||
|
||||
> **Product reservation — a user cannot be shown two identities on one device.** Signing in is one act with no choice attached: the user does not name, pick or switch an identity, and there is no in-app sign-out from one identity into another (concept `app-security`, [[decision_2026-08-10_the-barrier-names-no-identity]]). One session = one person, for the life of the page. Consequence for the domain: **do not design a flow that asks "who are you signing in as"**, nor an account-switcher, nor a demo that plays two people side by side on one device — none of them is expressible. Two people means two devices (or two browser contexts). The **isolation between two identities** is still a real requirement, but it is currently unproven at the `@data` layer for the same reason (concept `bdd-testing`).
|
||||
|
||||
## Identified evolutions (not implemented)
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ 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/**"]
|
||||
paths: ["build.ts", "package.json", "pnpm-lock.yaml", "Dockerfile", ".env.example", "bunfig.toml", "tsconfig.json", "src/index.ts", "src/index.html", ".storybook/**", "scripts/**"]
|
||||
---
|
||||
|
||||
# Tech stack
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
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
|
||||
last_checked: 2026-08-10
|
||||
---
|
||||
|
||||
# Firefox LNA blocks the broker's app iframe in local dev
|
||||
@@ -16,7 +16,7 @@ In local dev, the app runs INSIDE the hosted broker's iframe (`nextgraph.eu`/`ne
|
||||
`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.
|
||||
- **The top level loads just fine**: navigating directly to `https://festipod.localhost:1355` 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)
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
---
|
||||
type: caveat
|
||||
summary: A running `bun run dev` never picks up a refreshed data-layer package — VERIFIED, not even across a real rebuild (new bundle hash, still the stale dependency). Only a restart serves the fresh copy; suspect a stale server before suspecting the code.
|
||||
last_checked: 2026-08-16
|
||||
---
|
||||
|
||||
# Pitfall: refreshing the data-layer package never reaches a running dev server, not even across a rebuild
|
||||
|
||||
`pnpm run overlay:polyfill` (or `overlay:indexing`, for the other provider) overlays the local checkout into `node_modules/<package>/` as real files, and keeps them current. **That is all it does.** A `bun run dev` already running goes on serving the package it loaded at startup, however many times the overlay is rewritten underneath it, and however many rebuilds happen in between.
|
||||
|
||||
**VERIFIED, controlled sandbox test with this project's own bun.** A dependency resolving to copy A, overlaid with copy B: the running server still serves A at +3 s and +13 s after the overlay. An edit to **application source** then triggers a genuine rebuild — a new bundle hash confirms it — and the rebuilt bundle **still serves A**. Only a restart serves B. So the mechanism is not "the watcher never fires because `node_modules` is excluded" — a rebuild the watcher DOES trigger still carries the stale dependency forward; the server's resolution of that import is pinned at process start, and a rebuild does not re-resolve it.
|
||||
|
||||
**So: restart `bun run dev` after every refresh of the package — a rebuild is not a substitute, even a real one.** There is no signal that you needed to; a stale server looks exactly like a current one.
|
||||
|
||||
## Why this is worth a leaf
|
||||
|
||||
VERIFIED 2026-08-16, and it cost about an hour. A defect had been fixed on the provider's side, the overlay was refreshed, and an automated probe on a freshly launched server confirmed the fix — 3 runs out of 3, clean. The same sequence performed by hand in a browser reproduced the defect immediately. The two observations looked irreconcilable, and the search went to the wallet, to prior state, to timing.
|
||||
|
||||
The dev server had been running for **six days**. It predated the package rename and the whole migration, and it was serving code from before the fix. The browser was running a different application from the one under test.
|
||||
|
||||
Two things made it hard to see. The failure mode is **silence** — nothing warns that the served code is old. And `scripts/overlay-local-checkout.ts` explicitly promised the opposite, that `bun --hot` would reload the copied file live; that claim is now corrected in the script, but a reader who trusted it would rule out the true cause first, which is exactly what happened.
|
||||
|
||||
## The reflex to build
|
||||
|
||||
When a fix does not appear to take effect, or when a hand-run and an automated run disagree, **check how long the server has been up before anything else**. It is one command, and it eliminates the cheapest hypothesis first:
|
||||
|
||||
```bash
|
||||
ps -o lstart= -p $(pgrep -f 'bun --hot src/index.ts' | head -1)
|
||||
```
|
||||
|
||||
Do not reach for "touch a source file to force a rebuild" as a lighter alternative to restarting — it does trigger a real rebuild, and the rebuild still serves the stale dependency. The same reasoning applies to anything else served out of `node_modules` — the trap is the location, not this package.
|
||||
|
||||
Related: [[cookbook_live-probe]] (bdd-testing) — a probe answers only for the code the server actually holds, so a stale server invalidates the probe's conclusion, not the product's behaviour.
|
||||
@@ -1,13 +1,24 @@
|
||||
---
|
||||
type: knowledge
|
||||
summary: Dev runs on bun --hot, prod builds through build.ts (Bun bundler + Tailwind plugin) into dist/, path alias @/* → ./src/*
|
||||
summary: Three run paths — dev AND production both serve from src/ (bun --hot / bun run start), while bun run build produces a dist/ that nothing serves; NODE_ENV therefore never means "I am a bundle"; path alias @/* → ./src/*
|
||||
last_checked: 2026-08-16
|
||||
---
|
||||
|
||||
# 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`).
|
||||
## Three paths, and only two of them ever run
|
||||
|
||||
| Path | Command | What is served |
|
||||
|---|---|---|
|
||||
| **Dev** | `bun run dev` → `bun --hot src/index.ts` | **`src/`** — HMR, port 3000 |
|
||||
| **Production** | `bun run start` → `NODE_ENV=production bun src/index.ts` | **`src/` as well** — Bun transpiles on the fly |
|
||||
| Bundle | `bun run build` → `build.ts` (Bun bundler + Tailwind plugin) → `dist/` | **nothing** |
|
||||
|
||||
> ⚠️ **`dist/` has no consumer, and `NODE_ENV=production` does not mean "built".** The container copies the sources and runs `bun run start`, serving from `src/` exactly as dev does ([[knowledge_deployment]]) — **nothing ever serves `dist/`**, here or anywhere else. So any code that branches on `NODE_ENV` to answer *"am I a bundle?"* is wrong in the one place it matters: in production the answer is **no**. That inference shipped once, on the runtime-config fetch below, and the deployed app could sign nobody in. Ask the artifact you care about, never the environment.
|
||||
|
||||
- **Path alias**: `@/* → ./src/*` (declared in `tsconfig.json`, resolved relative to that file — `paths` has needed no `baseUrl` since TS 4.4).
|
||||
|
||||
> ⚠️ **Never put `baseUrl` back in `tsconfig.json`.** TypeScript 6 reports it as an **error that aborts the whole compilation**, and the failure is silent where it hurts: `tsc --noEmit` then exits **0 having checked nothing**, so the typecheck gate goes green over any amount of broken code. A green typecheck is only meaningful if `tsc` actually ran — treat an instant, output-free `tsc` as a red flag, not a fast pass.
|
||||
|
||||
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]]).
|
||||
|
||||
@@ -18,9 +29,13 @@ The server serves `src/index.html`, which loads `src/app/frontend.tsx` (see `app
|
||||
|
||||
## 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.
|
||||
`build.ts` injects **compile-time globals** through `define`: `__FESTIPOD_SHARED_WALLET_PASSWORD__` from `FESTIPOD_SHARED_WALLET_PASSWORD`, 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):
|
||||
Everything served from `src/` — **dev and production alike** — therefore takes its configuration from 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.
|
||||
|
||||
**The fetch is skipped on one condition only: the global is already set** (which is what a `build.ts` bundle's `define` does, and nothing else does). The entry reads it through bracket access, so `define` — which rewrites the dotted form — leaves that read alone. The question is *"was the value inlined?"*, asked of the global itself; it was once asked as *"is `NODE_ENV` production?"*, which in this project means the opposite of what it looks like (see above) — the deployed app then skipped the only step that could give it a wallet, `ensureIdentity()` threw for want of one, and `/festipod-config.json` sat there served and unasked (`app-security` → [[caveat_shared-wallet-global-before-gate-import]]).
|
||||
|
||||
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 \
|
||||
|
||||
@@ -1,32 +1,61 @@
|
||||
---
|
||||
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
|
||||
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; the data-layer git dependency must be pinned to a tag/commit and match `contracts.yaml`'s ref; the shared wallet reaches the container through env vars, not a mount, because it isn't a secret; no CI/CD committed; dev goes through the portless wrapper
|
||||
last_checked: 2026-08-17
|
||||
---
|
||||
|
||||
# Deployment & infra
|
||||
|
||||
Nothing has actually been deployed with this shape yet — this leaf states what a deployment needs to line up, verified against the code and manifests, not a procedure that has been run end to end.
|
||||
|
||||
## 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.
|
||||
- `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/polyfill` 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.
|
||||
**`bun` peer pitfall — historical, and no longer reproducing.** `bun-plugin-tailwind` declares `bun` as a peerDependency, and pnpm used to materialize the npm `bun` package with a `node_modules/.bin/bun` shim that shadowed the real binary under `bun run`; its postinstall being skipped left a broken shim and `bun run start` failed. `pnpm.onlyBuiltDependencies: ["bun"]` in `package.json` was added for that. **VERIFIED 2026-08-17 in a built image: the shim does not appear at all** — `bun` is absent from `node_modules/.bin`, and `which bun` resolves to the base image's `/usr/local/bin/bun`. So the approval is currently inert in this dependency shape. Keep it (it costs nothing and the shape can come back), but do not trust the mechanism as described without re-checking the built image — this paragraph described a live hazard and now describes a dormant one.
|
||||
|
||||
**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.
|
||||
**Asset paths are written `/../chunk-*.js`.** Verified in the built image's entry HTML. Browsers normalise that to `/chunk-*.js` at the root and it serves correctly, and the existing deployment already passes it through its proxy — so it works. It is still an odd literal: a proxy or CDN that rejects or rewrites `..` segments differently would break asset loading, and the symptom would be a blank page with 404s on chunks rather than anything naming the cause.
|
||||
|
||||
**`tailwindcss` is a devDependency the server needs at serve time, not only at build time.** `bunfig.toml`'s `[serve.static] plugins = ["bun-plugin-tailwind"]` applies to `Bun.serve`'s HTML-import serving — the path both `bun run dev` and `bun run start` use ([[knowledge_build-pipeline]]) — not only to `bun run build.ts`. The install stage must therefore keep installing devDependencies: no `--prod`, and `NODE_ENV` stays unset until the `release` stage, after `pnpm install --frozen-lockfile` has already run. Moving `ENV NODE_ENV=production` earlier, or adding `--prod` to the install, would drop `tailwindcss` and break every serve, dev included.
|
||||
|
||||
**Production runs the sources, and this is the normal path, not a quirk**: `start` = `NODE_ENV=production bun src/index.ts` → the container **runs the TypeScript directly** (Bun transpiles on the fly). `bun run build` (→ `dist/`) is on **no** path at all — nothing serves that directory, in this container or anywhere else; serving it would mean changing the entrypoint. Consequence for the code: in this deployment `NODE_ENV=production` says *how* the sources run, never *that they were bundled* — [[knowledge_build-pipeline]].
|
||||
|
||||
## The data-layer git dependency must stay pinned, and the pin must be checkable
|
||||
|
||||
`package.json` resolves `@ng-eventually/polyfill` from `git+https://…/ng-eventually.git#<ref>&path:/packages/polyfill` — the `path:` selector is what lets a subdirectory of the provider's repo be installed as the package. Two things follow, ahead of any real deployment:
|
||||
|
||||
- **`<ref>` must name a tag or a commit, never a branch.** A branch moves: the image was built against whatever commit the branch pointed to at build time, and the branch head can advance afterwards without the image changing — so "the same deployment" silently starts drifting from what it was actually built against. The tag-naming convention itself is the provider's call and is not settled yet; the requirement is only that the ref be immutable.
|
||||
- **The same `<ref>` should also be the `ref:` of the `polyfill-surface` entry in `.project/contracts.yaml`.** That manifest pins the version of [[contract_polyfill-surface]] the app is coded against; when it names the same ref as `package.json`'s specifier, the contract the app was written for and the package actually installed name the same state, and a difference between the two becomes visible instead of silent. Both now name the **same commit**, which is the state a deployment can ship on. A tag is expected to replace that commit once the provider settles a naming convention — a one-line change in each of the two files, with the invariant unchanged: whatever the ref is, the two must agree.
|
||||
|
||||
**`pnpm install --frozen-lockfile` (the Dockerfile's install step) never regenerates — it only verifies.** `pnpm-lock.yaml` must already reproduce `package.json` exactly, so any change to the git specifier (ref, path, or package name) needs `pnpm install` run and the regenerated lockfile committed *before* the image can build; skipping that step fails the build outright, not silently. This has bitten once: the lockfile still named the old package and path after the dependency was renamed, so `--frozen-lockfile` refused and the image could not build until it was regenerated.
|
||||
|
||||
## 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.
|
||||
|
||||
**A deployed origin IS embeddable in the hosted broker's iframe — VERIFIED 2026-08-17 in production**, on the first deployment carrying the injected wallet and the external data layer: a user signed in and saw their own data, which is only reachable through that iframe. The question had been open because nothing in this repo exercises it; it is settled for this origin, and it is settled by the deployment rather than by a test — **no scenario covers it**, so a change of origin, of proxy, or of the broker's embedding policy would be found by a person, not by the suite. [[caveat_firefox-lna-blocks-broker-iframe]] remains the one recorded failure mode, and it is a local-dev-origin one (`127.0.0.1` blocked by Firefox LNA).
|
||||
|
||||
## 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.
|
||||
- No `.env*` is committed (`.env` is gitignored).
|
||||
|
||||
### The shared wallet: config, not a secret, not a mount
|
||||
|
||||
[[contract_polyfill-surface]] requires the app to serve a wallet file (`.ngw`) and pass its URL and password to `configure` as `sharedWallet: { fileUrl, password }`. `*.ngw` is gitignored and no deployment mounts one, so `src/index.ts` serves it from environment variables, read fresh on every request:
|
||||
|
||||
- `FESTIPOD_SHARED_WALLET_PASSWORD` — the password, always read this way (dev, tests, and deployments alike).
|
||||
- `FESTIPOD_SHARED_WALLET_FILE` — a filesystem path to the `.ngw` file. The form local dev and the test harness use: the file sits on the machine's disk.
|
||||
- `FESTIPOD_SHARED_WALLET_FILE_BASE64` — the file's bytes, base64-encoded. The form a deployment uses instead, since nothing mounts a `.ngw` into the container.
|
||||
|
||||
**Precedence is one-directional and does not fall through.** `FESTIPOD_SHARED_WALLET_FILE` wins whenever it is set, *even if the path turns out unreadable* — an unreadable path answers 404, it does **not** fall back to the base64 form. A deployment must set exactly one of the two; leaving a leftover `FESTIPOD_SHARED_WALLET_FILE` pointing nowhere in a deployment environment silently 404s instead of serving the base64 value that was actually intended. A malformed base64 value answers 500 naming the variable — never a 404, which would be indistinguishable from "not configured at all".
|
||||
|
||||
**Neither the password nor the wallet file is a secret**, and that is deliberate, not an oversight: the contract has the app hand both to every user who opens it — that is how a first-time device without its own wallet onboards. Provisioning them as protected/mounted storage would guard something the app already gives away by design; they travel as plain configuration instead, and a new host needs only its environment variables, nothing to mount.
|
||||
|
||||
## 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`.
|
||||
**Reactive local overlay for the SDK**: in production the `@ng-eventually/polyfill` dependency comes from Gitea (git+https, pinned by `pnpm-lock.yaml`), and `@ng-helpers/indexing` likewise. When a provider's package has to be exercised from a local checkout, `pnpm run overlay:polyfill` or `pnpm run overlay:indexing` (script `scripts/overlay-local-checkout.ts`, one provider per run) replaces `node_modules/<package>` with a **real copy** of that checkout (location overridable with `NG_EVENTUALLY_LOCAL` / `NG_HELPERS_LOCAL`) — **without** its own `node_modules/*` — and resyncs on every edit. Copying rather than symlinking is what keeps a **single instance** of every package the provider shares with Festipod installed (`@ng-org/*`, and for `indexing`, `@ng-eventually/polyfill` itself): a symlink would drag in a second one and the SDK would stop working. To go back to the committed state: `pnpm install`.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
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)
|
||||
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, overlay:polyfill/overlay:indexing for the reactive local overlay)
|
||||
---
|
||||
|
||||
# Stack & commands
|
||||
@@ -10,7 +10,7 @@ summary: Stack components (Bun runtime/build/test, install through pnpm, React,
|
||||
| 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. |
|
||||
| **Dependency installation** | **pnpm** (`pnpm install`, `pnpm-lock.yaml`) — **only** installation moves to pnpm; runtime/build/test stay on bun. Reason: `@ng-eventually/polyfill` is resolved from Gitea over **git+https** (pnpm handles `git+…#main&path:/packages/polyfill` 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`) |
|
||||
@@ -23,7 +23,7 @@ summary: Stack components (Bun runtime/build/test, install through pnpm, React,
|
||||
|---|---|
|
||||
| `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]]) |
|
||||
| `build` | `bun run build.ts` — Bun bundler + Tailwind → `dist/`, **which nothing serves**: production runs `start`, from `src/` ([[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` |
|
||||
@@ -33,11 +33,11 @@ summary: Stack components (Bun runtime/build/test, install through pnpm, React,
|
||||
| `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]]. |
|
||||
| `overlay:polyfill` / `overlay:indexing` | `bun scripts/overlay-local-checkout.ts <provider>` — **reactive** local overlay of a provider's checkout (`@ng-eventually/polyfill` or `@ng-helpers/indexing`; copy-overlay + watcher, `--once` for a single pass). 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.
|
||||
- **`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, and reproducibly: regenerating from an *unchanged* `.shex` reproduces the committed bindings byte-for-byte. Verify that before trusting an ORM diff as your own — run the generator once on the shape untouched, then again after your edit, so the diff shown is the edit alone (concept `data-layer` → [[knowledge_nextgraph-stack]]).
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
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
|
||||
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, not bun install
|
||||
---
|
||||
|
||||
# Rule: Bun-first
|
||||
@@ -28,9 +28,9 @@ 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.
|
||||
**Dependencies are installed with `pnpm install`, not `bun install`.** 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]]).
|
||||
**Why.** The data SDK is installed from a Gitea repository as a **subdirectory** git dependency: `git+https://…/ng-eventually.git#main&path:/packages/polyfill`. pnpm (≥ 10.26) resolves that `#<ref>&path:/…` format and guarantees a **single** instance of `@ng-org/*`; `bun install` does not handle this workflow cleanly. The reference lockfile is therefore `pnpm-lock.yaml`, and the reactive local overlay goes through `pnpm run overlay:polyfill` (`overlay:indexing` for the other provider; 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.
|
||||
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
# Inter-repo contracts. Festipod is a CONSUMER only: it publishes no interface of its own,
|
||||
# and it consumes two — the SDK surface `@ng-eventually/polyfill` engages toward the
|
||||
# applications built on it, and the indexing layer `ng-helpers` engages toward the
|
||||
# applications that need to make things findable.
|
||||
#
|
||||
# The pulled copy under `into:` IS the specification Festipod codes against. An agent
|
||||
# working here reads that copy and never opens the provider's own source: a gap is raised
|
||||
# upstream (see `data-layer/rule_app-uses-sdk-surface-only`), never peeked around.
|
||||
#
|
||||
# Each interface gets its own FOLDER inside the concept that owns it, holding the pulled
|
||||
# engagement and — once Festipod actually consumes the interface — the `usage_festipod.md`
|
||||
# declaration beside it. Both interfaces land in `data-layer`: it is the concept that owns
|
||||
# how Festipod uses an external data surface, including the machinery behind discovery
|
||||
# (`functional-domain` owns the product intent of discovery and explicitly delegates its
|
||||
# technical how to the data SDK).
|
||||
#
|
||||
# `pullFrom:` names the canonical identity of the provider (its git remote URL + the
|
||||
# repo-relative path of the leaf), so the manifest travels with the branch. Per-developer
|
||||
# access to a local checkout lives in `.project/contracts.local.yaml`, which is never
|
||||
# committed.
|
||||
|
||||
consume:
|
||||
- contract: polyfill-surface
|
||||
into: concepts/data-layer/polyfill-surface/
|
||||
type: git
|
||||
# BLOCKED on the provider: it has moved this leaf into its own interface folder
|
||||
# (`.../app-contract/polyfill-surface/contract_polyfill-surface.md`) and has NOT pushed
|
||||
# that move. The path below is the only one that resolves at a pushed commit, and it is
|
||||
# the path the local copy's stamp came from — so it stays until the move is pushed.
|
||||
# Until then `pull` and `check` both fail on this entry (the file no longer exists at
|
||||
# this path in a working copy that has the move). Adopt the new path and re-pull the
|
||||
# moment the provider pushes; the pulled copy's basename does not change.
|
||||
pullFrom: https://gitea.reconnexion.apps.gueraud.net/Reconnexion/ng-eventually.git/.project/concepts/app-contract/contract_polyfill-surface.md
|
||||
# The contract is published from the branch that carries it while that branch is still
|
||||
# in flight; it moves to `main` once the provider lands it there. Flip this line then,
|
||||
# and re-pull — the stamp records which commit the local copy actually came from.
|
||||
ref: a8d53010c227462cc9317e9be499c2100ca8d533
|
||||
|
||||
- contract: indexing-layer
|
||||
into: concepts/data-layer/indexing-layer/
|
||||
type: git
|
||||
pullFrom: https://gitea.reconnexion.apps.gueraud.net/Sylvain/ng-helpers.git/.project/concepts/indexing/indexing-layer/contract_indexing-layer.md
|
||||
# Pinned on the TAG, never on a branch: a branch moves under us and the pin would stop
|
||||
# naming a state anyone can go back to. Re-pin to the next tag at each upgrade.
|
||||
ref: v1.0.1
|
||||
@@ -1,4 +1,3 @@
|
||||
# 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
|
||||
- [ ] clarifier le vocabulaire d'identité employé par Festipod (wallet, utilisateur, profil, username) et réconcilier decision_2026-07-06 (« identifiant = wallet ») et decision_2026-07-20 (« username dans le profil ») avec ce que le contrat publie aujourd'hui : `ensureIdentity()` ne prend aucun identifiant, et `username` ne désigne plus que `UserProfile.username`
|
||||
|
||||
@@ -14,15 +14,15 @@ Web app mobile-first où les utilisateurs créent des **points de rencontre** qu
|
||||
- **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).
|
||||
|
||||
## Frontière SDK NextGraph
|
||||
## Frontière SDK
|
||||
|
||||
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(...)`.
|
||||
Le SDK de données de Festipod est **`@ng-eventually/polyfill`**, injecté une seule fois via `ngSession.configure(...)`.
|
||||
|
||||
**`@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é.
|
||||
**L'engagement que le fournisseur publie est tiré dans ce repo et épinglé** : `data-layer`, fiche `contract_polyfill-surface`. **C'est la seule référence.** On n'ouvre jamais les sources du fournisseur ni sa copie dans `node_modules`, pas même pour vérifier une signature. Ce que le contrat ne dit pas, ce repo ne le sait pas : **un manque est remonté au fournisseur**, jamais contourné ici ni documenté ici. Vaut aussi pour les tests, qui valident **Festipod** et jamais le SDK (`bdd-testing`, `rule_tests-validate-festipod-not-the-sdk`).
|
||||
|
||||
**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 »**.
|
||||
Le contrat se re-tire à chaque montée de version : `python3 ~/projects/skills/concept/contracts.py pull` (dérive : `… check`). Sa surface **rétrécit** — un symbole retiré est du code que l'app supprime, pas une régression à amortir.
|
||||
|
||||
**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.
|
||||
**Ne jamais décrire dans ce repo comment la couche de données est implémentée.** La doctrine Festipod décrit uniquement *le contrat* + *comment Festipod l'utilise* + le domaine + l'architecture + le contrat BDD.
|
||||
|
||||
## Doctrine du projet — concepts (livrée automatiquement)
|
||||
|
||||
@@ -33,7 +33,7 @@ La connaissance détaillée vit dans `.project/concepts/` (système *concept*) :
|
||||
| `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 |
|
||||
| `data-layer` | Persistance via le SDK `@ng-eventually/polyfill` : 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 |
|
||||
|
||||
|
||||
+1
-1
@@ -3,7 +3,7 @@ FROM oven/bun:1-alpine AS base
|
||||
WORKDIR /app
|
||||
|
||||
# Install dependencies with pnpm.
|
||||
# - git: the @ng-eventually/client polyfill is a git+https (public Gitea) dependency → no auth.
|
||||
# - git: @ng-eventually/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
|
||||
|
||||
@@ -133,12 +133,9 @@ 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
|
||||
// Shared wallet password, baked into the browser bundle as a global (see
|
||||
// sharedWallet.ts) and handed to the SDK by the ONE `configure` call. 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 ?? "",
|
||||
),
|
||||
@@ -151,8 +148,9 @@ const result = await Bun.build({
|
||||
...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.
|
||||
// Staging: copy the shared wallet FILE into the bundle so it can be offered for
|
||||
// download (served at /shared-wallet.ngw — the `fileUrl` the app hands the SDK
|
||||
// through `configure`). 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"));
|
||||
|
||||
+4
-2
@@ -17,12 +17,14 @@
|
||||
"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",
|
||||
"overlay:polyfill": "bun scripts/overlay-local-checkout.ts polyfill",
|
||||
"overlay:indexing": "bun scripts/overlay-local-checkout.ts indexing",
|
||||
"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-eventually/polyfill": "git+https://gitea.reconnexion.apps.gueraud.net/Reconnexion/ng-eventually.git#a8d53010c227462cc9317e9be499c2100ca8d533&path:/packages/polyfill",
|
||||
"@ng-helpers/indexing": "git+https://gitea.reconnexion.apps.gueraud.net/Sylvain/ng-helpers.git#v1.0.1",
|
||||
"@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",
|
||||
|
||||
Generated
+19
-6
@@ -8,9 +8,12 @@ importers:
|
||||
|
||||
.:
|
||||
dependencies:
|
||||
'@ng-eventually/client':
|
||||
specifier: git+https://gitea.reconnexion.apps.gueraud.net/Reconnexion/ng-eventually.git#main&path:/packages/client
|
||||
version: git+https://gitea.reconnexion.apps.gueraud.net/Reconnexion/ng-eventually.git#1f0bae461e461c9fddd7215f972418acb2b4a989&path:/packages/client(@ng-org/alien-deepsignals@0.1.2-alpha.11(react@19.2.7))(@ng-org/orm@0.1.2-alpha.18(react@19.2.7))(@ng-org/shex-orm@0.1.2-alpha.8(typescript@6.0.3))(@ng-org/web@0.1.2-alpha.13)
|
||||
'@ng-eventually/polyfill':
|
||||
specifier: git+https://gitea.reconnexion.apps.gueraud.net/Reconnexion/ng-eventually.git#a8d53010c227462cc9317e9be499c2100ca8d533&path:/packages/polyfill
|
||||
version: git+https://gitea.reconnexion.apps.gueraud.net/Reconnexion/ng-eventually.git#a8d53010c227462cc9317e9be499c2100ca8d533&path:/packages/polyfill(@ng-org/alien-deepsignals@0.1.2-alpha.11(react@19.2.7))(@ng-org/orm@0.1.2-alpha.18(react@19.2.7))(@ng-org/shex-orm@0.1.2-alpha.8(typescript@6.0.3))(@ng-org/web@0.1.2-alpha.13)
|
||||
'@ng-helpers/indexing':
|
||||
specifier: git+https://gitea.reconnexion.apps.gueraud.net/Sylvain/ng-helpers.git#v1.0.1
|
||||
version: git+https://gitea.reconnexion.apps.gueraud.net/Sylvain/ng-helpers.git#d615a72775cc9110de64b9b7fcc1d0d6c6d127ea(@ng-eventually/polyfill@git+https://gitea.reconnexion.apps.gueraud.net/Reconnexion/ng-eventually.git#a8d53010c227462cc9317e9be499c2100ca8d533&path:/packages/polyfill(@ng-org/alien-deepsignals@0.1.2-alpha.11(react@19.2.7))(@ng-org/orm@0.1.2-alpha.18(react@19.2.7))(@ng-org/shex-orm@0.1.2-alpha.8(typescript@6.0.3))(@ng-org/web@0.1.2-alpha.13))
|
||||
'@ng-org/alien-deepsignals':
|
||||
specifier: 0.1.2-alpha.11
|
||||
version: 0.1.2-alpha.11(react@19.2.7)
|
||||
@@ -488,8 +491,8 @@ packages:
|
||||
'@emnapi/core': ^1.7.1
|
||||
'@emnapi/runtime': ^1.7.1
|
||||
|
||||
'@ng-eventually/client@git+https://gitea.reconnexion.apps.gueraud.net/Reconnexion/ng-eventually.git#1f0bae461e461c9fddd7215f972418acb2b4a989&path:/packages/client':
|
||||
resolution: {commit: 1f0bae461e461c9fddd7215f972418acb2b4a989, path: /packages/client, repo: https://gitea.reconnexion.apps.gueraud.net/Reconnexion/ng-eventually.git, type: git}
|
||||
'@ng-eventually/polyfill@git+https://gitea.reconnexion.apps.gueraud.net/Reconnexion/ng-eventually.git#a8d53010c227462cc9317e9be499c2100ca8d533&path:/packages/polyfill':
|
||||
resolution: {commit: a8d53010c227462cc9317e9be499c2100ca8d533, path: /packages/polyfill, repo: https://gitea.reconnexion.apps.gueraud.net/Reconnexion/ng-eventually.git, type: git}
|
||||
version: 0.0.0
|
||||
peerDependencies:
|
||||
'@ng-org/alien-deepsignals': '*'
|
||||
@@ -506,6 +509,12 @@ packages:
|
||||
'@ng-org/web':
|
||||
optional: true
|
||||
|
||||
'@ng-helpers/indexing@git+https://gitea.reconnexion.apps.gueraud.net/Sylvain/ng-helpers.git#d615a72775cc9110de64b9b7fcc1d0d6c6d127ea':
|
||||
resolution: {commit: d615a72775cc9110de64b9b7fcc1d0d6c6d127ea, repo: https://gitea.reconnexion.apps.gueraud.net/Sylvain/ng-helpers.git, type: git}
|
||||
version: 1.0.1
|
||||
peerDependencies:
|
||||
'@ng-eventually/polyfill': '*'
|
||||
|
||||
'@ng-org/alien-deepsignals@0.1.2-alpha.11':
|
||||
resolution: {integrity: sha512-nPgqOrheAda/pW5FHgSb45SrSZWuyMyEVqO683ijEsVPpD105bngfh92PPfcRoRnFzGSoKXa3CfuqUHi2+qVIQ==}
|
||||
peerDependencies:
|
||||
@@ -3727,13 +3736,17 @@ snapshots:
|
||||
'@tybys/wasm-util': 0.10.3
|
||||
optional: true
|
||||
|
||||
'@ng-eventually/client@git+https://gitea.reconnexion.apps.gueraud.net/Reconnexion/ng-eventually.git#1f0bae461e461c9fddd7215f972418acb2b4a989&path:/packages/client(@ng-org/alien-deepsignals@0.1.2-alpha.11(react@19.2.7))(@ng-org/orm@0.1.2-alpha.18(react@19.2.7))(@ng-org/shex-orm@0.1.2-alpha.8(typescript@6.0.3))(@ng-org/web@0.1.2-alpha.13)':
|
||||
'@ng-eventually/polyfill@git+https://gitea.reconnexion.apps.gueraud.net/Reconnexion/ng-eventually.git#a8d53010c227462cc9317e9be499c2100ca8d533&path:/packages/polyfill(@ng-org/alien-deepsignals@0.1.2-alpha.11(react@19.2.7))(@ng-org/orm@0.1.2-alpha.18(react@19.2.7))(@ng-org/shex-orm@0.1.2-alpha.8(typescript@6.0.3))(@ng-org/web@0.1.2-alpha.13)':
|
||||
optionalDependencies:
|
||||
'@ng-org/alien-deepsignals': 0.1.2-alpha.11(react@19.2.7)
|
||||
'@ng-org/orm': 0.1.2-alpha.18(react@19.2.7)
|
||||
'@ng-org/shex-orm': 0.1.2-alpha.8(typescript@6.0.3)
|
||||
'@ng-org/web': 0.1.2-alpha.13
|
||||
|
||||
'@ng-helpers/indexing@git+https://gitea.reconnexion.apps.gueraud.net/Sylvain/ng-helpers.git#d615a72775cc9110de64b9b7fcc1d0d6c6d127ea(@ng-eventually/polyfill@git+https://gitea.reconnexion.apps.gueraud.net/Reconnexion/ng-eventually.git#a8d53010c227462cc9317e9be499c2100ca8d533&path:/packages/polyfill(@ng-org/alien-deepsignals@0.1.2-alpha.11(react@19.2.7))(@ng-org/orm@0.1.2-alpha.18(react@19.2.7))(@ng-org/shex-orm@0.1.2-alpha.8(typescript@6.0.3))(@ng-org/web@0.1.2-alpha.13))':
|
||||
dependencies:
|
||||
'@ng-eventually/polyfill': git+https://gitea.reconnexion.apps.gueraud.net/Reconnexion/ng-eventually.git#a8d53010c227462cc9317e9be499c2100ca8d533&path:/packages/polyfill(@ng-org/alien-deepsignals@0.1.2-alpha.11(react@19.2.7))(@ng-org/orm@0.1.2-alpha.18(react@19.2.7))(@ng-org/shex-orm@0.1.2-alpha.8(typescript@6.0.3))(@ng-org/web@0.1.2-alpha.13)
|
||||
|
||||
'@ng-org/alien-deepsignals@0.1.2-alpha.11(react@19.2.7)':
|
||||
dependencies:
|
||||
alien-signals: 2.0.8
|
||||
|
||||
File diff suppressed because one or more lines are too long
+83
-9508
File diff suppressed because it is too large
Load Diff
@@ -1,106 +0,0 @@
|
||||
#!/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);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,160 @@
|
||||
#!/usr/bin/env bun
|
||||
/**
|
||||
* overlay-local-checkout.ts — Reactive local overlay of a data-layer PROVIDER's checkout
|
||||
* into node_modules. One script, one provider per run; only the paths differ between them.
|
||||
*
|
||||
* PROVIDERS (first non-flag argument; defaults to `polyfill`):
|
||||
* polyfill → node_modules/@ng-eventually/polyfill override: NG_EVENTUALLY_LOCAL
|
||||
* indexing → node_modules/@ng-helpers/indexing override: NG_HELPERS_LOCAL
|
||||
*
|
||||
* WHY a copy-overlay and not a symlink (identical for every provider):
|
||||
* A committed prod dependency installs from Gitea (git+https) into pnpm's store WITHOUT
|
||||
* its own node_modules/@ng-org, so @ng-org/web resolves UP to Festipod → ONE @ng-org
|
||||
* instance (one verifier). A local CHECKOUT, however, carries its own node_modules/*
|
||||
* (links into that provider's own dev tree). Symlinking node_modules/<pkg> to the
|
||||
* checkout would put the checkout's copies in the resolution path → a SECOND @ng-org
|
||||
* (and, for `indexing`, a second @ng-eventually/polyfill) → broken SDK, two verifiers.
|
||||
* So we overlay a real directory containing ONLY the provider's source (no node_modules):
|
||||
* shared packages still resolve up to Festipod, single instance preserved.
|
||||
*
|
||||
* WHAT IT DOES:
|
||||
* 1. Replaces node_modules/<package> (the pnpm store symlink) with a real directory
|
||||
* holding the local checkout's package.json + src (NO node_modules).
|
||||
* 2. Asserts the single-instance invariant — every package this provider SHARES with
|
||||
* Festipod must resolve to the same realpath from Festipod and from the overlay —
|
||||
* and aborts if it would break.
|
||||
* 3. Watches the local checkout's src and copies each change into the overlay.
|
||||
*
|
||||
* ⚠️ RESTART `bun run dev` AFTER THIS SCRIPT WRITES — a rebuild is NOT a substitute.
|
||||
* A running dev server NEVER picks up a package refreshed inside node_modules, not even
|
||||
* across a genuine rebuild: VERIFIED in a controlled test, an application-source edit
|
||||
* produced a new bundle hash and the rebuilt bundle STILL carried the stale dependency.
|
||||
* The server's resolution of that import is pinned at process start and a rebuild does not
|
||||
* re-resolve it. Only restarting serves the fresh copy, and nothing warns you — a stale
|
||||
* server looks exactly like a current one. See
|
||||
* .project/concepts/tech-stack/caveat_polyfill-overlay-needs-a-dev-restart.md, which cost
|
||||
* an hour to learn. Watching copies the files; it does not make anything reload them.
|
||||
*
|
||||
* USAGE (reactive dev):
|
||||
* Terminal 1: pnpm run overlay:polyfill # or: pnpm run overlay:indexing
|
||||
* Terminal 2: bun run dev # portless festipod bun --hot src/index.ts
|
||||
* Edit the checkout's src → it lands in node_modules → RESTART dev to pick it up.
|
||||
*
|
||||
* pnpm run overlay:indexing --once # overlay + verify, no watch (CI / one-shot)
|
||||
* Return to the committed git-installed dependencies: pnpm install
|
||||
*/
|
||||
import { existsSync, lstatSync, mkdirSync, rmSync, cpSync, copyFileSync, realpathSync } from "node:fs";
|
||||
import { watch } from "node:fs";
|
||||
import { join, dirname } from "node:path";
|
||||
|
||||
interface Provider {
|
||||
/** Package as installed, e.g. "@ng-eventually/polyfill" — also its node_modules path. */
|
||||
readonly packageName: string;
|
||||
/** Local checkout used when the env override is unset. */
|
||||
readonly defaultLocal: string;
|
||||
/** Env var overriding the local checkout path. */
|
||||
readonly envOverride: string;
|
||||
/**
|
||||
* Packages this provider SHARES with Festipod and that must stay single-instance.
|
||||
* Each is resolved from Festipod and from the overlay; the realpaths must match.
|
||||
*/
|
||||
readonly singletons: readonly string[];
|
||||
}
|
||||
|
||||
const PROVIDERS: Record<string, Provider> = {
|
||||
polyfill: {
|
||||
packageName: "@ng-eventually/polyfill",
|
||||
defaultLocal: "/home/sylvain/projects/nextgraph/ng-eventually-js/packages/polyfill",
|
||||
envOverride: "NG_EVENTUALLY_LOCAL",
|
||||
singletons: ["@ng-org/web"],
|
||||
},
|
||||
indexing: {
|
||||
packageName: "@ng-helpers/indexing",
|
||||
defaultLocal: "/home/sylvain/projects/nextgraph/ng-helpers",
|
||||
envOverride: "NG_HELPERS_LOCAL",
|
||||
// Consumes the polyfill, so BOTH it and the verifier underneath must stay single.
|
||||
singletons: ["@ng-eventually/polyfill", "@ng-org/web"],
|
||||
},
|
||||
};
|
||||
|
||||
const FESTIPOD = realpathSync(join(import.meta.dir, ".."));
|
||||
const args = process.argv.slice(2);
|
||||
const ONCE = args.includes("--once");
|
||||
const KEY = args.find((a) => !a.startsWith("-")) ?? "polyfill";
|
||||
|
||||
function fail(msg: string): never {
|
||||
console.error(`✖ overlay:${KEY} — ${msg}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const provider = PROVIDERS[KEY];
|
||||
if (!provider) {
|
||||
fail(`unknown provider "${KEY}" — expected one of: ${Object.keys(PROVIDERS).join(", ")}`);
|
||||
}
|
||||
|
||||
const LOCAL = process.env[provider.envOverride] ?? provider.defaultLocal;
|
||||
const TARGET = join(FESTIPOD, "node_modules", ...provider.packageName.split("/"));
|
||||
const SRC_LOCAL = join(LOCAL, "src");
|
||||
const SRC_TARGET = join(TARGET, "src");
|
||||
|
||||
if (!existsSync(join(LOCAL, "package.json"))) {
|
||||
fail(`local checkout not found at ${LOCAL} (set ${provider.envOverride} to override)`);
|
||||
}
|
||||
if (!existsSync(SRC_LOCAL)) {
|
||||
fail(`local checkout has no src/ at ${SRC_LOCAL}`);
|
||||
}
|
||||
|
||||
// 1. Replace the pnpm store symlink with a real overlay dir (metadata + src, NO node_modules).
|
||||
console.log(`→ overlaying local ${provider.packageName}: ${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 instances).
|
||||
cpSync(SRC_LOCAL, SRC_TARGET, { recursive: true });
|
||||
|
||||
// 2. Assert the single-instance invariant for every package shared with Festipod.
|
||||
const overlayReal = realpathSync(TARGET);
|
||||
for (const spec of provider.singletons) {
|
||||
const fromFestipod = realpathSync(Bun.resolveSync(spec, FESTIPOD));
|
||||
const fromOverlay = realpathSync(Bun.resolveSync(spec, overlayReal));
|
||||
console.log(` ${spec} (Festipod): ${fromFestipod}`);
|
||||
console.log(` ${spec} (overlay) : ${fromOverlay}`);
|
||||
if (fromFestipod !== fromOverlay) {
|
||||
fail(
|
||||
`single-instance invariant BROKEN — ${spec} resolves to two different realpaths.\n` +
|
||||
" The overlay must not contain its own node_modules. Aborting.",
|
||||
);
|
||||
}
|
||||
}
|
||||
console.log(`✓ single instance preserved for: ${provider.singletons.join(", ")}`);
|
||||
|
||||
if (ONCE) {
|
||||
console.log("✓ overlay ready (--once, not watching)");
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
// 3. Watch and copy on change. This keeps the overlay CURRENT; it does NOT make a running
|
||||
// dev server notice — not even across a rebuild (see the header). Restart it.
|
||||
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);
|
||||
}
|
||||
});
|
||||
+10
-13
@@ -1,7 +1,6 @@
|
||||
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';
|
||||
@@ -57,18 +56,16 @@ export function App() {
|
||||
return (
|
||||
<ThemeProvider>
|
||||
<NextGraphProvider>
|
||||
<AccountProvider>
|
||||
<FestipodDataProvider>
|
||||
<RouterProvider>
|
||||
<div className="app-container">
|
||||
<AuthGate>
|
||||
<AppContent />
|
||||
</AuthGate>
|
||||
<ToastContainer />
|
||||
</div>
|
||||
</RouterProvider>
|
||||
</FestipodDataProvider>
|
||||
</AccountProvider>
|
||||
<FestipodDataProvider>
|
||||
<RouterProvider>
|
||||
<div className="app-container">
|
||||
<AuthGate>
|
||||
<AppContent />
|
||||
</AuthGate>
|
||||
<ToastContainer />
|
||||
</div>
|
||||
</RouterProvider>
|
||||
</FestipodDataProvider>
|
||||
</NextGraphProvider>
|
||||
</ThemeProvider>
|
||||
);
|
||||
|
||||
+82
-70
@@ -1,89 +1,101 @@
|
||||
/**
|
||||
* 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.
|
||||
* AuthGate — the ONE await the application makes before it renders.
|
||||
*
|
||||
* 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.
|
||||
* Signing in is `ensureIdentity()` and nothing else: it takes no identifier,
|
||||
* resolves who we are and does the connection work (restoring what others shared
|
||||
* with us, draining our inboxes). Whatever a user has to see or do while that
|
||||
* resolves — opening the wallet, loading it onto a first-time device — belongs to
|
||||
* the SDK: it mounts a full-screen barrier of its own on every top-level load and
|
||||
* takes it down itself, and it owns the return from the broker round-trip (the
|
||||
* barrier comes back prefilled, and confirming it hands the page over a second
|
||||
* time; our page is never reloaded and nothing outside the barrier is touched).
|
||||
* Festipod renders no access screen of its own and re-drives nothing.
|
||||
*
|
||||
* TWO CALLS, IN ORDER, AND THE ORDER IS CONTRACTUAL: start the session (`init`),
|
||||
* then await `ensureIdentity()`. A session arrives only through `init`, and
|
||||
* `ensureIdentity()` awaited before it has been called THROWS. The order is a fact
|
||||
* of the statement sequence below, not of React's effect ordering — which would
|
||||
* get it wrong: this gate's effect runs BEFORE its parent provider's.
|
||||
*
|
||||
* It hands back WHO WE ARE, and this is the app's only upstream answer to that
|
||||
* question — everything else it knows about the user it has to read first. The
|
||||
* value is published for display (`shared/utils/currentPrincipal`) and goes
|
||||
* nowhere near a data call: no call takes an identity, because the session
|
||||
* already belongs to one user.
|
||||
*
|
||||
* Nothing of the app renders before that await settles: a screen mounted earlier
|
||||
* would read as an identity that is not yet settled.
|
||||
*
|
||||
* AND NOTHING RENDERS IF IT FAILS. A rejected `ensureIdentity()` is not a mode the
|
||||
* app degrades through: an app that could not sign in but still shows its screens
|
||||
* is indistinguishable from an app whose user simply owns nothing — a total
|
||||
* failure wearing the face of an empty account. So the rejection is SHOWN, and the
|
||||
* children stay unmounted, which is also what keeps the data layer from settling
|
||||
* on its empty stand-in provider for the rest of the session.
|
||||
*/
|
||||
|
||||
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 { useEffect, useState, type ReactNode } from 'react';
|
||||
import { ensureIdentity } from '@ng-eventually/polyfill';
|
||||
import { startNgSession } from '../shared/utils/ngSession';
|
||||
import { setCurrentPrincipal } from '../shared/utils/currentPrincipal';
|
||||
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();
|
||||
// Whether the ONE identity await has resolved.
|
||||
const [identityReady, setIdentityReady] = useState(false);
|
||||
// Why it did NOT resolve. Set once, never cleared: signing in is attempted once.
|
||||
const [signInError, setSignInError] = useState<string | null>(null);
|
||||
|
||||
// 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') {
|
||||
let cancelled = false;
|
||||
// FIRST — a session arrives only through the SDK's `init`. Idempotent, so the
|
||||
// provider above may have started it already; what matters is that it has been
|
||||
// called before the await below, or the await throws.
|
||||
void startNgSession();
|
||||
void ensureIdentity()
|
||||
.then(principal => {
|
||||
// Publish who we are BEFORE anything renders — the identity is a fact of
|
||||
// the session, not state of this component, so it is recorded even if the
|
||||
// effect was torn down in between.
|
||||
setCurrentPrincipal(principal);
|
||||
if (!cancelled) setIdentityReady(true);
|
||||
})
|
||||
.catch(err => {
|
||||
console.error('[Auth] ensureIdentity failed:', err);
|
||||
if (!cancelled) setSignInError(err instanceof Error ? err.message : String(err));
|
||||
});
|
||||
return () => { cancelled = true; };
|
||||
}, []);
|
||||
|
||||
// Once identified, leave the disconnected welcome screen for the app home.
|
||||
useEffect(() => {
|
||||
if (identityReady && route.page === 'welcome') {
|
||||
navigate('/home');
|
||||
}
|
||||
}, [status, identifier, route.page, navigate]);
|
||||
}, [identityReady, route.page, navigate]);
|
||||
|
||||
// Gate explicitly disabled (no-gate build / @e2e harness) → straight to app.
|
||||
if (GATE_DISABLED) {
|
||||
return <>{children}</>;
|
||||
// Signing in FAILED — say so. The app has nothing legitimate to show, and
|
||||
// showing it anyway would pass a broken session off as an empty one.
|
||||
if (signInError) {
|
||||
return (
|
||||
<div id="auth-error" role="alert" className="app-card" style={{ margin: '2rem 1rem' }}>
|
||||
<h1 className="app-title">Connexion impossible</h1>
|
||||
<p className="app-text">
|
||||
Festipod n’a pas réussi à vous connecter. Rien ne peut s’afficher tant que
|
||||
la connexion n’a pas abouti — les écrans seraient vides sans le dire.
|
||||
</p>
|
||||
<p className="app-text" data-testid="auth-error-detail">{signInError}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// 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}
|
||||
/>
|
||||
);
|
||||
// Signing in is not settled yet. Render NOTHING — the SDK's own full-screen
|
||||
// barrier is what is on screen, it put it there and it takes it down. Anything
|
||||
// of ours here would be a second thing competing with it.
|
||||
if (!identityReady) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// The app.
|
||||
|
||||
+20
-7
@@ -4,19 +4,32 @@
|
||||
*
|
||||
* 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).
|
||||
* Before loading the app tree it pulls the RUNTIME shared-wallet config, sets
|
||||
* the global, then dynamically imports `App` so `sharedWallet.ts` reads the
|
||||
* value on evaluation. A `build.ts` bundle already carries the value inlined by
|
||||
* `define`, and then there is nothing to fetch.
|
||||
*
|
||||
* WHICH ONE APPLIES IS NOT `NODE_ENV`. This used to skip the fetch under
|
||||
* `NODE_ENV=production`, on the reasoning "production means built". This
|
||||
* project's production does NOT build: the container copies the sources and
|
||||
* runs `bun run start` (= `NODE_ENV=production bun src/index.ts`), serving from
|
||||
* src/ exactly as dev does. Nothing ever serves `dist/`. So the deployed app
|
||||
* skipped the only step that could give it a wallet, `ensureIdentity()` threw
|
||||
* for want of one, and it could never sign anybody in — while `/festipod-config.json`
|
||||
* sat there, served and unasked.
|
||||
*
|
||||
* The question is therefore "was the value inlined?", never "am I in
|
||||
* production?" — ask the global itself.
|
||||
*/
|
||||
|
||||
import { StrictMode } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
|
||||
/** Fetch the runtime shared-wallet config and set the global (dev/start only). */
|
||||
/** Fetch the runtime shared-wallet config and set the global, unless it is already there. */
|
||||
async function loadRuntimeConfig(): Promise<void> {
|
||||
if (process.env.NODE_ENV === "production") return; // build.ts define provides it
|
||||
// Already inlined by `build.ts`'s `define` → nothing to fetch. Bracket access,
|
||||
// so that same `define` (which rewrites the dotted global) leaves this read alone.
|
||||
if ((globalThis as Record<string, unknown>)["__FESTIPOD_SHARED_WALLET_PASSWORD__"] != null) return;
|
||||
try {
|
||||
const res = await fetch("/festipod-config.json");
|
||||
if (!res.ok) return;
|
||||
|
||||
+54
-4
@@ -3,6 +3,24 @@ import index from "./index.html";
|
||||
|
||||
const port = process.env.PORT ? parseInt(process.env.PORT) : 3000;
|
||||
|
||||
// Strict base64 check (not a mere `Buffer.from` attempt, which silently drops invalid
|
||||
// characters instead of failing): reject anything that is not a well-formed base64 body
|
||||
// before decoding, so a typo'd env var is reported instead of served as 810 garbage bytes.
|
||||
const BASE64_SHAPE = /^[A-Za-z0-9+/]+={0,2}$/;
|
||||
|
||||
function decodeBase64WalletOrThrow(raw: string) {
|
||||
const trimmed = raw.trim();
|
||||
if (trimmed.length === 0 || trimmed.length % 4 !== 0 || !BASE64_SHAPE.test(trimmed)) {
|
||||
throw new Error("not valid base64 (bad characters, or length not a multiple of 4)");
|
||||
}
|
||||
// Web `atob` (not Node's `Buffer`, whose `ArrayBufferLike` generic doesn't line up
|
||||
// with `Response`'s `BodyInit`) — decodes to a binary string, rebuilt into bytes below.
|
||||
const binary = atob(trimmed);
|
||||
const bytes = new Uint8Array(binary.length);
|
||||
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
|
||||
return bytes;
|
||||
}
|
||||
|
||||
const server = serve({
|
||||
port,
|
||||
routes: {
|
||||
@@ -53,13 +71,45 @@ const server = serve({
|
||||
autoSeed: process.env.FESTIPOD_AUTO_SEED ?? "",
|
||||
}),
|
||||
|
||||
// The shared wallet file (download target of the access barrier), when configured.
|
||||
// The shared wallet file — the `fileUrl` the app hands the SDK, when configured.
|
||||
//
|
||||
// Two sources, read fresh on every request (never captured at module evaluation):
|
||||
// - FESTIPOD_SHARED_WALLET_FILE: a filesystem path. What local dev and the test
|
||||
// harness set today — a file sitting at the working-copy root.
|
||||
// - FESTIPOD_SHARED_WALLET_FILE_BASE64: the file's bytes, base64-encoded. What a
|
||||
// container sets instead, since *.ngw is gitignored and nothing mounts one there.
|
||||
//
|
||||
// Precedence: FILE wins whenever it is set, even if the path turns out unreadable —
|
||||
// it is NOT "whichever resolves". This keeps dev/test behaviour byte-for-byte
|
||||
// unchanged (they set only FILE, never BASE64) and makes the rule predictable: a
|
||||
// deployment picks exactly one variable to set, and setting both is a leftover, not
|
||||
// an intentional fallback chain.
|
||||
"/shared-wallet.ngw": async () => {
|
||||
const p = process.env.FESTIPOD_SHARED_WALLET_FILE;
|
||||
if (p) {
|
||||
const file = Bun.file(p);
|
||||
const path = process.env.FESTIPOD_SHARED_WALLET_FILE;
|
||||
if (path) {
|
||||
const file = Bun.file(path);
|
||||
if (await file.exists()) return new Response(file);
|
||||
return new Response("No shared wallet file configured.", { status: 404 });
|
||||
}
|
||||
|
||||
const encoded = process.env.FESTIPOD_SHARED_WALLET_FILE_BASE64;
|
||||
if (encoded) {
|
||||
// Malformed must fail loudly: a 404 here would look identical to "not
|
||||
// configured", which is exactly the confusion this project is removing.
|
||||
try {
|
||||
const bytes = decodeBase64WalletOrThrow(encoded);
|
||||
return new Response(bytes, {
|
||||
headers: { "Content-Type": "application/octet-stream" },
|
||||
});
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
return new Response(
|
||||
`FESTIPOD_SHARED_WALLET_FILE_BASE64 is set but ${message}.`,
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return new Response("No shared wallet file configured.", { status: 404 });
|
||||
},
|
||||
|
||||
|
||||
@@ -1,27 +0,0 @@
|
||||
# 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,10 +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
|
||||
|
||||
# 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.
|
||||
# NB : Festipod n'affiche plus d'écran d'accès à lui. Se connecter, c'est le
|
||||
# SEUL `ensureIdentity()` attendu par AuthGate ; ce qu'un utilisateur voit ou
|
||||
# fait pendant cette attente appartient au SDK, qui le montre. Aucun scénario
|
||||
# ici ne pilote donc une barrière d'accès.
|
||||
|
||||
# --- Data layer: comportement du portefeuille ---
|
||||
|
||||
|
||||
@@ -1,42 +0,0 @@
|
||||
# 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-level↔iframe (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"
|
||||
@@ -1,183 +0,0 @@
|
||||
/**
|
||||
* 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>
|
||||
);
|
||||
}
|
||||
@@ -5,18 +5,15 @@ import type { FestipodWorld } from '../../../../shared/support/world';
|
||||
// --- Setup ---
|
||||
|
||||
Given('le portefeuille est vide', async function (this: FestipodWorld) {
|
||||
// Each @data scenario runs under a UNIQUE identifier (see hooks.ts
|
||||
// freshScenarioIdentifier), so the shim hands it a FRESH, EMPTY virtual wallet:
|
||||
// "le portefeuille est vide" is trivially true on entry. So this is a fast
|
||||
// INSTANT CHECK — assert the reactive read already shows nothing — NOT the old
|
||||
// `clearWallet` per-entity-doc fan-out (a full physical-wallet enumeration that
|
||||
// was itself slow). No mutation, no polling: a fresh wallet has no docs to scan.
|
||||
// A fast INSTANT CHECK — assert the reactive read already shows nothing — NOT
|
||||
// the old `clearWallet` per-entity-doc fan-out (a full wallet enumeration that
|
||||
// was itself slow). No mutation, no polling.
|
||||
const counts = await this.appFrame!.evaluate(() => {
|
||||
const td = (window as any).__testData;
|
||||
return { events: td.events.size, users: td.users.size };
|
||||
});
|
||||
expect(counts.events, 'Fresh virtual wallet should have no events').to.equal(0);
|
||||
expect(counts.users, 'Fresh virtual wallet should have no users').to.equal(0);
|
||||
expect(counts.events, 'An empty wallet should have no events').to.equal(0);
|
||||
expect(counts.users, 'An empty wallet should have no users').to.equal(0);
|
||||
});
|
||||
|
||||
Given('le portefeuille contient déjà des événements', async function (this: FestipodWorld) {
|
||||
@@ -30,9 +27,12 @@ Given('le portefeuille contient déjà des événements', async function (this:
|
||||
const td = (window as any).__testData;
|
||||
td.loadTestData();
|
||||
});
|
||||
// Wait for data to propagate
|
||||
// Wait for data to propagate. `waitForFunction(fn, arg, options)` — the
|
||||
// timeout goes in the THIRD slot; passed second it is silently taken as the
|
||||
// predicate's argument and the wait runs on the 30s default instead.
|
||||
await this.appFrame!.waitForFunction(
|
||||
() => (window as any).__testData.events.size > 0,
|
||||
undefined,
|
||||
{ timeout: 75000 },
|
||||
);
|
||||
}
|
||||
@@ -72,6 +72,7 @@ When('je charge les données de test', async function (this: FestipodWorld) {
|
||||
const td = (window as any).__testData;
|
||||
return td.events.size > 0 && td.users.size > 0;
|
||||
},
|
||||
undefined,
|
||||
{ timeout: 75000 },
|
||||
).catch(() => {
|
||||
// Timeout tolerated — the assertions below surface the real failure with a
|
||||
|
||||
@@ -136,6 +136,7 @@ When('l\'utilisateur attend la fin du chargement', async function (this: Festipo
|
||||
const buttons = Array.from(document.querySelectorAll('button'));
|
||||
return !buttons.some(b => b.textContent?.includes('Chargement...'));
|
||||
},
|
||||
undefined,
|
||||
{ timeout: 60000 },
|
||||
);
|
||||
await this.appFrame!.waitForTimeout(2000);
|
||||
@@ -152,6 +153,7 @@ Then('l\'écran d\'accueil affiche des événements', async function (this: Fest
|
||||
|
||||
const appeared = await this.appFrame!.waitForFunction(
|
||||
() => document.querySelectorAll('.app-card').length > 0,
|
||||
undefined,
|
||||
{ timeout: 15000 },
|
||||
).then(() => true).catch(() => false);
|
||||
|
||||
|
||||
@@ -1,123 +0,0 @@
|
||||
/**
|
||||
* @ui steps for the access barrier (AccessGateScreen).
|
||||
*
|
||||
* These render the prop-driven AccessGateScreen directly (via renderElement) —
|
||||
* it is NOT a registry/route screen, its state comes from props (status,
|
||||
* initialIdentifier, onEnter). We assert on the rendered DOM: the identifier
|
||||
* field is PREFILLED from the stored value, and "Entrer" reports the identifier.
|
||||
*
|
||||
* Guards the reported regression: on return the barrier used to re-ask for a
|
||||
* bare, empty identifier despite one being stored. See AuthGate.tsx.
|
||||
*
|
||||
* SHARED WALLET IS THE SOLE SUPPORTED MODE (see AccessGateScreen header): the
|
||||
* identifier field lives INSIDE the assisted-import flow, which renders only when
|
||||
* a shared wallet is configured; otherwise the barrier shows a config-error with
|
||||
* NO field. Production always configures one, but the @ui node harness does not
|
||||
* inject the build global, so we set it HERE — before the screen module is first
|
||||
* imported, so `sharedWallet.ts` captures it at module-eval — and lazy-import the
|
||||
* screen. This file is the only @ui module that reaches sharedWallet.ts, so this
|
||||
* ordering is deterministic.
|
||||
*/
|
||||
import { Given, When, Then } from '@cucumber/cucumber';
|
||||
import { expect } from 'chai';
|
||||
import React from 'react';
|
||||
import { renderElement } from '../../../../shared/test-harness/renderHelper';
|
||||
import type { FestipodWorld } from '../../../../shared/support/world';
|
||||
|
||||
globalThis.__FESTIPOD_SHARED_WALLET_PASSWORD__ = 'test-shared-wallet';
|
||||
|
||||
// Lazy so sharedWallet.ts evaluates AFTER the global above is set (a static
|
||||
// import would hoist above it, capturing an empty password → config-error).
|
||||
type Gate = typeof import('../../screens/AccessGateScreen')['AccessGateScreen'];
|
||||
let gateComponent: Gate | null = null;
|
||||
async function loadGate(): Promise<Gate> {
|
||||
if (!gateComponent) {
|
||||
gateComponent = (await import('../../screens/AccessGateScreen')).AccessGateScreen;
|
||||
}
|
||||
return gateComponent;
|
||||
}
|
||||
|
||||
// Local per-scenario state (kept off the World to avoid touching its type).
|
||||
interface GateState {
|
||||
doc: Document | null;
|
||||
entered: string | null;
|
||||
}
|
||||
const gateStates = new WeakMap<object, GateState>();
|
||||
function stateFor(world: object): GateState {
|
||||
let s = gateStates.get(world);
|
||||
if (!s) {
|
||||
s = { doc: null, entered: null };
|
||||
gateStates.set(world, s);
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
async function renderGate(world: object, initialIdentifier?: string): Promise<void> {
|
||||
const s = stateFor(world);
|
||||
s.entered = null;
|
||||
const AccessGateScreen = await loadGate();
|
||||
// 'connecting' would disable the button; 'disconnected' is the returning-user
|
||||
// state (session not yet restored) — the exact case that re-prompted before.
|
||||
s.doc = await renderElement(
|
||||
React.createElement(AccessGateScreen, {
|
||||
status: 'disconnected',
|
||||
initialIdentifier,
|
||||
onEnter: (id: string) => {
|
||||
s.entered = id;
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
Given(
|
||||
'la barrière d\'accès s\'affiche avec l\'identifiant stocké {string}',
|
||||
async function (this: FestipodWorld, identifier: string) {
|
||||
await renderGate(this, identifier);
|
||||
},
|
||||
);
|
||||
|
||||
Given(
|
||||
'la barrière d\'accès s\'affiche sans identifiant stocké',
|
||||
async function (this: FestipodWorld) {
|
||||
await renderGate(this, '');
|
||||
},
|
||||
);
|
||||
|
||||
function identifierField(world: object): HTMLInputElement {
|
||||
const s = stateFor(world);
|
||||
expect(s.doc, 'The access barrier should be rendered').to.not.be.null;
|
||||
const input = s.doc!.querySelector('[data-testid="identifier-input"]') as HTMLInputElement | null;
|
||||
expect(input, 'The identifier field should be present').to.not.be.null;
|
||||
return input!;
|
||||
}
|
||||
|
||||
Then(
|
||||
'le champ identifiant contient {string}',
|
||||
function (this: FestipodWorld, expected: string) {
|
||||
expect(identifierField(this).value).to.equal(expected);
|
||||
},
|
||||
);
|
||||
|
||||
Then('le champ identifiant est vide', function (this: FestipodWorld) {
|
||||
expect(identifierField(this).value).to.equal('');
|
||||
});
|
||||
|
||||
When('je clique sur {string} dans la barrière', function (this: FestipodWorld, _label: string) {
|
||||
const s = stateFor(this);
|
||||
const input = identifierField(this);
|
||||
// Submit via Enter on the field (canEnter is satisfied by the prefilled value).
|
||||
const KeyboardEventCtor = (globalThis as { KeyboardEvent?: typeof KeyboardEvent }).KeyboardEvent;
|
||||
const evt = KeyboardEventCtor
|
||||
? new KeyboardEventCtor('keydown', { key: 'Enter', bubbles: true })
|
||||
: Object.assign(new (globalThis as { Event: typeof Event }).Event('keydown', { bubbles: true }), { key: 'Enter' });
|
||||
input.dispatchEvent(evt);
|
||||
expect(s.doc, 'The access barrier should be rendered').to.not.be.null;
|
||||
});
|
||||
|
||||
Then(
|
||||
'l\'identifiant remonté à l\'application est {string}',
|
||||
function (this: FestipodWorld, expected: string) {
|
||||
const s = stateFor(this);
|
||||
expect(s.entered, 'onEnter should have been called with the identifier').to.equal(expected);
|
||||
},
|
||||
);
|
||||
@@ -1,111 +0,0 @@
|
||||
/**
|
||||
* @ui steps for AccountContext identifier resolution.
|
||||
*
|
||||
* Guards the cross-frontier fix: the shared-wallet flow runs the app in TWO
|
||||
* localStorage partitions (top-level 127.0.0.1 vs broker iframe nextgraph.net),
|
||||
* so localStorage does NOT cross. The `?id=` URL param — embedded in the broker
|
||||
* redirect `o=` — DOES cross. AccountContext resolution therefore PRIORITIZES the
|
||||
* URL param over localStorage, and (when present) persists it to localStorage for
|
||||
* same-partition convenience. Normalization (trim, `@`-strip, lowercase) applies.
|
||||
*
|
||||
* These render a tiny probe inside a real AccountProvider (via renderElement),
|
||||
* having first seeded window.location.search and window.localStorage through the
|
||||
* happy-dom harness — so the resolution logic runs for real, not mocked.
|
||||
*/
|
||||
import { Given, When, Then } from '@cucumber/cucumber';
|
||||
import { expect } from 'chai';
|
||||
import React from 'react';
|
||||
import {
|
||||
renderElement,
|
||||
setRenderUrl,
|
||||
setRenderLocalStorage,
|
||||
getRenderLocalStorage,
|
||||
} from '../../../../shared/test-harness/renderHelper';
|
||||
import { AccountProvider, useAccount } from '../../../../shared/context/AccountContext';
|
||||
import type { FestipodWorld } from '../../../../shared/support/world';
|
||||
|
||||
const STORAGE_KEY = 'festipod.account.identifier';
|
||||
|
||||
// Per-scenario intent (kept off the World type via a WeakMap).
|
||||
interface ResolveState {
|
||||
storageSeed: string | null;
|
||||
url: string;
|
||||
doc: Document | null;
|
||||
}
|
||||
const states = new WeakMap<object, ResolveState>();
|
||||
function stateFor(world: object): ResolveState {
|
||||
let s = states.get(world);
|
||||
if (!s) {
|
||||
s = { storageSeed: null, url: 'http://localhost/', doc: null };
|
||||
states.set(world, s);
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
// Probe: renders the resolved identifier so the DOM can be asserted.
|
||||
function IdentifierProbe(): React.ReactElement {
|
||||
const { identifier } = useAccount();
|
||||
return React.createElement('div', { 'data-testid': 'resolved-identifier' }, identifier ?? '');
|
||||
}
|
||||
|
||||
Given(
|
||||
'localStorage contient l\'identifiant {string}',
|
||||
function (this: FestipodWorld, value: string) {
|
||||
stateFor(this).storageSeed = value;
|
||||
},
|
||||
);
|
||||
|
||||
Given('localStorage ne contient aucun identifiant', function (this: FestipodWorld) {
|
||||
stateFor(this).storageSeed = null;
|
||||
});
|
||||
|
||||
Given('l\'URL porte le param id {string}', function (this: FestipodWorld, id: string) {
|
||||
const s = stateFor(this);
|
||||
const url = new URL('http://localhost/');
|
||||
url.searchParams.set('id', id);
|
||||
s.url = url.toString();
|
||||
});
|
||||
|
||||
Given('l\'URL ne porte aucun param id', function (this: FestipodWorld) {
|
||||
stateFor(this).url = 'http://localhost/';
|
||||
});
|
||||
|
||||
When('le contexte de compte résout l\'identifiant', async function (this: FestipodWorld) {
|
||||
const s = stateFor(this);
|
||||
// Seed the happy-dom window (URL + localStorage) BEFORE mounting the provider,
|
||||
// so the provider's init-time resolution reads exactly this state.
|
||||
await setRenderUrl(s.url);
|
||||
await setRenderLocalStorage(STORAGE_KEY, s.storageSeed);
|
||||
s.doc = await renderElement(
|
||||
React.createElement(AccountProvider, null, React.createElement(IdentifierProbe)),
|
||||
);
|
||||
});
|
||||
|
||||
function resolved(world: object): string {
|
||||
const s = stateFor(world);
|
||||
expect(s.doc, 'The probe should be rendered').to.not.be.null;
|
||||
const el = s.doc!.querySelector('[data-testid="resolved-identifier"]');
|
||||
expect(el, 'The resolved-identifier probe should be present').to.not.be.null;
|
||||
return el!.textContent ?? '';
|
||||
}
|
||||
|
||||
Then('l\'identifiant résolu est {string}', function (this: FestipodWorld, expected: string) {
|
||||
expect(resolved(this)).to.equal(expected);
|
||||
});
|
||||
|
||||
Then(
|
||||
'localStorage contient désormais l\'identifiant {string}',
|
||||
async function (this: FestipodWorld, expected: string) {
|
||||
// The URL-param → localStorage persistence runs in a mount useEffect, which
|
||||
// React flushes AFTER the render's first microtask. Yield a few macrotask
|
||||
// ticks (bounded, no polling of any live resource) so the effect has run
|
||||
// before asserting — otherwise the read races the effect and flakes.
|
||||
let stored: string | null = null;
|
||||
for (let i = 0; i < 10; i++) {
|
||||
stored = await getRenderLocalStorage(STORAGE_KEY);
|
||||
if (stored === expected) break;
|
||||
await new Promise((r) => setTimeout(r, 0));
|
||||
}
|
||||
expect(stored).to.equal(expected);
|
||||
},
|
||||
);
|
||||
@@ -1,5 +1,12 @@
|
||||
# language: fr
|
||||
@EVENT @priority-1
|
||||
# SUSPENDU (@wip) le 2026-08-03 — l'index global de découverte a été RETIRÉ du SDK :
|
||||
# il n'y a pas de découverte, on ne joint un document qu'en suivant un lien reçu.
|
||||
# Ce scénario décrit donc une capacité qui n'existe plus telle quelle. Il est
|
||||
# conservé, non supprimé : le besoin produit demeure, et il sera réalisé par un
|
||||
# ANNUAIRE Festipod — un document public dont l'app connaît le lien, alimenté par
|
||||
# dépôt et matérialisé par son curateur. À ce moment-là ce scénario est réécrit
|
||||
# sur l'annuaire et redevient actif.
|
||||
@EVENT @priority-1 @wip
|
||||
Fonctionnalité: Découverte publique via l'index global
|
||||
En tant qu'utilisateur
|
||||
Je veux découvrir les événements publics des autres comptes sans être connecté
|
||||
|
||||
@@ -60,8 +60,7 @@ Fonctionnalité: Validation e2e multi-navigateurs des nouvelles features (T02.f)
|
||||
# vise pas « sans reload ».
|
||||
#
|
||||
# FIX (appliqué) : la matérialisation du propriétaire lit l'inbox APRÈS sa barrière
|
||||
# de sync (`inbox.readSynced` → `ensureRepoOpen` + `read`, lib
|
||||
# `@ng-eventually/client`), de sorte qu'un dépôt de l'inscrit déjà synchronisé au
|
||||
# de sync (`inbox.readSynced`, SDK `@ng-eventually/polyfill`), de sorte qu'un dépôt de l'inscrit déjà synchronisé au
|
||||
# broker EST vu (plus de « 0 prématuré » mémoïsé) ; le materializer est lancé
|
||||
# directement à la connexion ([ready, ownedKey]), pas seulement sur un push
|
||||
# d'inbox. Source unique du NOMBRE : `event.participantCount` (le littéral local
|
||||
|
||||
@@ -1,21 +1,21 @@
|
||||
# language: fr
|
||||
@EVENT @priority-1 @data
|
||||
# SUSPENDU (@wip) — comportement Festipod bien réel, mais inexprimable aujourd'hui : il faut DEUX contextes navigateur réellement séparés, chacun se connectant pour lui-même via `ensureIdentity()`, ce que le support multi-navigateur n'offre pas encore.
|
||||
@EVENT @priority-1 @data @wip
|
||||
Fonctionnalité: Isolation entre deux identités sur le wallet partagé
|
||||
En tant qu'utilisateur qui nomme son espace virtuel par un identifiant à la
|
||||
barrière d'accès, sur le MÊME wallet physique partagé,
|
||||
En tant qu'utilisateur qui se connecte pour lui-même, sur le MÊME wallet
|
||||
physique partagé qu'un autre utilisateur,
|
||||
Je ne dois voir NI l'inscription NI l'accueil d'une autre identité
|
||||
Afin que les participations restent privées à leur propriétaire.
|
||||
|
||||
# Régression du leak d'isolation : une identité A crée un événement et le
|
||||
# rejoint ; une identité fraîche B arrive sur le même wallet (faux-logout +
|
||||
# re-login sous un autre identifiant, sans reload — le stopgap wallet-partagé).
|
||||
# rejoint ; une identité fraîche B arrive sur le même wallet physique, dans son
|
||||
# propre contexte navigateur, et se connecte pour elle-même.
|
||||
# B ne doit PAS voir la participation de A : ni sur son accueil
|
||||
# (getUserEvents(B)), ni via isParticipating(E, B), ni dans son set de
|
||||
# participations réactif. Le mécanisme : le changement d'identifiant est traité
|
||||
# comme une session fraîche (reset du jeu de lecture + caps + registre), sinon
|
||||
# les docs PROTECTED de A survivent dans le jeu de lecture de B et fuient par la
|
||||
# lecture union. Voir data-layer/knowledge_context-internals § « Changement
|
||||
# d'identité = session fraîche ».
|
||||
# participations réactif. Ce qui est sous test, c'est le comportement de
|
||||
# Festipod : rien de ce que l'app affiche à B ne provient des documents
|
||||
# PROTECTED de A, quand bien même les deux identités vivent sur un seul wallet
|
||||
# physique.
|
||||
|
||||
@data
|
||||
Scénario: Une identité fraîche ne voit pas la participation d'une autre
|
||||
|
||||
@@ -79,25 +79,34 @@ export function CreateEventScreen() {
|
||||
? (endDate ? `${startDate} - ${endDate}` : startDate)
|
||||
: 'Date à définir';
|
||||
|
||||
const newEvent = await createEvent({
|
||||
title: name || 'Nouvel événement',
|
||||
date: dateLabel,
|
||||
startDate,
|
||||
endDate,
|
||||
startTime,
|
||||
endTime,
|
||||
location: location || 'Lieu à définir',
|
||||
description,
|
||||
// Option B: the creator does NOT auto-participate (no host notion). The count
|
||||
// starts at 0 and is DERIVED by the owner-materializer from real inbox
|
||||
// deposits (|active registrations|) — never a local literal. Passing 1 here was
|
||||
// the "local number" bug: the creator's own view showed 1 while the derived
|
||||
// truth (and every other viewer) was 0.
|
||||
participantCount: 0,
|
||||
themes: ['Social'],
|
||||
hostName: 'Moi',
|
||||
hostInitials: 'MD',
|
||||
});
|
||||
// A creation that cannot be recorded FAILS — it never hands back an event
|
||||
// that would read empty forever. So the success toast and the navigation
|
||||
// belong AFTER the create resolves, and a failure must say so rather than
|
||||
// send the user to a page for an event that does not exist.
|
||||
let newEvent;
|
||||
try {
|
||||
newEvent = await createEvent({
|
||||
title: name || 'Nouvel événement',
|
||||
date: dateLabel,
|
||||
startDate,
|
||||
endDate,
|
||||
startTime,
|
||||
endTime,
|
||||
location: location || 'Lieu à définir',
|
||||
description,
|
||||
// Option B: the creator does NOT auto-participate (no host notion). The count
|
||||
// starts at 0 and is DERIVED by the owner-materializer from real inbox
|
||||
// deposits (|active registrations|) — never a local literal. Passing 1 here was
|
||||
// the "local number" bug: the creator's own view showed 1 while the derived
|
||||
// truth (and every other viewer) was 0.
|
||||
participantCount: 0,
|
||||
themes: ['Social'],
|
||||
});
|
||||
} catch (err) {
|
||||
console.error('[CreateEvent] createEvent failed:', err);
|
||||
showToast("L'événement n'a pas pu être relayé", 'error');
|
||||
return;
|
||||
}
|
||||
showToast('Événement relayé', 'success');
|
||||
navigate(`/events/${newEvent.id}`);
|
||||
};
|
||||
@@ -227,11 +236,6 @@ export function CreateEventScreen() {
|
||||
<Text style={{ margin: '4px 0', fontSize: 13, color: '#888' }}>
|
||||
{ev.date} · {ev.location}
|
||||
</Text>
|
||||
{ev.hostName && (
|
||||
<Text style={{ margin: '0 0 10px 0', fontSize: 12, color: '#888' }}>
|
||||
Relayé par {ev.hostName}
|
||||
</Text>
|
||||
)}
|
||||
<Button
|
||||
variant="primary"
|
||||
style={{ width: '100%', padding: 10, fontSize: 13 }}
|
||||
|
||||
@@ -14,6 +14,7 @@ export function EventDetailScreen() {
|
||||
leaveEvent,
|
||||
getEventParticipants,
|
||||
getEventMeetingPoints,
|
||||
getEventOwnership,
|
||||
} = useFestipodData();
|
||||
|
||||
const event = eventId ? getEvent(eventId) : undefined;
|
||||
@@ -29,7 +30,19 @@ export function EventDetailScreen() {
|
||||
lieu: mp.location,
|
||||
}));
|
||||
|
||||
const isOwner = true;
|
||||
// EDITING IS OWNING. Only a document's owner writes to it, and nothing delegates
|
||||
// a write, so "may I edit this event" is answered entirely by whether this
|
||||
// session owns the event's document — no permission call, no extra read.
|
||||
//
|
||||
// The third answer, `'unknown'`, is rendered as a DISABLED affordance rather
|
||||
// than resolved either way. Hiding it would be the worst outcome: an owner
|
||||
// would be told, silently and wrongly, that their own event is not theirs, with
|
||||
// nothing on screen to suggest otherwise. Showing it live would be the opposite
|
||||
// lie — a control that promises an edit it may not be able to make, and only
|
||||
// says so after the person has typed. Visible-but-inert says the true thing:
|
||||
// the answer is still coming.
|
||||
const ownership = eventId ? getEventOwnership(eventId) : 'unknown';
|
||||
const canEdit = ownership === 'mine';
|
||||
// Preview list shows the OTHER participants (deliberate — the total is in the
|
||||
// header count; the full list at "Voir tous les participants" shows everyone).
|
||||
// Compare on the PROFILE id: `currentUser.id` is the resolved profile NURI, the
|
||||
@@ -40,12 +53,23 @@ export function EventDetailScreen() {
|
||||
|
||||
const handleToggleJoin = () => {
|
||||
if (!eventId) return;
|
||||
// THE CONFIRMATION FOLLOWS THE WRITE. It used to be shown on the spot, before
|
||||
// the call had settled, so a sign-up that wrote nothing still read as
|
||||
// « Tu participes ». The screen's own list flips immediately anyway (the data
|
||||
// layer's optimistic overlay), so nothing is lost by waiting for the truth.
|
||||
const confirmed = (message: string, tone: 'success' | 'info') => () => showToast(message, tone);
|
||||
const failed = (message: string) => (err: unknown) => {
|
||||
console.error('[EventDetail] participation write failed:', err);
|
||||
showToast(message, 'error');
|
||||
};
|
||||
if (joined) {
|
||||
leaveEvent(eventId);
|
||||
showToast('Participation annulée', 'info');
|
||||
void Promise.resolve(leaveEvent(eventId))
|
||||
.then(confirmed('Participation annulée', 'info'))
|
||||
.catch(failed("La désinscription n'a pas pu être enregistrée"));
|
||||
} else {
|
||||
joinEvent(eventId);
|
||||
showToast('Tu participes à cet événement', 'success');
|
||||
void Promise.resolve(joinEvent(eventId))
|
||||
.then(confirmed('Tu participes à cet événement', 'success'))
|
||||
.catch(failed("L'inscription n'a pas pu être enregistrée"));
|
||||
}
|
||||
};
|
||||
|
||||
@@ -74,8 +98,25 @@ export function EventDetailScreen() {
|
||||
<div style={{ fontSize: 12, color: '#888' }}>{event.distance} km</div>
|
||||
)}
|
||||
</div>
|
||||
{isOwner && (
|
||||
<span onClick={() => navigate(`/events/${eventId}/edit`)} style={{ cursor: 'pointer', fontSize: 18, color: '#888' }}>✎</span>
|
||||
{canEdit && (
|
||||
<span
|
||||
onClick={() => navigate(`/events/${eventId}/edit`)}
|
||||
title="Modifier l'événement"
|
||||
style={{ cursor: 'pointer', fontSize: 18, color: '#888' }}
|
||||
>✎</span>
|
||||
)}
|
||||
{ownership === 'unknown' && (
|
||||
// DELIBERATELY NOT A ✎. The slot stays occupied, so an owner is never
|
||||
// silently told the event is not theirs — but a pending control must
|
||||
// not look like the actionable one it is not: a greyed-out twin of the
|
||||
// pencil reads as "edit, broken" and invites a click that does nothing.
|
||||
// A distinct mark reads as "still working it out", which is the truth.
|
||||
<span
|
||||
aria-busy="true"
|
||||
aria-label="Vérification de vos droits de modification"
|
||||
title="Vérification de vos droits de modification…"
|
||||
style={{ cursor: 'default', fontSize: 18, color: '#ddd' }}
|
||||
>⋯</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
|
||||
@@ -26,8 +26,6 @@ export function MeetingPointsScreen() {
|
||||
eventId,
|
||||
location: title || lieu || 'Point de rencontre',
|
||||
time: when || duration,
|
||||
hostName: currentUser?.name?.split(' ')[0] ?? 'Moi',
|
||||
hostInitials: currentUser?.initials ?? '?',
|
||||
});
|
||||
showToast(title ? `Point de rencontre créé : ${title}` : 'Point de rencontre créé', 'success');
|
||||
navigate(`/events/${eventId}`);
|
||||
|
||||
@@ -6,8 +6,16 @@ import { useNavigate, useParams } from '../../../app/router';
|
||||
export function UpdateEventScreen() {
|
||||
const navigate = useNavigate();
|
||||
const { eventId } = useParams();
|
||||
const { getEvent, updateEvent } = useFestipodData();
|
||||
const { getEvent, updateEvent, getEventOwnership } = useFestipodData();
|
||||
const event = eventId ? getEvent(eventId) : undefined;
|
||||
// THE ROUTE IS GUARDED BY THE SAME ANSWER EventDetailScreen uses for its pencil
|
||||
// icon — "editing is owning", so there is nothing else to ask. `'unknown'` is a
|
||||
// real third case (the owned-document listing may not have landed yet), and it
|
||||
// is rendered as its OWN pending state below rather than folded into either
|
||||
// side: showing the form would let a non-owner edit on a still-resolving
|
||||
// guess, and bouncing the user out would tell an actual owner, wrongly, that
|
||||
// the event is not theirs.
|
||||
const ownership = eventId ? getEventOwnership(eventId) : 'unknown';
|
||||
|
||||
const [title, setTitle] = useState(event?.title ?? '');
|
||||
const [startDate, setStartDate] = useState(event?.startDate ?? '');
|
||||
@@ -22,7 +30,11 @@ export function UpdateEventScreen() {
|
||||
const dateLabel = startDate
|
||||
? (endDate ? `${startDate} - ${endDate}` : startDate)
|
||||
: event?.date ?? '';
|
||||
updateEvent(eventId, {
|
||||
// THE CONFIRMATION FOLLOWS THE WRITE — same idiom as EventDetailScreen's
|
||||
// participation toggle. Showing the toast and navigating away before
|
||||
// `updateEvent` has settled announced success whether or not anything was
|
||||
// actually written; a rejection must be told as a failure, not swallowed.
|
||||
void Promise.resolve(updateEvent(eventId, {
|
||||
title,
|
||||
date: dateLabel,
|
||||
startDate,
|
||||
@@ -31,11 +43,54 @@ export function UpdateEventScreen() {
|
||||
endTime,
|
||||
location,
|
||||
description,
|
||||
});
|
||||
showToast('Événement mis à jour', 'success');
|
||||
navigate(`/events/${eventId}`);
|
||||
}))
|
||||
.then(() => {
|
||||
showToast('Événement mis à jour', 'success');
|
||||
navigate(`/events/${eventId}`);
|
||||
})
|
||||
.catch((err: unknown) => {
|
||||
console.error('[UpdateEvent] event update failed:', err);
|
||||
showToast("La modification n'a pas pu être enregistrée", 'error');
|
||||
});
|
||||
};
|
||||
|
||||
if (ownership === 'not-mine') {
|
||||
// A resolved, definitive answer — not a guess. Block the form outright
|
||||
// rather than let a non-owner type into a write that will only ever reject.
|
||||
return (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
|
||||
<Header
|
||||
title="Modifier l'événement"
|
||||
left={<span onClick={() => navigate(`/events/${eventId}`)} style={{ cursor: 'pointer', fontSize: 18 }}>✕</span>}
|
||||
/>
|
||||
<div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 16 }}>
|
||||
<Text style={{ textAlign: 'center', color: '#888' }}>
|
||||
Vous ne pouvez pas modifier cet événement.
|
||||
</Text>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (ownership === 'unknown') {
|
||||
// The listing hasn't landed yet — neither "mine" nor "not mine" is true, so
|
||||
// neither the form nor a bounce-out is shown. Same wording as
|
||||
// EventDetailScreen's pending pencil affordance.
|
||||
return (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
|
||||
<Header
|
||||
title="Modifier l'événement"
|
||||
left={<span onClick={() => navigate(`/events/${eventId}`)} style={{ cursor: 'pointer', fontSize: 18 }}>✕</span>}
|
||||
/>
|
||||
<div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 16 }}>
|
||||
<Text aria-busy="true" style={{ textAlign: 'center', color: '#888' }}>
|
||||
Vérification de vos droits de modification…
|
||||
</Text>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
|
||||
<Header
|
||||
|
||||
@@ -1,18 +1,18 @@
|
||||
import { Given, When, Then } from '@cucumber/cucumber';
|
||||
import { Given, Then } from '@cucumber/cucumber';
|
||||
import { expect } from 'chai';
|
||||
import type { FestipodWorld } from '../../../../shared/support/world';
|
||||
import { pool } from '../../../../shared/support/browserPool';
|
||||
|
||||
// Two-identity isolation (@data, real broker). Identity A (the fresh per-scenario
|
||||
// identifier set in localStorage) creates an event E and joins it; a genuinely-
|
||||
// different identity B is brought up on the SAME wallet; B must read NONE of A's
|
||||
// protected participation, E must not be on B's home, isParticipating(E,B) false.
|
||||
// Isolation entre deux utilisateurs (@data, broker réel). A crée un événement et
|
||||
// s'y inscrit ; B ne doit rien lire de la participation PROTECTED de A.
|
||||
//
|
||||
// B is brought up via a FRESH PAGE on the SAME persistent wallet context with B's
|
||||
// identifier in localStorage — the closest analogue to the real app's re-enter-
|
||||
// gate / reload path (a brand-new NgDataProvider mount, identifier=B, on a wallet
|
||||
// that already holds A's docs). This exercises the identity-switch reset that
|
||||
// keeps A's protected docs out of B's read set.
|
||||
// LE « QUAND » DE CE SCÉNARIO N'EXISTE PLUS ICI, et c'est délibéré : faire venir B
|
||||
// demande son PROPRE contexte navigateur avec son PROPRE wallet — deux personnes
|
||||
// sur deux appareils. Un contexte navigateur est UN utilisateur, et `ensureIdentity()`
|
||||
// dit lequel ; rien ne le choisit. Le scénario est donc suspendu (@wip dans
|
||||
// isolation-deux-identites.feature) jusqu'à ce que le harness sache monter un second
|
||||
// contexte avec son wallet à lui. Le Given ci-dessous reste : il est réutilisé par
|
||||
// les scénarios de reconnexion. Les Alors restent aussi — les assertions sont
|
||||
// intactes, c'est le montage de B qui manque.
|
||||
|
||||
Given('l\'identité A crée l\'événement {string} et s\'y inscrit', { timeout: 180000 }, async function (this: FestipodWorld, title: string) {
|
||||
const out = await this.appFrame!.evaluate(async (title) => {
|
||||
@@ -37,28 +37,8 @@ Given('l\'identité A crée l\'événement {string} et s\'y inscrit', { timeout:
|
||||
(this as any).isoAId = out.aId;
|
||||
});
|
||||
|
||||
When('une identité fraîche B arrive sur le même wallet partagé', { timeout: 120000 }, async function (this: FestipodWorld) {
|
||||
const bId = `iso-b-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`;
|
||||
(this as any).isoBId = bId;
|
||||
const ctx = this.page!.context();
|
||||
const bPage = await ctx.newPage();
|
||||
await bPage.addInitScript((u: string) => {
|
||||
try { window.localStorage.setItem('festipod.account.identifier', u); } catch { /* opaque */ }
|
||||
}, bId);
|
||||
await bPage.addInitScript(() => {
|
||||
(globalThis as Record<string, unknown>).__FESTIPOD_ACCESS_GATE_DISABLED__ = true;
|
||||
});
|
||||
bPage.on('console', (msg) => { if (msg.type() === 'error') console.error('[Bpage console]', msg.text()); });
|
||||
const bFrame = await pool.setupBrokerPage!(bPage, pool.harnessUrl!);
|
||||
await bFrame.waitForFunction(() => (window as any).__testData?.ready === true, { timeout: 60000 });
|
||||
// Let B's listing effect + union read run (rebuilds the read set bounded to B).
|
||||
await bFrame.evaluate(async () => {
|
||||
const td = (window as any).__testData;
|
||||
await td.ensureCurrentUser();
|
||||
await new Promise(r => setTimeout(r, 6000));
|
||||
});
|
||||
(this as any).isoBFrame = bFrame;
|
||||
});
|
||||
// Le « Quand une identité fraîche B arrive… » n'a pas d'équivalent : il faut à B son
|
||||
// propre contexte navigateur avec son propre wallet (voir l'en-tête de ce fichier).
|
||||
|
||||
Then('l\'événement {string} n\'est pas sur l\'accueil de B', async function (this: FestipodWorld, title: string) {
|
||||
const bFrame = (this as any).isoBFrame;
|
||||
|
||||
@@ -31,8 +31,6 @@ When(
|
||||
'un navigateur frais non-persistant recharge pour la MÊME identité A avec le wallet partagé',
|
||||
{ timeout: 120000 },
|
||||
async function (this: FestipodWorld) {
|
||||
// SAME identity A: the per-scenario virtual identifier set by the Before hook.
|
||||
const aIdentifier = (this as any).freshIdentifier as string;
|
||||
if (!pool.sharedWalletState) {
|
||||
throw new Error(
|
||||
'sharedWalletState non capturé au BeforeAll — impossible de provisionner un ' +
|
||||
@@ -41,25 +39,16 @@ When(
|
||||
);
|
||||
}
|
||||
|
||||
// FRESH, non-persistent, hermetic context seeded with ONLY the shared wallet
|
||||
// storageState (captured before A's event existed). Separate storage partition
|
||||
// from the persistent write page → no shared IndexedDB, no local copy of A's
|
||||
// just-created event. Its ONLY source for A's event is the broker.
|
||||
// FRESH, non-persistent, hermetic context seeded with ONLY the deployment
|
||||
// wallet's storageState (captured before A's event existed). Separate storage
|
||||
// partition from the persistent write page → no shared IndexedDB, no local copy
|
||||
// of A's just-created event. Its ONLY source for A's event is the broker.
|
||||
// It comes up as the SAME person because it opens the SAME wallet — that is
|
||||
// what makes this a reconnect, and nothing here names an identity.
|
||||
const ctx = await spawnContext('shared');
|
||||
(this as any).recoColdCtx = ctx; // closed by freshBrowser.close() in AfterAll
|
||||
const freshPage = await ctx.newPage();
|
||||
|
||||
// SAME identity A: inject A's app-level identifier on every origin BEFORE any
|
||||
// script (incl. the harness iframe on 127.0.0.1), so the shim keys to the SAME
|
||||
// virtual account A — a reconnect, not an identity switch. Identical injection
|
||||
// to isolation.steps.ts / reconnexion.steps.ts, but into a FRESH context.
|
||||
await freshPage.addInitScript((u: string) => {
|
||||
try { window.localStorage.setItem('festipod.account.identifier', u); } catch { /* opaque */ }
|
||||
}, aIdentifier);
|
||||
await freshPage.addInitScript(() => {
|
||||
(globalThis as Record<string, unknown>).__FESTIPOD_ACCESS_GATE_DISABLED__ = true;
|
||||
});
|
||||
|
||||
// Broad console capture (ALL types) so the SDK diagnostic lines
|
||||
// (BARRIER synced|timed-out, OUTBOX, readScopeIndex → N, CONNECTION ESTABLISHED,
|
||||
// REPLAY TOPIC NOT FOUND, …) surface verbatim to stdout as the verdict's proof.
|
||||
@@ -72,6 +61,7 @@ When(
|
||||
const freshFrame = await pool.setupBrokerPage!(freshPage, pool.harnessUrl!);
|
||||
await freshFrame.waitForFunction(
|
||||
() => (window as any).__testData?.ready === true,
|
||||
undefined,
|
||||
{ timeout: 60000 },
|
||||
);
|
||||
// Resolve A's principal (profile read hydrated) before the reactive Then reads.
|
||||
|
||||
@@ -3,23 +3,18 @@ import { expect } from 'chai';
|
||||
import type { FestipodWorld } from '../../../../shared/support/world';
|
||||
import { pool } from '../../../../shared/support/browserPool';
|
||||
|
||||
// RECONNECTION of the SAME identity on the SAME persistent wallet (@data, real
|
||||
// broker). Distinct from the two-identity isolation scenario: here the fresh page
|
||||
// re-enters under the SAME identifier A (same virtual wallet), on a NEW broker
|
||||
// login (fresh verifier session). The defect under test: the fresh page reads its
|
||||
// OWN data EMPTY (home=[], isParticipating=false, authCount=0) because the anchored
|
||||
// listing path (listMyEntityDocs → readScopeIndex, then readUnion/readDoc) queries
|
||||
// repos not yet in `self.repos` at cold-start and silently returns 0 rows.
|
||||
// RECONNECTION of the same user on the same persistent wallet (@data, real
|
||||
// broker). The fresh page re-enters on a NEW broker login (fresh verifier
|
||||
// session). The defect under test: the fresh page reads its OWN data EMPTY
|
||||
// (home=[], isParticipating=false, authCount=0) because the anchored listing path
|
||||
// (listMyEntityDocs → readScopeIndex, then readUnion/readDoc) queries repos not
|
||||
// yet in `self.repos` at cold-start and silently returns 0 rows.
|
||||
//
|
||||
// Identity A is the scenario's fresh virtual-wallet identifier (this.freshIdentifier, set
|
||||
// by the Before hook into localStorage on every origin). A creates E via the REAL
|
||||
// app path (createEventReal) and joins it (appJoinEvent) on the MAIN page. Then a
|
||||
// FRESH PAGE is brought up on the SAME persistent wallet context with the SAME
|
||||
// identifier A in localStorage BEFORE any script — the closest analogue to the real
|
||||
// app's re-enter-gate / reload path (a brand-new NgDataProvider mount + a fresh
|
||||
// broker session that must re-open A's own repos). Montage identical to
|
||||
// isolation.steps.ts, except the fresh page reuses this.freshIdentifier (SAME A) rather
|
||||
// than minting a new identifier B.
|
||||
// A creates E via the REAL app path (createEventReal) and joins it (appJoinEvent)
|
||||
// on the MAIN page. Then a FRESH PAGE is opened on the SAME browser context — one
|
||||
// context is one user, so that page comes up as the same person, and it is the
|
||||
// closest analogue to the real app's re-entry / reload path (a brand-new
|
||||
// NgDataProvider mount + a fresh broker session that must re-open A's own repos).
|
||||
|
||||
// The Given "l'identité A crée l'événement {string} et s'y inscrit" is REUSED from
|
||||
// isolation.steps.ts (same wording, same behavior — A creates E and joins on the
|
||||
@@ -81,12 +76,13 @@ Then('l\'événement {string} finit par apparaître sur la page fraîche A en la
|
||||
const titles = await readHome();
|
||||
if (titles.includes(title)) { appearedAtMs = elapsed; break; }
|
||||
// At each reload mark, do a FULL reload → new NgDataProvider mount → new barrier.
|
||||
if (reloadIdx < reloadAtMs.length && elapsed >= reloadAtMs[reloadIdx]) {
|
||||
const reloadMark = reloadAtMs[reloadIdx];
|
||||
if (reloadMark !== undefined && elapsed >= reloadMark) {
|
||||
reloadIdx++;
|
||||
console.log(`[LongPoll] t=${elapsed}ms still ABSENT — forcing a full reload (#${reloadIdx}) to re-attempt the barrier…`);
|
||||
try {
|
||||
freshFrame = await pool.setupBrokerPage!(freshPage, pool.harnessUrl!);
|
||||
await freshFrame.waitForFunction(() => (window as any).__testData?.ready === true, { timeout: 60000 });
|
||||
await freshFrame.waitForFunction(() => (window as any).__testData?.ready === true, undefined, { timeout: 60000 });
|
||||
await freshFrame.evaluate(async () => { await (window as any).__testData.ensureCurrentUser(); });
|
||||
(this as any).recoFreshFrame = freshFrame;
|
||||
} catch (e) {
|
||||
@@ -105,18 +101,11 @@ Then('l\'événement {string} finit par apparaître sur la page fraîche A en la
|
||||
});
|
||||
|
||||
When('une page fraîche pour la MÊME identité A recharge sur le même wallet', { timeout: 120000 }, async function (this: FestipodWorld) {
|
||||
// SAME identity A as the main page: reuse the scenario's fresh virtual-wallet
|
||||
// identifier (set by the Before hook). NOT a new identifier — this is a reconnect,
|
||||
// not an identity switch.
|
||||
const aIdentifier = (this as any).freshIdentifier as string;
|
||||
// SAME user as the main page — by construction, not by declaration: the new page
|
||||
// is opened on the SAME browser context, and a browser context is one user. This
|
||||
// is a reconnect, and there is nothing to select.
|
||||
const ctx = this.page!.context();
|
||||
const freshPage = await ctx.newPage();
|
||||
await freshPage.addInitScript((u: string) => {
|
||||
try { window.localStorage.setItem('festipod.account.identifier', u); } catch { /* opaque */ }
|
||||
}, aIdentifier);
|
||||
await freshPage.addInitScript(() => {
|
||||
(globalThis as Record<string, unknown>).__FESTIPOD_ACCESS_GATE_DISABLED__ = true;
|
||||
});
|
||||
// Broadened to ALL console types (not just 'error') for the pause-reproduction
|
||||
// investigation: the SDK's diagnostic lines (logStage: BARRIER/OUTBOX/
|
||||
// readScopeIndex) are emitted via console.log, not console.error, and would
|
||||
@@ -124,7 +113,7 @@ When('une page fraîche pour la MÊME identité A recharge sur le même wallet',
|
||||
freshPage.on('console', (msg) => { console.log(`[FreshApage:${msg.type()}]`, msg.text()); });
|
||||
// New broker login → fresh verifier session on the SAME persistent wallet.
|
||||
const freshFrame = await pool.setupBrokerPage!(freshPage, pool.harnessUrl!);
|
||||
await freshFrame.waitForFunction(() => (window as any).__testData?.ready === true, { timeout: 60000 });
|
||||
await freshFrame.waitForFunction(() => (window as any).__testData?.ready === true, undefined, { timeout: 60000 });
|
||||
// Let A's listing effect + anchored union read run on the fresh session (this is
|
||||
// exactly the cold-start read path the fix heals).
|
||||
await freshFrame.evaluate(async () => {
|
||||
|
||||
@@ -20,6 +20,7 @@ Given('le portefeuille contient des données de test', async function (this: Fes
|
||||
// EventsScreen renders Card components (class app-card) when events load.
|
||||
const hasData = await this.appFrame!.waitForFunction(
|
||||
() => document.querySelectorAll('.app-card').length > 0,
|
||||
undefined,
|
||||
{ timeout: 30000 },
|
||||
).then(() => true).catch(() => false);
|
||||
|
||||
@@ -69,6 +70,7 @@ When('l\'utilisateur remplit le formulaire de création d\'événement:', async
|
||||
|
||||
const formReady = await this.appFrame!.waitForFunction(
|
||||
() => !!document.querySelector('input[placeholder="Donnez un nom à votre événement"]'),
|
||||
undefined,
|
||||
{ timeout: 10000 },
|
||||
).then(() => true).catch(() => false);
|
||||
|
||||
@@ -131,6 +133,7 @@ When('l\'utilisateur modifie le champ lieu avec {string}', async function (this:
|
||||
// adjacent to that label.
|
||||
await this.appFrame!.waitForFunction(
|
||||
() => document.getElementById('root')?.textContent?.includes('Lieu') ?? false,
|
||||
undefined,
|
||||
{ timeout: 10000 },
|
||||
);
|
||||
await this.appFrame!.evaluate((val: string) => {
|
||||
@@ -164,6 +167,7 @@ When('l\'utilisateur clique sur un événement de l\'accueil', async function (t
|
||||
});
|
||||
const homeHasCards = await this.appFrame!.waitForFunction(
|
||||
() => document.querySelectorAll('.app-card').length > 0,
|
||||
undefined,
|
||||
{ timeout: 5000 },
|
||||
).then(() => true).catch(() => false);
|
||||
if (!homeHasCards) {
|
||||
@@ -173,6 +177,7 @@ When('l\'utilisateur clique sur un événement de l\'accueil', async function (t
|
||||
});
|
||||
await this.appFrame!.waitForFunction(
|
||||
() => document.querySelectorAll('.app-card').length > 0,
|
||||
undefined,
|
||||
{ timeout: 10000 },
|
||||
);
|
||||
}
|
||||
@@ -211,6 +216,7 @@ When('l\'utilisateur clique sur un événement de la liste', async function (thi
|
||||
// EventsScreen also uses Card with .app-card class.
|
||||
await this.appFrame!.waitForFunction(
|
||||
() => document.querySelectorAll('.app-card').length > 0,
|
||||
undefined,
|
||||
{ timeout: 10000 },
|
||||
);
|
||||
const clicked = await this.appFrame!.evaluate(() => {
|
||||
|
||||
@@ -6,14 +6,13 @@ import { pool } from '../../../../shared/support/browserPool';
|
||||
// RECONNECTION-PERSISTENCE at the @e2e layer (REAL app, real broker).
|
||||
//
|
||||
// Mirrors reconnexion.steps.ts (@data) but drives the REAL app (pool.appUrl),
|
||||
// NOT the harness. The main page is booted by the @e2e Before hook: identity =
|
||||
// this.freshIdentifier (set into localStorage['festipod.account.identifier'] on every
|
||||
// origin by the hook), gate disabled → the real app boots directly on that
|
||||
// identity. We create an event via the REAL create form (same DOM path the app
|
||||
// user takes), verify it appears, then open a SECOND page in the SAME persistent
|
||||
// wallet context with the SAME identifier + gate disabled, and a FRESH broker
|
||||
// login → a fresh verifier session (empty memory) that must re-read everything
|
||||
// from the broker. That is the faithful analogue of "close and reopen".
|
||||
// NOT the harness. The main page is booted by the @e2e Before hook; who it comes
|
||||
// up as is `ensureIdentity()`'s answer, and nothing here selects it. We create an
|
||||
// event via the REAL create form (same DOM path the app user takes), verify it
|
||||
// appears, then open a SECOND page in the SAME browser context — one context is
|
||||
// one user, so it is the same person — with a FRESH broker login → a fresh
|
||||
// verifier session (empty memory) that must re-read everything from the broker.
|
||||
// That is the faithful analogue of "close and reopen".
|
||||
//
|
||||
// The step captures console logs from BOTH pages and reports (via cucumber
|
||||
// attachments) the timing of `WRITE`-ish lines vs `CONNECTION ESTABLISHED`, and
|
||||
@@ -94,6 +93,7 @@ Given('l\'utilisateur crée un événement {string} via le vrai formulaire', { t
|
||||
});
|
||||
const formReady = await frame.waitForFunction(
|
||||
() => !!document.querySelector('input[placeholder="Donnez un nom à votre événement"]'),
|
||||
undefined,
|
||||
{ timeout: 15000 },
|
||||
).then(() => true).catch(() => false);
|
||||
if (!formReady) {
|
||||
@@ -171,18 +171,11 @@ Given('l\'événement {string} apparaît sur l\'accueil de l\'utilisateur', { ti
|
||||
// --- Step 2: reconnect faithfully — a fresh page/session for the SAME identity ---
|
||||
|
||||
When('l\'utilisateur ferme et rouvre l\'app sous la même identité dans une session broker fraîche', { timeout: 180000 }, async function (this: FestipodWorld) {
|
||||
const identifier = (this as any).freshIdentifier as string;
|
||||
// SAME browser context → same wallet → same person. The reopened app asks
|
||||
// `ensureIdentity()` who it is, exactly as the first page did.
|
||||
const ctx = this.page!.context();
|
||||
|
||||
const freshPage = await ctx.newPage();
|
||||
// SAME identity in localStorage BEFORE any script (what the reopened app reads,
|
||||
// gate disabled) + gate disabled so the real app boots straight onto that id.
|
||||
await freshPage.addInitScript((u: string) => {
|
||||
try { window.localStorage.setItem('festipod.account.identifier', u); } catch { /* opaque */ }
|
||||
}, identifier);
|
||||
await freshPage.addInitScript(() => {
|
||||
(globalThis as Record<string, unknown>).__FESTIPOD_ACCESS_GATE_DISABLED__ = true;
|
||||
});
|
||||
|
||||
const freshLogs: StampedLog[] = [];
|
||||
(this as any).recoFreshLogs = freshLogs;
|
||||
@@ -197,6 +190,7 @@ When('l\'utilisateur ferme et rouvre l\'app sous la même identité dans une ses
|
||||
const root = document.getElementById('root');
|
||||
return !!root && root.innerHTML.length > 100;
|
||||
},
|
||||
undefined,
|
||||
{ timeout: 60000 },
|
||||
);
|
||||
// Let NG connect + the cold-start read path run.
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user