Code against the polyfill's published contract, and nothing else

The data layer is now reached through one pulled, version-pinned engagement
(`.project/concepts/data-layer/contract_polyfill-surface.md`, @1ecf511e9d).
That copy is the only reference: the provider's sources are never opened, and
what the contract does not answer is a gap raised with it, never worked around
here.

Surface
- `@ng-eventually/sdk` -> `@ng-eventually/polyfill`, one entry point.
- `configure` loses `getSession`, `normalizeId`, `currentUser`; the session
  belongs to the package and its own `init` captures it.
- Placement is named by scope alone -- a session is one user, so the app no
  longer passes an identity it had no way to obtain. This removes a constant
  that made every user collide on one owner's document.
- `init(...)` then `await ensureIdentity()`, in that order, as one sequence:
  React runs child effects first, so the two calls sat in the wrong order and
  the contract now makes that throw.
- `sessionId` relayed as `string | number`, `materialize` -> `read`.

A rejection means "unknown", never "absent"
Four places treated a caught error as an empty result. The worst wrote a
duplicate participation: an unknown count read as zero defeated the idempotence
guard of `joinEvent`. Also fixed: a per-document count, a silently dropped
notification shown optimistically anyway, and a failed listing that left the
owned-event set empty and disabled the materializer for the whole session.

Shared identity is not a Festipod notion
A browser context is one user. The per-scenario identity plant is deleted at
its source and its five sites; what stays is the deployment's wallet file,
which the contract requires an application to serve.

Documentation
The doctrine no longer describes how the data layer works underneath: five
leaves whose subject was internals are gone, a dozen more are re-founded on the
contract's own words, and two frozen arbitrations about a deleted screen were
removed rather than left to mislead a future session.

Test harness
It can sign in at last: cucumber runs under node, which does not load `.env`,
so the harness never received the wallet material and every scenario silently
fell back to an empty local mode. A failed sign-in is now loud on both sides.
The suite also releases what it opens and exits on its own -- runs were still
resident hours after reporting, holding a browser and two servers.

Known red: `@data` cannot be measured. The served wallet accumulates and
nothing resets it; moving the browser profile aside does not, since the data
lives in the wallet file, not the profile.
This commit is contained in:
Sylvain Duchesne
2026-08-16 12:33:14 +02:00
parent 47af46fd09
commit 53c0e095cf
108 changed files with 2741 additions and 3850 deletions
@@ -1,7 +0,0 @@
# Doc-debt — app-architecture
> Presence of a block = doc to update. Processed → delete the block; no blocks left → delete this file.
> One block = one "big change": `why` + `files` + `verify` (leaves to review).
## Raw markers (consolidate into blocks, then delete)
- TOUCHED src/shared/context/FestipodDataContext.tsx @2026-08-03 (session 0b064e8b-1717-421f-a20e-a4318ad217b1)
@@ -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 the profile document's NURI and is **empty until the protected read lands**; empty reads like "no data"
- [[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 standalone yourself** before believing the tests.
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,24 @@
---
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: currentUserId is now the profile document's NURI — the same value as currentUser.id — so the old two-id-spaces pitfall is gone; the live hazard is that it is EMPTY until the protected profile read lands, and nothing raises when a screen keys on it too early
last_checked: 2026-08-10
---
# Pitfall: two ids for the current user inside a screen
# Pitfall: the current user arrives late, and empty reads like a value
`useFestipodData()` exposes **two** identifiers for the current user. They live in **different spaces** and are **never equal in connected mode**:
## What is true now — one id, not two
| 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** `currentUser?.id`: the **NURI of the profile document** the app reads back in its own protected scope. The two are no longer distinct spaces, because the app no longer derives a principal from anything it was told — it stopped naming its own identity altogether (concept `app-security`, [[decision_2026-08-10_the-barrier-names-no-identity]]). A participation written today carries that same NURI in `fp:user`.
In seed/demo mode the two coincide (`user-1`) — **the pitfall only shows up when connected**, and never as an error: just a wrong result.
> The earlier pitfall — a stable principal `urn:festipod:user:<key>` on one side and a profile NURI on the other, never equal in connected mode — **no longer applies to values written today**. The provider still resolves the older principal form on read (`resolveParticipantUser`, concept `data-layer` → [[knowledge_context-internals]]); a screen never sees it.
## The rule
## The live hazard: `''` before the read lands
- 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`.
`currentUserId` is **empty** until the protected profile read resolves — and empty is a perfectly ordinary string. Nothing throws.
## What the mistake costs (observed)
- A **query** keyed on it (`getUserEvents`, `isParticipating`, `getFriends` — all defaulting to `currentUserId`) returns an **empty result** rather than an error, which renders as "you have nothing" instead of "not ready yet".
- A **mutation** that needs it refuses rather than writing a malformed entity: `joinEvent` logs `empty user principal — refusing to write a participation with no fp:user` and returns. A screen that assumed the write happened shows a success it did not get.
- Comparing `participant.id !== currentUserId` to filter yourself out **removes nothing**: you show up in your own list, and since the row is no longer recognized it renders as « participant inconnu ».
- Symmetrically, a screen displaying **another user's** events from their **profile id** (`getUserEvents(viewedUser.id)`) yields an empty list when connected — same cause.
**The rule**: treat an empty `currentUserId` as *not ready*, never as *no data*. Gate on it before rendering an emptiness verdict or firing a mutation that stores it.
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]].
The participation→profile join itself is **not** the screen's business: it is done in the provider (`resolveParticipantUser`). Full mechanics and the write/read invariant: concept `data-layer`, [[knowledge_context-internals]].
@@ -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
@@ -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` |
| `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, reads everything through useFestipodData/useNavigate/useParams, flex column layout (Header / scrollable content / BottomNav), feedback via showToast, hard-coded French labels; zero-prop rule has no exception left
last_checked: 2026-08-10
---
# Canonical screen pattern
@@ -34,10 +35,8 @@ 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 profile document the app reads back in its own protected scope, so it is **empty until that read lands** — see [[caveat_identity-ids-in-screens]] before keying anything on it.
- **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
+9 -6
View File
@@ -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,20 @@ 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]].
- **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
- [[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,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 — a missing one used to yield AccessGateScreen's error block, now it makes ensureIdentity() throw and the app render nothing at all, silently
last_checked: 2026-08-10
---
# 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]]). A bundle produced by `build.ts` is **not** concerned: there the value is inlined by `define`.
- **`@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` now fails **silently** (blank page, console-only) rather than with a screen saying so — worth knowing when diagnosing "the app shows nothing."
**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]].
@@ -1,24 +1,33 @@
---
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, seen from the app
The app does not derive an identity from anything it was told; **what it is, is the profile document it reads back in its own protected scope**. That value is therefore empty until the protected read lands — 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,25 @@
---
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.
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.
-9
View File
@@ -1,9 +0,0 @@
# Doc-debt — bdd-testing
> Presence of a block = doc to update. Processed → delete the block; no blocks left → delete this file.
> One block = one "big change": `why` + `files` + `verify` (leaves to review).
## Raw markers (consolidate into blocks, then delete)
- TOUCHED src/modules/event/steps/data/reconnexion.steps.ts @2026-08-03 (session 0b064e8b-1717-421f-a20e-a4318ad217b1)
- TOUCHED src/shared/test-harness/harness-ng.tsx @2026-08-03 (session 0b064e8b-1717-421f-a20e-a4318ad217b1)
- TOUCHED src/modules/workshop/steps/data/protected-connections.steps.ts @2026-08-03 (session 0b064e8b-1717-421f-a20e-a4318ad217b1)
+6 -3
View File
@@ -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,15 @@ 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_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`)
@@ -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: 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.
@@ -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 exactly as the app does, and per-scenario isolation is currently ABSENT
last_checked: 2026-08-10
---
# 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`; the current user is **the profile document read back in the protected scope**, so it lags behind the public events. Steps wait for `ensureCurrentUser()` before `joinEvent` (otherwise the mutation refuses, or writes a participation with no user → dropped on read) and then wait (`waitForFunction`) for the participation to be read back.
- **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 connected seed stays **lightweight** (few docs): creating a document is a serial round trip, so the seed's cost is linear in the number of documents it writes.
@@ -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
@@ -31,17 +31,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.
-11
View File
@@ -1,11 +0,0 @@
# Doc-debt — data-layer
> Presence of a block = doc to update. Processed → delete the block; no blocks left → delete this file.
> One block = one "big change": `why` + `files` + `verify` (leaves to review).
## Raw markers (consolidate into blocks, then delete)
- TOUCHED src/shared/data/entityWrites.ts @2026-08-03 (session 0b064e8b-1717-421f-a20e-a4318ad217b1)
- TOUCHED src/shared/utils/ngBootstrap.ts @2026-08-03 (session 0b064e8b-1717-421f-a20e-a4318ad217b1)
- TOUCHED src/shared/utils/ngSession.ts @2026-08-03 (session 0b064e8b-1717-421f-a20e-a4318ad217b1)
- TOUCHED src/shared/context/FestipodDataContext.tsx @2026-08-03 (session 0b064e8b-1717-421f-a20e-a4318ad217b1)
- TOUCHED src/shared/shapes/shex/festipodShapes.shex @2026-08-03 (session 0b064e8b-1717-421f-a20e-a4318ad217b1)
+10 -16
View File
@@ -1,40 +1,34 @@
---
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]].
## 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`
- [[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.
- [[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_context-internals]] — pitfalls of `FestipodDataContext` (who the current user is and when it arrives, the legacy principal space, dev auto-seed, `participantCount`, local no-op)
## Write rules
- [[rule_document-per-entity]] — every entity gets **its own document** (per scope), never one at store level; this is what makes the SDK's per-document isolation possible
- [[rule_app-uses-sdk-surface-only]] — the app behaves as if NextGraph were finished; every workaround lives in the polyfill
## What leaves this repo (two destinations, don't confuse them)
- [[rule_capture-nextgraph-findings]] — established **knowledge** about how NextGraph actually works → the **polyfill**'s reference docs, at the moment of discovery
- [[rule_nextgraph-inbox]] — a NextGraph **malfunction**, or a **gap** we need and emulate in the meantime → a note in `orm-tests/INBOX/`, which tracks upstream progress and says what to remove from the polyfill
- [[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
## Pitfalls (read before touching deletions / event fields)
- [[caveat_participation-deletion]] — withdrawal must be **authoritative** and must not come back
- [[caveat_event-fields-not-persisted]] — `startTime`/`themes`… not covered by the Event shape → lost when connected
- [[caveat_write-durability-across-disconnect]] — a write made just before an idle period / socket drop can be **lost** (no broker durability); the account survives. Open incident → post-mortem in the polyfill
> Confidentiality (scope isolation, trusting the SDK): concept `app-security`. Product scopes per entity + discovery: concept `functional-domain`.
@@ -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. P1P3 can ship before P4P6.
- **Materialization idempotence**: the per-deposit `uid` (`RegistrationPayload.uid`, `registration.ts:56`) is the pivot; the (reference) recorded by the owner must be consulted before any increment/decrement so as never to double-count (sync replay) nor "resurrect" a count.
- **Native inbox migration**: today the inbox is emulated over the shared wallet (`inbox.ts` post/read RDF). On migration to the native broker inbox (`inbox_post`/`inbox_pop_for_user`, sealed), the Option B flow **remains valid** (non-member deposits allowed, reads reserved to the *readers* = the owner), but the `subscribeDoc` wrapper on the inbox will have to target the native deposit-notification mechanism. To be checked at migration time.
@@ -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]]).
@@ -6,7 +6,9 @@ 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`).
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 covers exactly (verified 2026-08-10 in the `.shex`): `title, description, date, location, distance, participantCount, coverImage, hostName, hostInitials`, plus an optional `inbox`.
> That `inbox` field is a **vestige, and it must stay unused**: it was there to publish an event's inbox address so others could deposit into it. The app no longer handles an inbox address anywhere — 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]]).
## Consequence
@@ -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,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: 1ecf511e9d8de8e0feb007f3a88f2c0d56ce455a
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.
@@ -1,45 +1,47 @@
---
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 — currentUserId is the profile document read back in the protected scope (empty until it lands), the legacy principal space resolveParticipantUser still resolves on read, OPT-IN auto-seed, owner-derived participantCount, local-mode no-op mutations
last_checked: 2026-08-10
---
# 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)
## Who am I — `currentUserId` is a document you read back, not a value you were given
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 app names no identity of its own** (concept `app-security`, [[decision_2026-08-10_the-barrier-names-no-identity]]): `ensureIdentity()` takes nothing, and nothing switches identity afterwards. So the provider cannot *derive* a principal from an input. What the current user **is**, is the **profile document it reads back in its own protected scope**: `currentUserId` = that profile's `@id`, a doc NURI — the very same value as `currentUser?.id`.
## TWO id spaces meet — joining a participation to its profile
**The pitfall that follows**: it is **empty until the protected read lands**, and empty is an ordinary string that raises nothing. Mutations needing it **refuse** (`joinEvent` logs `empty user principal — refusing to write a participation with no fp:user` rather than writing an entity that would be dropped on read); queries keyed on it return **empty results** that render as "you have nothing". Treat `''` as *not ready*, never as *no data* — see `app-architecture`, [[caveat_identity-ids-in-screens]].
**Invariant.** A `Participation` stores its user as a **principal** (`urn:festipod:user:<normalized-identifier>`, = `currentUserId`), whereas a `UserProfile` has as its `id` the **NURI of its document** (`did:ng:…`). In connected mode, **these two values are never equal**. So a raw `participation.userId === profile.id` join **never** matches — a symptom that shipped and was then fixed (2026-07-27): every participant displayed as « participant inconnu ». Every participation→profile join goes through **`resolveParticipantUser`** (`FestipodDataContext`), never through a direct comparison.
> The `currentUser` object is picked with a **fallback** (`@mariedupont`, then `users[0]`) — a leftover of the demo seed, and a silent one: on a wallet holding several profiles it can settle on the wrong person. Worth a look whenever "the app thinks I am someone else".
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.
## The legacy principal space — resolved on READ only
**`USER_PRINCIPAL_PREFIX` is the single source of the prefix**, shared by the **write** side (deriving `currentUserId`) and the **read** side (`resolveParticipantUser`). If you change the shape of the principal, change it **there**: otherwise write and read drift apart silently and the join falls back to « inconnu » without raising an error.
A `Participation` written **today** carries `currentUserId` in `fp:user`, i.e. a profile doc NURI, so a direct `participation.userId === profile.id` join matches. Participations written under the **earlier** scheme carry a principal of the form `urn:festipod:user:<normalized-handle>`, which matches nothing directly.
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.
**`resolveParticipantUser`** (`FestipodDataContext`) is the single join point, and it tries, in order: (1) a **direct match** `u.id === userId` — today's writes, and the demo seed's bare `user-1` space; (2) failing that, strip `USER_PRINCIPAL_PREFIX` and match the remainder against `normalizeIdentifier(profile.username)` — the legacy space. Never join by direct comparison at a call site: the symptom of getting it wrong is every participant rendering as « participant inconnu », which shipped once already.
> **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.
`USER_PRINCIPAL_PREFIX` is now **read-side only** — nothing mints it any more. It is kept so old data still resolves; it is not a shape to write against.
A further id space takes **no** part in this join: the inbox deposit `uid` (`mint…`) — it identifies a **deposit** for the counter, never a user.
> **Horizon.** This paragraph describes **what is implemented**. The target model drops the plaintext `userId` and routes identity resolution through **reading the profile** — see [[brief_2026-07-20_attendance-set-model]], whose implementation is gated. The id-space fix is explicitly noted there as **still valid**: do not undo it in anticipation of the target.
### Which space each query expects (the `buildQueries` contract)
| Query | What it expects / returns |
|---|---|
| `getUserEvents(userId)`, `isParticipating(eventId, userId?)`, `getFriends(userId?)` | **expect the principal** (they filter on `participation.userId` / `friendship.userId`) — their default is `currentUserId`, which is correct |
| `getUserEvents(userId)`, `isParticipating(eventId, userId?)`, `getFriends(userId?)` | filter on `participation.userId` / `friendship.userId`; their default is `currentUserId`, which is correct |
| `getEventParticipants(eventId)` | **returns profiles** (`FpUserData``id` = NURI), the join being done internally |
**Screen-side impact**: filtering yourself out of a participant list compares against **`currentUser?.id`** (the profile NURI, the same space as the rendered items), **not** against `currentUserId` (the principal) — otherwise you do not remove yourself and you see yourself appear as one more participant. Conversely, passing a **profile id** to `getUserEvents`/`isParticipating` returns an **empty** list in connected mode. See `app-architecture`, [[caveat_identity-ids-in-screens]].
**Screen-side impact**: `currentUserId` and `currentUser?.id` are now the same value, so filtering yourself out of a participant list works either way. What still bites is passing an id **before it resolves** — see `app-architecture`, [[caveat_identity-ids-in-screens]].
## Reads = `watchShape` (the SDK surface), no more bespoke machinery
**Since 2026-07-10**: `useNgData` reads through `useShapeQuery(shape, scope)` (a `useSyncExternalStore` binding over the polyfill's `watchShape`) — THREE useQuery-shaped reads (events/public, users/protected, participations/protected) + Fp adapters (`shapeAdapters.ts`). Removed: `readEntities`, `subscribeDocs`+`bumpRead`+`readTick`, the manual listing (`publicDocs`/`protectedDocs`/`registerDoc` for reads), and `relist`. `ready` = the combination of the `isSuccess` flags. See [[rule_app-uses-sdk-surface-only]].
**Since 2026-07-10**: `useNgData` reads through `useShapeQuery(shape, scope)` (a `useSyncExternalStore` binding over `watchShape`) — THREE useQuery-shaped reads (events/public, users/protected, participations/protected) + Fp adapters (`shapeAdapters.ts`). Removed: `readEntities`, `subscribeDocs`+`bumpRead`+`readTick`, the manual listing (`publicDocs`/`protectedDocs`/`registerDoc` for reads), and `relist`. `ready` = the combination of the `isSuccess` flags. See [[rule_app-uses-sdk-surface-only]].
**Immediate visibility of mutations = an OPTIMISTIC overlay** (no `registerDoc`): `createEvent`/`joinEvent`/`leaveEvent` feed `pendingAddEvents`/`pendingAddParticipations`/`pendingRemoveIds`; the exposed state = merge(reactive, adds) minus removes, deduped by id (id = the doc's NURI). Reconciliation happens automatically on push (an add that shows up in the reactive state, or a remove that disappears from it, is dropped) — never a poll ([[rule_no-broker-polling]]). Cleared on identity change.
**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]]).
## Dev auto-seed
@@ -47,19 +49,19 @@ A **third** id space exists and takes **no** part in this join: the inbox deposi
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.
- The seed writes under the **connected session**, so the session that seeds **holds** what it seeded and its protected fixtures round-trip. Seeded users are fixtures, not accounts — nobody has signed in as them, which matters because `inbox.share` refuses a recipient nobody has ever been. Only **events** get an inbox opened at seed time (`openDocumentInbox`), because events are what people deposit into.
- **No retry**: if the seed fails, you get an empty screen + a `console.error`.
## `participantCount` — derived and owned by the owner (Option B)
## `participantCount` — derived and owned by the owner
> ✅ **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]]).
> ✅ **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 through `inbox.readSynced` instead of `inbox.read` — the two differ by contract, and only the former is the synced view ([[contract_polyfill-surface]]); (2) the materializer fires **directly on connection** (`[ready, ownedKey]`), no longer only on a push; (3) `materializedCountRef` no longer locks in a premature 0 (its sole role = loop guard: only write when the derived value changes); (4) **the single source of the NUMBER = `event.participantCount`** (the `participantCount: 1` literal in `CreateEventScreen` is removed → it starts at 0; the display no longer computes a local number). Kept GREEN (on a fresh profile) by `event/e2e-multibrowser.feature` « Le compteur converge chez le propriétaire à sa prochaine connexion » (un-`@wip`'d). No polling ([[rule_no-broker-polling]]).
**Since Option B (2026-07-07)**: `participantCount` is no longer mutated in place by the participant. The flow is inbox-deposit → owner-materialization:
- `joinEvent`/`leaveEvent` **no longer** write `participantCount` on the event's doc (that would be an isolation violation — the participant writing someone else's doc; NextGraph writes are membership-bound, with no append). The participant only writes their **own** participation doc (protected), then **deposits** a marker into the event's inbox (`depositRegistration` on join, `depositLeave` on leave, `src/shared/data/registration.ts`).
- The event **owner's** session does the materializing: it is subscribed (`inbox.watch`, `doc_subscribe`, no polling) to the inbox of the events it owns (`ownedEventIds` = `listMyEntityDocs(owner,'public')` + freshly created events), and on every deposit it **recomputes** `participantCount` on **its own** event doc (`updateEntityField` on its own doc). It is the counter's only writer.
- **The counter is DERIVED, not incremented**: `materializeAttendance` (registration.ts) reads the inbox and computes the **set** of distinct active sign-ups (`new-participant` deposits deduped by `uid`, MINUS those cancelled by a `leave-participant` — by exact `regUid` or by the `(eventId, userId)` fallback). `participantCount = |active set|`**no host baseline**: the creator does not attend automatically (there is no notion of host, see concept `functional-domain`), so the counter starts at **0** on creation and only moves on real sign-ups. `createEvent` **no longer writes** a participation at creation time (it used to write a host participation and set the counter to 1); the creator sees « J'y serai » and can join/leave their own event like anyone else. Because it is a **pure function of the inbox**, a broker sync replay converges — never double-counting nor a phantom decrement (idempotence). The write is guarded (it only writes when the value changes), a loop guard. Covered by the `@data` scenario « Le créateur ne participe pas automatiquement à son événement » (us-13): counter 0 + `isParticipating(E)===false` at creation, then join→true / leave→false.
- **Owner offline = eventual**: only the owner's session materializes; while they are disconnected, the counter does not move for anyone else (the participations/deposits stay persisted — nothing is lost; a future service will materialize in their stead).
- The counter nevertheless remains an **aggregate**, not the list of named participants: `getEventParticipants` (named identity) is still governed by the protected read cap ([[caveat_participation-deletion]] for the authoritative deletion, unchanged). See the brief `brief_2026-07-06_reactive-reads-and-attendance` §B.
**Since 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 **only a document's owner writes to it**, so a participant cannot touch someone else's. 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 watches (`inbox.watch`, no polling) the inbox of the events it owns (`ownedEventIds` = `listMyEntityDocs('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 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 and deposits stay persisted — nothing is lost).
- The counter nevertheless remains an **aggregate**, not the list of named participants: `getEventParticipants` (named identity) is still governed by what the protected scope hands back ([[caveat_participation-deletion]] for the authoritative deletion, unchanged).
### Id-form invariant: match on the CANONICAL form of the event id
@@ -69,19 +71,13 @@ An event's `@id` **is** its document NURI (`did:ng:o:<repo>[:v:<overlay>]`). The
**Rule**: match the event id on its **canonical form** — the base repo id, with any `:v:<overlay>` suffix stripped (`canonicalEventId`, `src/shared/data/registration.ts`). This canonical form is used for **matching** in `materializeAttendance` / `readRegistrationNotifications`, and for **deduplicating** `ownedEventIds` (`ownedKey`, FestipodDataContext) so that one and the same event reached through two paths is not materialized twice. **Careful**: only the **matching** uses the stripped form; the counter is always **written** to the real owned NURI (a live, openable doc) — a stripped id must never serve as a write target or an anchor. This is an **app-side** invariant (not a NextGraph detail): however the lib makes the overlay vary, the app matches on the common base.
## Identity change = a fresh session (isolation)
## There is no identity switch any more
> **History of the symptom** (the paragraph that follows describes the setup of the time — the bespoke read set `publicDocs`/`protectedDocs`/`readTick` **no longer exists** since the move to `watchShape`). It is kept because it explains *why* the reset rule exists; the **current mechanism** is described further down.
The app settles its identity **once**, before anything renders (`ensureIdentity()` in `AuthGate`), and offers no way to change it — the surface stopped publishing one (concept `app-security`, [[decision_2026-08-10_the-barrier-names-no-identity]]). So the provider carries **no identity-change reset**: no `useEffect([identifier])`, no cap reset, no registry-cache reset. Those symbols are gone; do not reintroduce a reset for a transition that cannot happen.
The on-demand read set (`publicDocs`/`protectedDocs`) **accumulated** the current identity's scope docs (so as not to lose a just-created doc before the re-listing). But the shared-wallet stopgap keeps **a single React tree** across a fake logout + re-login under a **different identifier** (no page reload — `AccountContext.login` merely rewrites the identifier in localStorage, and `AuthGate` remounts nothing). Without a reset, **the previous identity's PROTECTED docs (its participations) survive in the new identity's read set and leak** through the union read: the cap gate cannot filter them out when the (in-memory) cap registry does not govern that doc in *this* session (a doc persisted from an earlier run, or a fresh load where the caps are empty). Symptom observed: a user B saw A's participation (and A's event appeared on B's **home screen**, since home = `getUserEvents(currentUserId)`, see concept `app-architecture`).
**Rule**: treat **any identifier change** as a **fresh session**. A `useEffect([identifier])`, **ref-guarded** (it does not fire on first mount, only on a genuine value change), resets **all session state carried by the app**. Isolation remains per-document/emulated (concept `app-security`, [[knowledge_trust-model]]); this reset only removes the carry-over of state between identities.
**Current mechanism** (since reads go through `watchShape`): the **read** side has nothing left to reset — `watchShape` re-resolves its scope against the new `getCurrentUser()` on the next push. What the effect clears is the **app-side** state: `ownedEventIds` (the owner materializer's set), the `joinUids` map (the current session's deposit uids), the **optimistic overlay** (`pendingAddEvents`/`pendingAddParticipations`/`pendingRemoveIds` — otherwise the old identity's mutations bleed into the new one's reads), then `resetCaps()` + `resetRegistryCache()`.
> **Impact — the invariant not to break**: **any new session state** added to the provider (a cache, a `useRef`, the overlay, a doc set) must be added to that effect. Forgotten state **leaks from one identity to the next** with no error — exactly the class of bug the regression guard below covers.
**Mechanism confirmed empirically (2026-07-07)**: the leak reproduces ONLY when TWO conditions coincide — (a) the read set still carries A's PROTECTED doc across the switch (no reset), AND (b) the in-memory cap registry does not govern that doc (`resetCaps()` already fired / caps empty for a doc persisted from a session earlier than the reload). Then A's participation makes it through B's union read (the per-document filter has no cap to check). With the reset fired, A's doc left B's read set BEFORE the cap-less read could expose it → no more leak whatever the state of the caps (at the time via `setProtectedDocs([])`; today it is `watchShape` that re-resolves the scope, and the reset now carries only the app-side state listed above). **Regression guarded** by the `@data` scenario « Une identité fraîche ne voit pas la participation d'une autre » (event/isolation-deux-identites.feature): A creates E and signs up to it, B (a fresh page on the same wallet, with a distinct identifier) has NEITHER E on their home screen (`getUserEvents(B)`), NOR `isParticipating(E,B)`, AND reads NO participation carrying A's principal. The historical symptom « B voit "Je participe" » mostly occurred when B **reused an identifier already used by A** (the same normalized principal) on a **bloated** wallet (docs persisted from an earlier run, empty caps).
> **Why there is nothing left to reset.** An identity-change reset only made sense while a single React tree could outlive a change of identity. It cannot: one page hosts exactly one identity for its whole life, so session state (the read set, the optimistic overlay, the owner-materializer's doc set) has no second identity to leak into.
>
> The **cross-identity isolation** behaviour is still a real Festipod requirement, but proving it needs **two genuinely separate browser contexts**, each signing in for itself. `event/isolation-deux-identites.feature` is `@wip` for exactly that reason (concept `bdd-testing`, [[rule_tests-validate-festipod-not-the-sdk]]).
## `useShapeQuery` instrumentation — global spinner + timing
@@ -89,7 +85,7 @@ The on-demand read set (`publicDocs`/`protectedDocs`) **accumulated** the curren
## Logging convention — identity-first prefix, and counter before→after
Every DATA log from the provider goes through **`logPrefix`**: `[<currentUserId>][app][data]` when the principal is resolved, `[app][data]` otherwise (a transient connection state). Reason: with the shared wallet, **two identities share the same console** (two tabs / a multi-browser run) — an unprefixed line does not say *whose* it is and becomes useless for diagnosing a leak or a stuck counter. **Adding a DATA log = reusing `logPrefix`**, not a bare `console.log`.
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: a run often drives **several sessions at once** (two tabs, a multi-browser scenario) and their lines end up read side by side — 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.
@@ -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`)
@@ -1,23 +1,17 @@
---
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
@@ -31,6 +25,6 @@ The reactive ORM (`useShape`) is built on **SHEX shapes**: `src/shared/shapes/sh
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.
> **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,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`.
> **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.)
**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`).
The same goes for **mutating an existing field** (e.g. `participantCount`): mutating a value in memory does not hold — the reactive read re-reads the **persisted** value from the broker (reverting to the old value) → persist through SPARQL (`updateEntityField`: DELETE then INSERT of the triple) so that the change sticks and the re-read agrees. Each field is written with the **right RDF term** according to the SHEX shape (xsd:integer / float / boolean, or an IRI for the `Participation.event`/`.user` references) — a missing or mistyped mandatory field makes the read **discard the entity** (it never round-trips). The entity's **subject** = its document's **NURI** (one entity = one document), which yields an `@id` of the form `did:ng:…`.
Identity corollary: a `Participation` carries a **mandatory** `fp:user` — never write it with an empty principal (the entity would be discarded on read). The current user's principal is **stable and derived from the username** (`urn:festipod:user:<normalized-username>`), available **immediately** after login (no dependency on reading the protected profile, which may lag) and **invariant** (it does not flip from a fallback to the profile IRI mid-session, which would desynchronize a participation written under one value from a check made under the other). It is the same principal that the SDK identity (`setCurrentUser`) and the owner cap derive from the username; bilateral connections (`declareConnections`) are declared with those same username keys (not profile IRIs) so that "protected = my connections" discriminates.
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 the app read back in its own protected scope**; the app derives it from nothing, because it names no identity ([[decision_2026-08-10_the-barrier-names-no-identity]] in `app-security`). It therefore **arrives late**: a mutation fired before the protected read lands must refuse rather than write, which is what `joinEvent` does. See [[knowledge_context-internals]].
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]].
@@ -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 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 = 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,13 +27,13 @@ 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…").
A user discovers the events they did not create simply by **reading the `public` scope**: the app names the shape and the scope, and gets back everyone's public events, not just its own. That is the **primary** discovery axis; a **secondary**, relational one is layered on top (the connections' *protected* participations: "my friends are attending…").
> **Sign-up notification (product intent).** Signing up to a meeting point notifies its host: identified if the participant is one of the host's connections, **anonymous otherwise**. This "identified if known, anonymous otherwise" is a property of the data model — the app relies on it, the mechanism is provided by the SDK.
> **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.
## Open questions (business)
@@ -17,7 +17,9 @@ summary: What is implemented today (event + meeting point lifecycle, profiles, c
> Signing up to / withdrawing from a meeting point is **genuinely wired** on the data side: `joinEvent` persists a Participation, notifies the meeting point's host and creates a Notification; `leaveEvent` deletes the Participation authoritatively (see concept `data-layer`, [[caveat_participation-deletion]] on the data-layer side). Public discovery — a user seeing another user's public event — works too.
> **Product reservation — persistence is not guaranteed end to end.** An event that was created can **disappear** after a period of inactivity followed by a reconnection under the same identity (same wallet). This is an **open defect**, not a property of the product model: impact and pointer on the `data-layer` side → [[caveat_write-durability-across-disconnect]]. Consequence for the domain: "my events / my sign-ups" behave as *implemented* but **not yet as durable** — do not build any product promise (reminders, history, commitment) on top of them while this caveat is open. The `src/modules/event/features/reconnexion-*.feature` scenarios of the `event` module are the non-regression guard for that promise (execution status: concept `bdd-testing`).
> **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)
-7
View File
@@ -1,7 +0,0 @@
# Doc-debt — tech-stack
> Presence of a block = doc to update. Processed → delete the block; no blocks left → delete this file.
> One block = one "big change": `why` + `files` + `verify` (leaves to review).
## Raw markers (consolidate into blocks, then delete)
- TOUCHED tsconfig.json @2026-08-03 (session 0b064e8b-1717-421f-a20e-a4318ad217b1)
@@ -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)
@@ -1,13 +1,16 @@
---
type: knowledge
summary: Dev runs on bun --hot, prod builds through build.ts (Bun bundler + Tailwind plugin) into dist/, path alias @/* → ./src/*
last_checked: 2026-08-10
---
# 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`).
- **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,7 +21,7 @@ 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):
@@ -9,7 +9,7 @@ last_checked: 2026-07-14
## 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.
@@ -29,4 +29,4 @@ A `Dockerfile` exists (multi-stage Bun Alpine). **Installation goes through pnpm
`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 link to the SDK**: in production the `@ng-eventually/polyfill` dependency comes from Gitea (git+https, pinned by `pnpm-lock.yaml`). When the provider's package has to be exercised from a local checkout, `pnpm run link:polyfill` (script `scripts/link-polyfill.ts`) replaces `node_modules/@ng-eventually/polyfill` with a **real copy** of that checkout (location overridable with `NG_EVENTUALLY_LOCAL`) — **without** its own `node_modules/@ng-org` — and resyncs on every edit. Copying rather than symlinking is what keeps **a single `@ng-org/*` instance** installed: 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, link:polyfill for the reactive local link)
---
# 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`) |
@@ -33,7 +33,7 @@ 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]]. |
| `link:polyfill` | `bun scripts/link-polyfill.ts`**reactive** local link to `@ng-eventually/polyfill` (copy-overlay + watcher). Details in [[knowledge_deployment]]. |
| `storybook` / `build-storybook` | Storybook dev (6006) / static build |
## Pitfalls
@@ -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 link goes through `pnpm run link:polyfill` (see [[knowledge_deployment]]).
**Practical consequence.** npm scripts that relied on `node_modules/.bin/*` may break (pnpm puts shell shims there, not JS entries) — call the package's actual JS entry (e.g. `node_modules/@cucumber/cucumber/bin/cucumber.js`) rather than the `.bin/` shim.