fix(client): résolution de compte barrière-autoritative — fin du fork à la reconnexion

Bug: à la reconnexion, resolveAccount lisait le shim depuis le store-root
(did🆖${privateStoreId}), NON abonnable → pas de barrière first-State → un "0 rows"
à froid est ambigu → le retry (resolveAccountReliably/provisionRetry) échoue → nouveau
compte provisionné → FORK → données du compte invisibles.

Cause NextGraph (vérifiée nextgraph-rs): "trouvable-sans-lookup" (store-root) et
"abonnable" (did:ng:o:<RepoID aléatoire>) sont DISJOINTS — pas de doc à la fois
devinable et attendable → une résolution shim purement barrière est impossible.

Fix (indirection pointeur → doc-shim abonnable):
- Les AccountRecord migrent dans un doc-shim doc_create'd (did:ng:o:..., a une barrière).
- Un pointeur écrit-une-fois dans le store-root (<shim:root> <shim:shimDoc> <docShim>)
  le nomme. resolveShimDoc lit le pointeur → ensureRepoOpen(docShim) [barrière] → lecture
  de compte AUTORITATIVE (cold 0 = absent pour de vrai). Retry de compte SUPPRIMÉ.
- Micro-garde résiduel (pointerGuard, ex-provisionRetry) sur le SEUL triple pointeur
  écrit-une-fois; ne peut jamais forker un compte; fork de pointeur réconcilié au
  doc-shim canonique (lexicographiquement-min), sans perte.
- Migration: migrateLegacyRecords copie (pas déplace) les comptes de l'ancien store-root
  vers le doc-shim avant toute conclusion "absent"; idempotent; wallet neuf → no-op.

Tests: unit 128/128, e2e réel 42/42 (CONTRACT 2 = non-fork du compte à la reconnexion),
red-before/green-after prouvé. Docs: nextgraph-current-state (antagonisme + indirection),
simulation, migration-guide.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Sylvain Duchesne
2026-07-13 17:46:16 +02:00
parent 5cdc6ce77f
commit 5e91771da6
17 changed files with 744 additions and 351 deletions
+171 -107
View File
@@ -1,20 +1,27 @@
/**
* anti-fork.test.ts — behavioral tests for the reconnection fix in the
* polyfill-era shim (src/store-registry.ts). Two guards, one file:
* polyfill-era shim (src/store-registry.ts), redesigned around the
* pointer → doc-shim indirection. Three groups, one file:
*
* (1) DETERMINISTIC RESOLUTION — a shim whose account subject carries DUPLICATE
* scope-doc values (fork residue: several `shim:docPublic`) must resolve to
* the SAME canonical doc every time (lexicographically-smallest NURI), so the
* session that WROTE an entity and a fresh page that RESOLVES the doc never
* disagree. This is the root-cause fix for the reconnection bug.
* (1) DETERMINISTIC RESOLUTION — a doc-shim whose account subject carries
* DUPLICATE scope-doc values (fork residue: several `shim:docPublic`) must
* resolve to the SAME canonical doc every time (lexicographically-smallest
* NURI), so the session that WROTE an entity and a fresh page that RESOLVES
* the doc never disagree. Robustness against PAST fork residue.
*
* (2) ANTI-FORK BOUNDED RETRY — a fresh page over a persistent wallet may read
* the shim as 0 rows while the private store is still syncing. A BOUNDED retry
* (capped backoff, from the injected `provisionRetry` budget) bridges that
* window before concluding "account genuinely new" and provisioning —
* preventing new fork residue. A genuinely-new account (always 0) is still
* provisioned exactly once. The budget defaults to `attempts: 1` (no retry)
* when unset, so the synchronous unit fakes stay single-read and unchanged.
* (2) BARRIER-AUTHORITATIVE RECONNECT (the core fix) — a fresh page over a
* persistent wallet resolves the SAME account through the doc-shim's
* first-`State` BARRIER, with NO account-level retry. The account records
* live in a subscribable doc-shim (`did:ng:o:...`) reached via a write-once
* POINTER triple in the store-root; opening the doc-shim makes a cold read
* authoritative, so a genuinely-present account is found on the first read
* and never re-provisioned (no fork). This replaced the deleted
* `resolveAccountReliably` / `provisionRetry` account retry.
*
* (3) MIGRATION — a wallet whose accounts were written at the OLD location (the
* store-root graph, pre-indirection) must have those records MIGRATED into
* the doc-shim at resolution, so a legacy account resolves (is READ, not
* re-provisioned) after reconnect. No existing account is lost.
*/
import { describe, it, expect, mock, beforeEach, afterAll } from "bun:test";
@@ -41,13 +48,18 @@ afterAll(() => {
});
const SESSION: RegistrySession = { sessionId: "sid-af", privateStoreId: "PRIV-AF" };
const ROOT = "did:ng:PRIV-AF";
// ---------------------------------------------------------------------------
// Fake ng — in-memory quad store. Two variants:
// - makeFakeNg(): NO doc_subscribe → non-reactive path (no sync lag, no retry).
// - makeLaggyFakeNg({lag}): HAS doc_subscribe (so the anti-fork retry path
// fires) and can simulate a sync lag: the account SELECT returns 0 rows for the
// first `lag` reads, then the seeded data — modelling a shim not yet synced.
// Fake ng — in-memory quad store modelling the pointer → doc-shim indirection.
//
// - The POINTER (`<shim:root> <shim:shimDoc> <docShim>`) lives in the store-root
// graph (keyed by GRAPH <ROOT>).
// - AccountRecords live in the doc-shim (anchored default graph, keyed by the
// anchor arg = the doc-shim NURI). A LEGACY record may ALSO be seeded directly
// in the store-root graph (the pre-indirection location) to exercise migration.
// - doc_subscribe pushes an initial `State` so ensureRepoOpen resolves at once
// (the barrier).
// ---------------------------------------------------------------------------
interface Quad { g: string; s: string; p: string; o: string }
@@ -95,10 +107,9 @@ function makeSparqlUpdate(quads: Quad[]) {
});
}
/** Build the account-SELECT bindings from the quads (grouped per subject). Each
* (subject × docPublic × docProtected × docPrivate) combination is a binding, so
* a subject with DUPLICATE scope docs yields a cross-product of bindings — exactly
* what a corrupted shim returns. */
/** Build the account-SELECT bindings from the quads in ONE graph (the doc-shim, or
* the store-root for the migration read), grouped per subject. A subject with
* DUPLICATE scope docs yields a cross-product of bindings — a corrupted shim. */
function accountBindings(quads: Quad[], anchor: string | undefined, onlySubject: string | null) {
const bySubject = new Map<string, { id: string; pub: string[]; prot: string[]; priv: string[] }>();
for (const q of quads) {
@@ -130,19 +141,33 @@ function accountBindings(quads: Quad[], anchor: string | undefined, onlySubject:
return bindings;
}
/** Non-reactive fake ng (no doc_subscribe → no sync lag, no retry). */
/** Reactive fake ng modelling the pointer → doc-shim indirection. `doc_subscribe`
* pushes a first `State` so the doc-shim barrier resolves synchronously. */
function makeFakeNg() {
const quads: Quad[] = [];
let docCounter = 0;
let accountQueryCount = 0;
// Count account SELECTs per anchor graph. The AUTHORITATIVE account read is anchored
// to the doc-shim (a did:ng:o: NURI); the one-time legacy MIGRATION scan is anchored
// to the store-root (ROOT). Counting per-anchor lets a test assert "exactly one
// doc-shim account read" (no account RETRY) separately from the migration scan.
const accountReadsByAnchor = new Map<string, number>();
const doc_create = mock(async (..._a: unknown[]) => `did:ng:o:doc${++docCounter}`);
const sparql_update = makeSparqlUpdate(quads);
const sparql_query = mock(async (...a: unknown[]) => {
const query = a[1] as string;
const anchor = a[3] as string | undefined;
// Pointer SELECT (store-root).
if (query.includes("<urn:ng-eventually:shim:shimDoc>")) {
const bindings = quads
.filter((q) => q.g === anchor && q.p === "urn:ng-eventually:shim:shimDoc")
.map((q) => ({ shimDoc: { value: q.o } }));
return { results: { bindings } };
}
// Account SELECT — anchored either to the doc-shim (authoritative read) or, for
// the migration scan, to the store-root (legacy location). Same shape either way.
if (query.includes("<urn:ng-eventually:shim:id>")) {
accountQueryCount++;
const subjM = query.match(/GRAPH <[^>]+>\s*\{\s*<([^>]+)>\s+a\s+<urn:ng-eventually:shim:Account>/);
accountReadsByAnchor.set(anchor ?? "", (accountReadsByAnchor.get(anchor ?? "") ?? 0) + 1);
const subjM = query.match(/<([^>]+)>\s+a\s+<urn:ng-eventually:shim:Account>/);
return { results: { bindings: accountBindings(quads, anchor, subjM ? subjM[1]! : null) } };
}
const bindings = quads
@@ -150,40 +175,7 @@ function makeFakeNg() {
.map((q) => ({ e: { value: q.o } }));
return { results: { bindings } };
});
return { doc_create, sparql_update, sparql_query, _quads: quads, getAccountQueryCount: () => accountQueryCount };
}
/** Fake ng with a SYNC-LAG simulation: the first `lag` account reads return 0 rows
* (shim not synced yet), then the seeded data appears — modelling a fresh page over
* a persistent wallet. Used with a fast `provisionRetry` budget to exercise the
* anti-fork retry. (Carries a `doc_subscribe` so it also passes as a reactive ng.) */
function makeLaggyFakeNg(opts: { lag?: number } = {}) {
const quads: Quad[] = [];
let docCounter = 0;
let accountQueryCount = 0;
let lag = opts.lag ?? 0;
const doc_create = mock(async (..._a: unknown[]) => `did:ng:o:doc${++docCounter}`);
const sparql_update = makeSparqlUpdate(quads);
const sparql_query = mock(async (...a: unknown[]) => {
const query = a[1] as string;
const anchor = a[3] as string | undefined;
if (query.includes("<urn:ng-eventually:shim:id>")) {
accountQueryCount++;
if (lag > 0) { lag--; return { results: { bindings: [] } }; } // sync not landed yet
const subjM = query.match(/GRAPH <[^>]+>\s*\{\s*<([^>]+)>\s+a\s+<urn:ng-eventually:shim:Account>/);
return { results: { bindings: accountBindings(quads, anchor, subjM ? subjM[1]! : null) } };
}
const bindings = quads
.filter((q) => q.g === anchor && q.p === "urn:ng-eventually:shim:contains")
.map((q) => ({ e: { value: q.o } }));
return { results: { bindings } };
});
// doc_subscribe: immediately push a State (the sync barrier) so `ensureRepoOpen`
// resolves at once. `resolveAccount`/`ensureAccount` now open the anchor repo
// (open-repo.ts) before reading/writing the shim (the cold-start heal); the real
// broker pushes `TabInfo` then a first `State` on subscribe, and open-repo awaits
// that `State`. Model it: invoke the callback with a `State` AppResponse so the
// barrier is reached synchronously (no 8s fallback → the retry tests stay fast).
// Push a `State` on subscribe (the sync barrier) so ensureRepoOpen resolves at once.
const doc_subscribe = mock(async (_repo: unknown, _sid: unknown, cb: Function) => {
if (typeof cb === "function") cb({ V0: { State: {} } });
return () => {};
@@ -191,47 +183,52 @@ function makeLaggyFakeNg(opts: { lag?: number } = {}) {
return {
doc_create, sparql_update, sparql_query, doc_subscribe,
_quads: quads,
getAccountQueryCount: () => accountQueryCount,
// Total account reads across all anchors.
getAccountQueryCount: () => [...accountReadsByAnchor.values()].reduce((a, b) => a + b, 0),
// Account reads anchored to a did:ng:o: doc-shim (excludes the store-root migration scan).
getDocShimAccountReads: () =>
[...accountReadsByAnchor.entries()]
.filter(([g]) => g.startsWith("did:ng:o:"))
.reduce((a, [, n]) => a + n, 0),
};
}
function inject(
fakeNg: unknown,
provisionRetry?: { attempts?: number; baseMs?: number; maxStepMs?: number },
pointerGuard?: { attempts?: number; baseMs?: number; maxStepMs?: number },
) {
configure({ ng: fakeNg as any, useShape: (() => {}) as any });
configureStoreRegistry({
getSession: async () => SESSION,
normalizeId: (u) => u.trim().toLowerCase(),
// Default (unset) → attempts:1 (no retry). The retry tests pass a fast budget.
provisionRetry,
pointerGuard,
});
resetRegistryCache();
resetOpenedRepos();
}
// ---------------------------------------------------------------------------
// (1) Deterministic resolution
// (1) Deterministic resolution over fork residue (in the doc-shim)
// ---------------------------------------------------------------------------
describe("deterministic resolution over a shim corrupted by fork residue", () => {
describe("deterministic resolution over a doc-shim corrupted by fork residue", () => {
beforeEach(() => { resetRegistryCache(); resetOpenedRepos(); });
it("(1a) a subject with MULTIPLE docPublic values always resolves the SAME canonical (lexicographically-smallest)", async () => {
const fakeNg = makeFakeNg();
inject(fakeNg);
const anchor = "did:ng:PRIV-AF";
// Same account subject with 5 duplicate docPublic values (fork residue), out of
// lexicographic order, plus one docProtected/docPrivate each.
const docShim = "did:ng:o:shimdoc";
// Seed the pointer (store-root → doc-shim) and the corrupted record IN the doc-shim.
fakeNg._quads.push({ g: ROOT, s: "urn:ng-eventually:shim:root", p: "urn:ng-eventually:shim:shimDoc", o: docShim });
const subj = "urn:ng-eventually:shim:account:dupuser";
const dupPublics = [
"did:ng:o:pub-m", "did:ng:o:pub-a", "did:ng:o:pub-z", "did:ng:o:pub-c", "did:ng:o:pub-a",
];
fakeNg._quads.push({ g: anchor, s: subj, p: "urn:ng-eventually:shim:id", o: "dupuser" });
fakeNg._quads.push({ g: docShim, s: subj, p: "urn:ng-eventually:shim:id", o: "dupuser" });
for (const p of dupPublics)
fakeNg._quads.push({ g: anchor, s: subj, p: "urn:ng-eventually:shim:docPublic", o: p });
fakeNg._quads.push({ g: anchor, s: subj, p: "urn:ng-eventually:shim:docProtected", o: "did:ng:o:prot-1" });
fakeNg._quads.push({ g: anchor, s: subj, p: "urn:ng-eventually:shim:docPrivate", o: "did:ng:o:priv-1" });
fakeNg._quads.push({ g: docShim, s: subj, p: "urn:ng-eventually:shim:docPublic", o: p });
fakeNg._quads.push({ g: docShim, s: subj, p: "urn:ng-eventually:shim:docProtected", o: "did:ng:o:prot-1" });
fakeNg._quads.push({ g: docShim, s: subj, p: "urn:ng-eventually:shim:docPrivate", o: "did:ng:o:priv-1" });
const r1 = await resolveAccount("dupuser");
resetRegistryCache();
@@ -240,9 +237,7 @@ describe("deterministic resolution over a shim corrupted by fork residue", () =>
// Canonical = lexicographically smallest → "did:ng:o:pub-a".
expect(r1?.docPublic).toBe("did:ng:o:pub-a");
// Stable across independent resolves...
expect(r2?.docPublic).toBe(r1?.docPublic);
// ...and loadShim (full scan) agrees with resolveAccount (targeted).
expect(viaShim?.docPublic).toBe(r1?.docPublic);
expect(viaShim?.docProtected).toBe("did:ng:o:prot-1");
expect(viaShim?.docPrivate).toBe("did:ng:o:priv-1");
@@ -250,18 +245,21 @@ describe("deterministic resolution over a shim corrupted by fork residue", () =>
});
// ---------------------------------------------------------------------------
// (2) Anti-fork bounded retry
// (2) Barrier-authoritative reconnect — the core fix (no account retry)
// ---------------------------------------------------------------------------
describe("ensureAccount: anti-fork bounded retry", () => {
describe("reconnect resolves the SAME account through the doc-shim barrier (no fork, no account retry)", () => {
beforeEach(() => { resetRegistryCache(); resetOpenedRepos(); });
it("(2a) NO-FORK: account already in shim → reused, 0 new doc_create (non-reactive fake, single read)", async () => {
it("(2a) NO-FORK: account already in the doc-shim → reused, 0 new scope docs", async () => {
const fakeNg = makeFakeNg();
inject(fakeNg);
// First login: provisions the account (1 doc-shim + 3 scope docs).
const first = await ensureAccount("LauraBarrier");
expect(fakeNg.doc_create).toHaveBeenCalledTimes(3);
expect(fakeNg.doc_create).toHaveBeenCalledTimes(4);
// Fresh page over the SAME persistent quads: reset all in-memory caches, keep the
// quads. Reconnect must find the SAME account via the doc-shim barrier, NO new docs.
resetRegistryCache();
resetOpenedRepos();
const second = await ensureAccount("LauraBarrier");
@@ -269,56 +267,62 @@ describe("ensureAccount: anti-fork bounded retry", () => {
expect(second.docPublic).toBe(first.docPublic);
expect(second.docProtected).toBe(first.docProtected);
expect(second.docPrivate).toBe(first.docPrivate);
expect(fakeNg.doc_create).toHaveBeenCalledTimes(3); // still 3, not 6
// Still 4 — no doc-shim re-created (pointer reused), no scope docs re-created.
expect(fakeNg.doc_create).toHaveBeenCalledTimes(4);
});
it("(2b) SYNC LAG: shim reads 0 K times then the data → RETRY reuses, no fork", async () => {
// Seed an account into an initial (non-reactive) fake, capture its NURIs.
it("(2b) barrier-authoritative: a fresh session finds the persisted account on the FIRST read — single doc-shim read, NO retry", async () => {
// Seed session 1; capture the account NURIs + the persistent quads.
const seed = makeFakeNg();
inject(seed);
const orig = await ensureAccount("LaggyUser");
expect(seed.doc_create).toHaveBeenCalledTimes(3);
const orig = await ensureAccount("BarrierUser");
expect(seed.doc_create).toHaveBeenCalledTimes(4);
// Fresh reactive session over the SAME quads, with a 3-read sync lag: the first
// 3 account reads return 0 rows (shim not synced), then the seeded data appears.
const reactive = makeLaggyFakeNg({ lag: 3 });
reactive._quads.push(...seed._quads);
inject(reactive, { attempts: 8, baseMs: 1, maxStepMs: 2 }); // fast budget
// Fresh reactive session over the SAME persistent quads. The doc-shim pushes a
// `State` on subscribe → resolveShimDoc opens the barrier → the account read is
// authoritative on the FIRST attempt. Give a MULTI-attempt pointer guard to prove
// it is NOT used for the account.
const reconnect = makeFakeNg();
reconnect._quads.push(...seed._quads);
inject(reconnect, { attempts: 8, baseMs: 1, maxStepMs: 2 });
const resolved = await ensureAccount("LaggyUser");
const resolved = await ensureAccount("BarrierUser");
// Reused the SAME account — NO fork provisioning despite the initial 0 rows.
expect(resolved.docPublic).toBe(orig.docPublic);
expect(resolved.docProtected).toBe(orig.docProtected);
expect(resolved.docPrivate).toBe(orig.docPrivate);
expect(reactive.doc_create).toHaveBeenCalledTimes(0); // no new docs → no fork
// It DID retry: more than one account read (1 initial + retries until data).
expect(reactive.getAccountQueryCount()).toBeGreaterThan(1);
expect(reconnect.doc_create).toHaveBeenCalledTimes(0); // no new docs → no fork
// Barrier-authoritative: found on the FIRST doc-shim read (the store-root migration
// scan, which finds nothing to migrate here, is separate).
expect(reconnect.getDocShimAccountReads()).toBe(1);
});
it("(2c) GENUINELY NEW: shim always reads 0 → provisioned exactly once after the budget", async () => {
const reactive = makeLaggyFakeNg({ lag: 999 }); // never resolves → genuinely new
inject(reactive, { attempts: 5, baseMs: 1, maxStepMs: 2 });
it("(2c) GENUINELY NEW: a cold doc-shim reads 0 → provisioned exactly once, no retry", async () => {
// Pointer + doc-shim exist but the doc-shim holds NO record for this account.
const fakeNg = makeFakeNg();
inject(fakeNg, { attempts: 5, baseMs: 1, maxStepMs: 2 });
const docShim = "did:ng:o:preexisting-shim";
fakeNg._quads.push({ g: ROOT, s: "urn:ng-eventually:shim:root", p: "urn:ng-eventually:shim:shimDoc", o: docShim });
const rec = await ensureAccount("BrandNewUser");
// Provisioned exactly ONE set of scope docs.
expect(reactive.doc_create).toHaveBeenCalledTimes(3);
// Provisioned exactly ONE set of 3 scope docs (the doc-shim already existed).
expect(fakeNg.doc_create).toHaveBeenCalledTimes(3);
expect(rec.docPublic).toMatch(/^did:ng:o:doc/);
expect(rec.docProtected).not.toBe(rec.docPublic);
// Retry was BOUNDED: exactly `attempts` account reads, then it gave up and provisioned.
expect(reactive.getAccountQueryCount()).toBe(5);
// Barrier-authoritative: exactly ONE doc-shim account read (the 0 is definitive).
expect(fakeNg.getDocShimAccountReads()).toBe(1);
});
it("(2d) default budget (unset → attempts:1): genuinely-new account → single read, no retry", async () => {
it("(2d) default budget (unset pointer guard): genuinely-new account → single doc-shim account read", async () => {
const fakeNg = makeFakeNg();
inject(fakeNg); // provisionRetry unset → attempts:1 (synchronous default)
inject(fakeNg); // pointerGuard unset → attempts:1 (synchronous default)
const rec = await ensureAccount("SyncUser");
expect(fakeNg.doc_create).toHaveBeenCalledTimes(3);
// Exactly ONE account read — the default budget does not retry.
expect(fakeNg.getAccountQueryCount()).toBe(1);
// 1 doc-shim + 3 scope docs.
expect(fakeNg.doc_create).toHaveBeenCalledTimes(4);
expect(fakeNg.getDocShimAccountReads()).toBe(1);
expect(rec.docPublic).toMatch(/^did:ng:o:doc/);
});
@@ -328,6 +332,66 @@ describe("ensureAccount: anti-fork bounded retry", () => {
const a = await ensureAccount("SameUser");
const b = await ensureAccount("SameUser");
expect(b).toEqual(a);
expect(fakeNg.doc_create).toHaveBeenCalledTimes(3);
expect(fakeNg.doc_create).toHaveBeenCalledTimes(4); // 1 doc-shim + 3 scope docs
});
});
// ---------------------------------------------------------------------------
// (3) Migration — legacy store-root records folded into the doc-shim
// ---------------------------------------------------------------------------
describe("migration: legacy store-root records are read (not re-provisioned) after reconnect", () => {
beforeEach(() => { resetRegistryCache(); resetOpenedRepos(); });
it("(3a) a pre-indirection account (records in the store-root, no pointer) is migrated into a new doc-shim and resolves — no fork", async () => {
const fakeNg = makeFakeNg();
inject(fakeNg);
// Seed a LEGACY account directly in the store-root graph (old location), NO pointer.
const subj = "urn:ng-eventually:shim:account:legacyuser";
fakeNg._quads.push({ g: ROOT, s: subj, p: "urn:ng-eventually:shim:id", o: "legacyuser" });
fakeNg._quads.push({ g: ROOT, s: subj, p: "urn:ng-eventually:shim:docPublic", o: "did:ng:o:legacy-pub" });
fakeNg._quads.push({ g: ROOT, s: subj, p: "urn:ng-eventually:shim:docProtected", o: "did:ng:o:legacy-prot" });
fakeNg._quads.push({ g: ROOT, s: subj, p: "urn:ng-eventually:shim:docPrivate", o: "did:ng:o:legacy-priv" });
const rec = await ensureAccount("legacyuser");
// The legacy account was READ (migrated), NOT re-provisioned: original NURIs come
// back, and NO scope docs were created (only the fresh doc-shim: 1 doc_create).
expect(rec.docPublic).toBe("did:ng:o:legacy-pub");
expect(rec.docProtected).toBe("did:ng:o:legacy-prot");
expect(rec.docPrivate).toBe("did:ng:o:legacy-priv");
expect(fakeNg.doc_create).toHaveBeenCalledTimes(1); // only the new doc-shim
// A pointer was written, and the record now also lives in the doc-shim.
const pointerRow = fakeNg._quads.find(
(q) => q.g === ROOT && q.p === "urn:ng-eventually:shim:shimDoc",
);
expect(pointerRow?.o).toMatch(/^did:ng:o:doc/);
const inDocShim = fakeNg._quads.some(
(q) => q.g === pointerRow!.o && q.p === "urn:ng-eventually:shim:docPublic" && q.o === "did:ng:o:legacy-pub",
);
expect(inDocShim).toBe(true);
});
it("(3b) a pointer that predates migration still folds legacy store-root records into its doc-shim", async () => {
const fakeNg = makeFakeNg();
inject(fakeNg);
// A doc-shim + pointer already exist (empty doc-shim), records still only in the root.
const docShim = "did:ng:o:existing-shim";
fakeNg._quads.push({ g: ROOT, s: "urn:ng-eventually:shim:root", p: "urn:ng-eventually:shim:shimDoc", o: docShim });
const subj = "urn:ng-eventually:shim:account:oldtimer";
fakeNg._quads.push({ g: ROOT, s: subj, p: "urn:ng-eventually:shim:id", o: "oldtimer" });
fakeNg._quads.push({ g: ROOT, s: subj, p: "urn:ng-eventually:shim:docPublic", o: "did:ng:o:old-pub" });
fakeNg._quads.push({ g: ROOT, s: subj, p: "urn:ng-eventually:shim:docProtected", o: "did:ng:o:old-prot" });
fakeNg._quads.push({ g: ROOT, s: subj, p: "urn:ng-eventually:shim:docPrivate", o: "did:ng:o:old-priv" });
const rec = await ensureAccount("oldtimer");
expect(rec.docPublic).toBe("did:ng:o:old-pub");
expect(fakeNg.doc_create).toHaveBeenCalledTimes(0); // doc-shim already existed
const inDocShim = fakeNg._quads.some(
(q) => q.g === docShim && q.p === "urn:ng-eventually:shim:docPublic" && q.o === "did:ng:o:old-pub",
);
expect(inDocShim).toBe(true);
});
});