• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

knowledgepixels / nanopub-query / 28032874768

23 Jun 2026 02:16PM UTC coverage: 61.38%. Remained the same
28032874768

push

github

web-flow
Merge pull request #126 from knowledgepixels/fix/issue-125-persist-role-tier

fix(spaces): persist role tier + role IRI on non-admin RoleInstantiation rows (#125)

541 of 974 branches covered (55.54%)

Branch coverage included in aggregate %.

1568 of 2462 relevant lines covered (63.69%)

9.6 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

19.09
src/main/java/com/knowledgepixels/query/AuthorityResolver.java
1
package com.knowledgepixels.query;
2

3
import java.util.ArrayList;
4
import java.util.List;
5
import java.util.Optional;
6
import java.util.Set;
7

8
import org.eclipse.rdf4j.common.transaction.IsolationLevels;
9
import org.eclipse.rdf4j.model.IRI;
10
import org.eclipse.rdf4j.model.Statement;
11
import org.eclipse.rdf4j.model.Value;
12
import org.eclipse.rdf4j.model.ValueFactory;
13
import org.eclipse.rdf4j.model.impl.SimpleValueFactory;
14
import org.eclipse.rdf4j.model.vocabulary.FOAF;
15
import org.eclipse.rdf4j.model.vocabulary.RDF;
16
import org.eclipse.rdf4j.query.BindingSet;
17
import org.eclipse.rdf4j.query.QueryLanguage;
18
import org.eclipse.rdf4j.query.TupleQueryResult;
19
import org.eclipse.rdf4j.repository.RepositoryConnection;
20
import org.eclipse.rdf4j.repository.RepositoryResult;
21
import org.nanopub.vocabulary.NPA;
22
import org.nanopub.vocabulary.NPX;
23
import org.slf4j.Logger;
24
import org.slf4j.LoggerFactory;
25

26
import com.knowledgepixels.query.vocabulary.GEN;
27
import com.knowledgepixels.query.vocabulary.NPAT;
28
import com.knowledgepixels.query.vocabulary.SpacesVocab;
29

30
/**
31
 * Drives the space-state materialization pipeline. Three entry points scheduled
32
 * by {@code MainVerticle}:
33
 * <ul>
34
 *   <li>{@link #tick()} — detects trust-state flips (full build) and otherwise
35
 *       advances the current space-state graph by an {@link #runIncrementalCycle
36
 *       incremental cycle} bounded by {@code (processedUpTo, currentLoadCounter]}.</li>
37
 *   <li>{@link #periodicRebuildTick()} — checks the {@code npa:needsFullRebuild}
38
 *       flag set by structural invalidations and re-runs the full build into a
39
 *       fresh graph, atomically flips the pointer, drops the old graph.</li>
40
 *   <li>{@link #cleanOrphans()} — startup cleanup of {@code npass:*} graphs the
41
 *       pointer isn't referencing.</li>
42
 * </ul>
43
 *
44
 * <p>Incremental cycle order: invalidation DELETEs (admin RI / RoleAssignment /
45
 * non-admin RI) → mirror-step delta is implicit (rebuilt only on full build) →
46
 * per-tier INSERTs (admin → alias → attachment → maintainer → member → observer) →
47
 * late-arrival sweep (re-run downstream tiers without the load-number filter
48
 * iff this cycle added any structural rows). Sets {@code npa:needsFullRebuild}
49
 * when an admin RI / RoleAssignment / RoleDeclaration was invalidated; periodic
50
 * worker turns the flag into a from-scratch rebuild.
51
 *
52
 * <p>See {@code doc/design-space-repositories.md} — this implements the "Full
53
 * build", "Incremental cycle", and "Periodic full rebuild" procedures.
54
 */
55
public final class AuthorityResolver {
56

57
    private static final Logger logger = LoggerFactory.getLogger(AuthorityResolver.class);
9✔
58

59
    private static final ValueFactory vf = SimpleValueFactory.getInstance();
6✔
60

61
    private static final String SPACES_REPO = "spaces";
62
    private static final String TRUST_REPO = "trust";
63

64
    /** NPA constants pulled in locally (trust-side). */
65
    private static final IRI NPA_HAS_CURRENT_TRUST_STATE =
9✔
66
            vf.createIRI(NPA.NAMESPACE, "hasCurrentTrustState");
6✔
67
    private static final IRI NPA_ACCOUNT_STATE = vf.createIRI(NPA.NAMESPACE, "AccountState");
15✔
68
    private static final IRI NPA_AGENT = vf.createIRI(NPA.NAMESPACE, "agent");
15✔
69
    private static final IRI NPA_PUBKEY = vf.createIRI(NPA.NAMESPACE, "pubkey");
15✔
70
    private static final IRI NPA_TRUST_STATUS = vf.createIRI(NPA.NAMESPACE, "trustStatus");
15✔
71
    private static final IRI NPA_LOADED = vf.createIRI(NPA.NAMESPACE, "loaded");
15✔
72
    private static final IRI NPA_TO_LOAD = vf.createIRI(NPA.NAMESPACE, "toLoad");
15✔
73

74
    /**
75
     * Trust-approved set: rows with one of these {@code npa:trustStatus} values
76
     * are mirrored into the space-state graph. Per
77
     * {@code doc/design-trust-state-repos.md}, these are the two "authority-
78
     * approving" statuses; {@code npa:contested}, {@code npa:skipped}, and the
79
     * transient statuses are distinct values of the same predicate and are
80
     * excluded automatically by this positive-list filter.
81
     */
82
    private static final Set<IRI> APPROVED_SET = Set.of(NPA_LOADED, NPA_TO_LOAD);
15✔
83

84
    private static AuthorityResolver instance;
85

86
    /** Returns the singleton. */
87
    public static synchronized AuthorityResolver get() {
88
        if (instance == null) {
6✔
89
            instance = new AuthorityResolver();
12✔
90
        }
91
        return instance;
6✔
92
    }
93

94
    private AuthorityResolver() {
6✔
95
    }
3✔
96

97
    // ---------------- Operational metrics snapshot ----------------
98
    //
99
    // Updated at the end of each runFullBuild / runIncrementalCycle, read by
100
    // MetricsCollector via the get*() accessors below. volatile is enough —
101
    // writers serialise via the synchronized methods, and readers (Prometheus
102
    // scrapes) only need most-recent visibility, not transactional consistency
103
    // across the snapshot. Defaults to zero values so a scrape that races a
104
    // boot before the first cycle returns 0, not NaN.
105

106
    private volatile TierSubjectTotals lastSubjectTotals = new TierSubjectTotals(0L, 0L, 0L);
24✔
107
    private volatile long lastInsertedTriplesTotal;
108
    private volatile long lastFullBuildDurationMs;
109
    private volatile long lastIncrementalCycleDurationMs;
110
    private volatile long lastProcessedUpToLag;
111

112
    public TierSubjectTotals getLastSubjectTotals() { return lastSubjectTotals; }
9✔
113
    public long getLastInsertedTriplesTotal() { return lastInsertedTriplesTotal; }
9✔
114
    public long getLastFullBuildDurationMs() { return lastFullBuildDurationMs; }
9✔
115
    public long getLastIncrementalCycleDurationMs() { return lastIncrementalCycleDurationMs; }
9✔
116
    public long getLastProcessedUpToLag() { return lastProcessedUpToLag; }
9✔
117

118
    // ---------------- Public entry points ----------------
119

120
    /**
121
     * Poll entry point. Behaviour:
122
     * <ul>
123
     *   <li>If no current space-state graph or the trust state has flipped → full build.</li>
124
     *   <li>Otherwise → {@link #runIncrementalCycle incremental cycle} on the load-number
125
     *       delta {@code (processedUpTo, currentLoadCounter]}. No-op if {@code
126
     *       processedUpTo == currentLoadCounter}.</li>
127
     * </ul>
128
     * Safe to call repeatedly on a schedule. Gated by {@link FeatureFlags#spacesEnabled()}.
129
     */
130
    public void tick() {
131
        if (!FeatureFlags.spacesEnabled()) return;
6!
132
        String trustStateHash = TrustStateRegistry.get().getCurrentHash().orElse(null);
18✔
133
        if (trustStateHash == null) {
6!
134
            logger.debug("AuthorityResolver.tick: no current trust state yet — skipping");
9✔
135
            return;
3✔
136
        }
137
        IRI currentGraph = getCurrentSpaceStateGraph();
×
138
        String currentGraphName = (currentGraph == null) ? null
×
139
                : currentGraph.stringValue().substring(SpacesVocab.NPASS_NAMESPACE.length());
×
140
        if (currentGraphName == null || !currentGraphName.startsWith(trustStateHash + "_")) {
×
141
            logger.info("AuthorityResolver.tick: trust-state flip detected (now {}); running full build",
×
142
                    abbrev(trustStateHash));
×
143
            runFullBuild(trustStateHash);
×
144
            return;
×
145
        }
146
        runIncrementalCycle(currentGraph);
×
147
    }
×
148

149
    /**
150
     * Periodic worker. If {@code npa:needsFullRebuild} was raised by an
151
     * incremental cycle's structural DELETE, runs a from-scratch rebuild into
152
     * a fresh space-state graph (using the current trust-state hash and load
153
     * counter) and clears the flag. No-op when the flag is not set. Safe to
154
     * call concurrently with {@link #tick()} when both are scheduled on the
155
     * same single-threaded executor.
156
     */
157
    public void periodicRebuildTick() {
158
        if (!FeatureFlags.spacesEnabled()) return;
×
159
        if (!readNeedsFullRebuild()) return;
×
160
        String trustStateHash = TrustStateRegistry.get().getCurrentHash().orElse(null);
×
161
        if (trustStateHash == null) {
×
162
            logger.debug("AuthorityResolver.periodicRebuildTick: no current trust state — deferring");
×
163
            return;
×
164
        }
165
        logger.info("AuthorityResolver.periodicRebuildTick: needsFullRebuild flag set; rebuilding");
×
166
        runFullBuild(trustStateHash);
×
167
        clearNeedsFullRebuild();
×
168
    }
×
169

170
    /**
171
     * Startup cleanup: drop any {@code npass:*} graph that the
172
     * {@code npa:hasCurrentSpaceState} pointer isn't pointing at. Orphans come
173
     * from crashes mid-build. Safe to call at any time; idempotent.
174
     */
175
    public void cleanOrphans() {
176
        if (!FeatureFlags.spacesEnabled()) return;
×
177
        IRI current = getCurrentSpaceStateGraph();
×
178
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
179
            int dropped = 0;
×
180
            try (RepositoryResult<org.eclipse.rdf4j.model.Resource> ctxs = conn.getContextIDs()) {
×
181
                List<IRI> toDrop = new ArrayList<>();
×
182
                while (ctxs.hasNext()) {
×
183
                    org.eclipse.rdf4j.model.Resource ctx = ctxs.next();
×
184
                    if (!(ctx instanceof IRI iri)) continue;
×
185
                    if (!iri.stringValue().startsWith(SpacesVocab.NPASS_NAMESPACE)) continue;
×
186
                    if (iri.equals(current)) continue;
×
187
                    toDrop.add(iri);
×
188
                }
×
189
                for (IRI iri : toDrop) {
×
190
                    conn.begin(IsolationLevels.SERIALIZABLE);
×
191
                    conn.clear(iri);
×
192
                    conn.commit();
×
193
                    dropped++;
×
194
                    logger.info("AuthorityResolver.cleanOrphans: dropped orphan graph {}", iri);
×
195
                }
×
196
            }
197
            if (dropped == 0) {
×
198
                logger.debug("AuthorityResolver.cleanOrphans: no orphan space-state graphs");
×
199
            }
200
        } catch (Exception ex) {
×
201
            logger.info("AuthorityResolver.cleanOrphans: failed: {}", ex.toString());
×
202
        }
×
203
    }
×
204

205
    // ---------------- Full build ----------------
206

207
    /**
208
     * Mutex-protected full build of the space-state graph for the given trust
209
     * state. Captures {@code M = currentLoadCounter}, mirrors trust-approved
210
     * rows, (PR 2b: runs per-tier UPDATE loops from scratch), stamps
211
     * {@code processedUpTo = M}, flips the pointer, drops the previous graph.
212
     */
213
    synchronized void runFullBuild(String trustStateHash) {
214
        long startNanos = System.nanoTime();
×
215
        long loadCounter = getCurrentLoadCounter();
×
216
        IRI newGraph = SpacesVocab.forSpaceState(trustStateHash, loadCounter);
×
217
        IRI oldGraph = getCurrentSpaceStateGraph();
×
218
        if (newGraph.equals(oldGraph)) {
×
219
            logger.debug("AuthorityResolver.runFullBuild: already current at {}", newGraph);
×
220
            return;
×
221
        }
222

223
        // 1. Mirror trust-approved rows into the new graph.
224
        int mirrored = mirrorTrustState(trustStateHash, newGraph);
×
225

226
        // 2. Per-tier UPDATE loops (from scratch: lastProcessed = -1 so the
227
        //    delta filter FILTER(?ln > ?lastProcessed) includes everything).
228
        TierInsertedTriples counts = runAllTierLoops(newGraph, -1);
×
229

230
        // 3. Stamp processedUpTo inside the new graph.
231
        writeProcessedUpTo(newGraph, loadCounter);
×
232

233
        // 4. Flip the current-space-state pointer.
234
        flipPointer(newGraph);
×
235

236
        // 5. Drop the old graph if one existed.
237
        if (oldGraph != null) {
×
238
            dropGraph(oldGraph);
×
239
        }
240

241
        TierSubjectTotals totals = computeTierSubjectTotals(newGraph);
×
242
        long durationMs = (System.nanoTime() - startNanos) / 1_000_000L;
×
243
        lastSubjectTotals = totals;
×
244
        lastInsertedTriplesTotal = (long) counts.admin + counts.alias + counts.presetAttachment
×
245
                + counts.presetAssignmentRef
246
                + counts.attachment + counts.maintainer + counts.member + counts.observer
247
                + counts.subSpace + counts.subSpacePrefix + counts.maintainedResource;
248
        lastFullBuildDurationMs = durationMs;
×
249
        lastProcessedUpToLag = 0L;
×
250
        logger.info("AuthorityResolver: full build complete — graph={} mirrored={} rows loadCounter={} "
×
251
                        + "subjects: adminRIs={} attachmentRAs={} nonAdminRIs={} "
252
                        + "(inserted-triples: admin={} alias={} preset-attachment={} preset-assignment-ref={} attachment={} maintainer={} member={} observer={} "
253
                        + "subspace={} subspace-prefix={} maintained-resource={}) durationMs={}",
254
                newGraph, mirrored, loadCounter,
×
255
                totals.adminRIs(), totals.attachmentRAs(), totals.nonAdminRIs(),
×
256
                counts.admin, counts.alias, counts.presetAttachment, counts.presetAssignmentRef, counts.attachment, counts.maintainer, counts.member, counts.observer,
×
257
                counts.subSpace, counts.subSpacePrefix, counts.maintainedResource,
×
258
                durationMs);
×
259
    }
×
260

261
    // ---------------- Incremental cycle ----------------
262

263
    /**
264
     * Single delta cycle on the current space-state graph. Bounded by
265
     * {@code (processedUpTo, currentLoadCounter]}; no-op if the range is empty.
266
     *
267
     * <p>Order:
268
     * <ol>
269
     *   <li>Apply invalidation DELETEs (admin RI, RoleAssignment, non-admin RI)
270
     *       and the RoleDeclaration ASK. Any DELETE on a structural kind sets
271
     *       {@code npa:needsFullRebuild} to bound the staleness from sticky
272
     *       downstream entries; the periodic worker turns that into a from-scratch
273
     *       rebuild on its next pass.</li>
274
     *   <li>Run per-tier INSERTs in the same order as the full build.</li>
275
     *   <li>Late-arrival sweep: if any structural row was added, re-run downstream
276
     *       tier INSERTs with {@code lastProcessed = -1} to catch candidates whose
277
     *       enabling event landed in this same cycle. Dedup filters protect
278
     *       against double-insert.</li>
279
     *   <li>Bump {@code processedUpTo} to {@code currentLoadCounter}.</li>
280
     * </ol>
281
     */
282
    synchronized void runIncrementalCycle(IRI graph) {
283
        long startNanos = System.nanoTime();
×
284
        long currentLoadCounter = getCurrentLoadCounter();
×
285
        long lastProcessed = readProcessedUpTo(graph);
×
286
        if (lastProcessed < 0) {
×
287
            logger.warn("AuthorityResolver.runIncrementalCycle: missing processedUpTo on {}; skipping",
×
288
                    graph);
289
            return;
×
290
        }
291
        lastProcessedUpToLag = currentLoadCounter - lastProcessed;
×
292
        if (currentLoadCounter <= lastProcessed) {
×
293
            logger.debug("AuthorityResolver.runIncrementalCycle: caught up at load {} on {}",
×
294
                    currentLoadCounter, graph);
×
295
            return;
×
296
        }
297

298
        boolean structuralInvalidation = applyInvalidations(graph, lastProcessed);
×
299
        TierInsertedTriples counts = runAllTierLoops(graph, lastProcessed);
×
300
        boolean structuralAdds = (counts.admin > 0)
×
301
                || (counts.alias > 0)
302
                || (counts.presetAttachment > 0)
303
                || (counts.attachment > 0)
304
                || (counts.subSpace > 0)
305
                || newRoleDeclarationsArrived(lastProcessed)
×
306
                || newPresetAssignmentsArrived(lastProcessed);
×
307
        if (structuralAdds) {
×
308
            // Late-arrival sweep: leaf tiers (attachment/maintainer/member/observer)
309
            // can promote candidates whose enabling event arrived in this same cycle.
310
            // Sub-space admit is also re-run here for Mode-B late-arrival (a new
311
            // partner declaration can validate an older primary that the regular
312
            // pass's load-number filter excluded). The URL-prefix fallback also
313
            // re-runs so newly-orphaned children pick up derived edges. Skip the
314
            // admin tier — its only enabling event is the admin grant itself,
315
            // already handled by the regular pass.
316
            TierInsertedTriples lateCounts = runDownstreamWithoutLoadFilter(graph);
×
317
            counts.alias              += lateCounts.alias;
×
318
            counts.presetAttachment   += lateCounts.presetAttachment;
×
319
            counts.presetAssignmentRef += lateCounts.presetAssignmentRef;
×
320
            counts.attachment         += lateCounts.attachment;
×
321
            counts.maintainer         += lateCounts.maintainer;
×
322
            counts.member             += lateCounts.member;
×
323
            counts.observer           += lateCounts.observer;
×
324
            counts.subSpace           += lateCounts.subSpace;
×
325
            counts.subSpacePrefix     += lateCounts.subSpacePrefix;
×
326
            counts.maintainedResource += lateCounts.maintainedResource;
×
327
        }
328

329
        writeProcessedUpTo(graph, currentLoadCounter);
×
330

331
        TierSubjectTotals totals = computeTierSubjectTotals(graph);
×
332
        long durationMs = (System.nanoTime() - startNanos) / 1_000_000L;
×
333
        lastSubjectTotals = totals;
×
334
        lastInsertedTriplesTotal = (long) counts.admin + counts.alias + counts.presetAttachment
×
335
                + counts.presetAssignmentRef
336
                + counts.attachment + counts.maintainer + counts.member + counts.observer
337
                + counts.subSpace + counts.subSpacePrefix + counts.maintainedResource;
338
        lastIncrementalCycleDurationMs = durationMs;
×
339
        logger.info("AuthorityResolver: incremental cycle complete — graph={} delta=({}, {}] "
×
340
                        + "subjects: adminRIs={} attachmentRAs={} nonAdminRIs={} "
341
                        + "(inserted-triples: admin={} alias={} preset-attachment={} preset-assignment-ref={} attachment={} maintainer={} member={} observer={} "
342
                        + "subspace={} subspace-prefix={} maintained-resource={}) "
343
                        + "structuralInvalidation={} structuralAdds={} durationMs={}",
344
                graph, lastProcessed, currentLoadCounter,
×
345
                totals.adminRIs(), totals.attachmentRAs(), totals.nonAdminRIs(),
×
346
                counts.admin, counts.alias, counts.presetAttachment, counts.presetAssignmentRef, counts.attachment, counts.maintainer, counts.member, counts.observer,
×
347
                counts.subSpace, counts.subSpacePrefix, counts.maintainedResource,
×
348
                structuralInvalidation, structuralAdds, durationMs);
×
349
    }
×
350

351
    /**
352
     * Runs the four invalidation-DELETE / ASK steps. Sets {@code npa:needsFullRebuild}
353
     * when admin-RI, RoleAssignment, or RoleDeclaration invalidations matched (the
354
     * three structural kinds). Leaf-tier RI deletes don't set the flag.
355
     *
356
     * @return true iff at least one structural kind was invalidated
357
     */
358
    boolean applyInvalidations(IRI graph, long lastProcessed) {
359
        boolean structural = false;
×
360
        if (wouldInvalidate(graph, lastProcessed, /*adminPinned=*/ true,
×
361
                            adminInvalidationCheckWhere(graph, lastProcessed))) {
×
362
            executeUpdate(adminInvalidationDelete(graph, lastProcessed));
×
363
            structural = true;
×
364
        }
365
        if (wouldInvalidate(graph, lastProcessed, /*adminPinned=*/ false,
×
366
                            roleAssignmentInvalidationCheckWhere(graph, lastProcessed))) {
×
367
            executeUpdate(roleAssignmentInvalidationDelete(graph, lastProcessed));
×
368
            structural = true;
×
369
        }
370
        // Role-declaration invalidation is deliberately NOT acted on (see
371
        // nonAdminTierUpdate): a role assignment is governed by the admin-validated
372
        // attachment, not by the declaration author's later supersession/retraction, so
373
        // an invalidated RD neither deletes rows nor triggers a rebuild.
374
        // Sub-space declarations are structural — invalidating one (Mode A) or one
375
        // of two co-declarations (Mode B) changes the validated parent/child
376
        // topology. The DELETE removes the per-declaration row; the convenience
377
        // direct triples are left sticky and cleaned on the next periodic rebuild.
378
        if (wouldInvalidate(graph, lastProcessed, /*adminPinned=*/ false,
×
379
                            subSpaceInvalidationCheckWhere(graph, lastProcessed))) {
×
380
            executeUpdate(subSpaceInvalidationDelete(graph, lastProcessed));
×
381
            structural = true;
×
382
        }
383
        // Space-alias declarations are structural — invalidating one removes an
384
        // owl:sameAs edge that feeds the admin-authority closure (issue #113). The
385
        // DELETE removes the per-declaration row; the convenience npa:sameAsSpace edge
386
        // is left sticky and cleaned on the next periodic rebuild (same policy as
387
        // sub-space declarations).
388
        if (wouldInvalidate(graph, lastProcessed, /*adminPinned=*/ false,
×
389
                            aliasInvalidationCheckWhere(graph, lastProcessed))) {
×
390
            executeUpdate(aliasInvalidationDelete(graph, lastProcessed));
×
391
            structural = true;
×
392
        }
393
        // Preset-derived RoleAssignment removal (issue #302). NOT npx:invalidates: a newer
394
        // admin-authored same-(preset,resource) assignment supersedes by dct:created (a
395
        // gen:DeactivatedPresetAssignment, or any newer assignment that is no longer active).
396
        // Structural — sticky downstream non-admin RIs derived through a removed attachment
397
        // are bounded by the periodic full rebuild. The DELETE is scoped by
398
        // npa:derivedFromPreset so directly-published gen:hasRole attachments are never
399
        // touched; the §4.3 re-INSERT re-materializes only currently-active pairs in the same
400
        // cycle. See doc/design-preset-role-materialization.md §4.4.
401
        if (wouldInvalidate(graph, lastProcessed, /*adminPinned=*/ false,
×
402
                            presetDeactivationCheckWhere(graph, lastProcessed))) {
×
403
            executeUpdate(presetDeactivationDelete(graph, lastProcessed));
×
404
            structural = true;
×
405
        }
406
        // Leaf-tier RI deletes — no flag.
407
        executeUpdate(leafTierInvalidationDelete(graph, lastProcessed));
×
408
        // Ref-scoped preset-assignment listing stamps whose assignment nanopub was
409
        // hard-retracted (issue #122) — no flag (display leaf, nothing downstream).
410
        executeUpdate(presetAssignmentRefInvalidationDelete(graph, lastProcessed));
×
411
        // Maintained-resource declaration deletes — no flag (leaf relation, no
412
        // downstream caches to bound).
413
        executeUpdate(maintainedResourceInvalidationDelete(graph, lastProcessed));
×
414
        if (structural) setNeedsFullRebuild();
×
415
        return structural;
×
416
    }
417

418
    /**
419
     * Runs the four leaf tiers (attachment/maintainer/member/observer) with
420
     * {@code lastProcessed = -1} so the load-number filter on the candidate
421
     * side admits everything. Dedup filters in the tier templates prevent
422
     * double-insert. Used by the late-arrival sweep.
423
     */
424
    TierInsertedTriples runDownstreamWithoutLoadFilter(IRI graph) {
425
        TierInsertedTriples c = new TierInsertedTriples();
×
426
        // Alias late-arrival: catches alias declarations whose canonical admin grant
427
        // became valid only in this same cycle (the load-number filter on the
428
        // declaration's nanopub would otherwise exclude it). Runs first so the
429
        // attachment / role tiers below see this cycle's fresh npa:sameAsSpace edges.
430
        c.alias = runTierLabeled("alias(late)", graph, aliasAdmitUpdate(graph, -1));
×
431
        // Sub-space late-arrival: catches Mode-B candidates whose primary
432
        // declaration is older than lastProcessed but whose partner just landed.
433
        c.subSpace = runTierLabeled("subspace(late)", graph,
×
434
                subSpaceAdmitUpdate(graph, -1));
×
435
        // Maintained-resource late-arrival: catches declarations that landed
436
        // before the publisher's admin grant became valid in this state.
437
        c.maintainedResource = runTierLabeled("maintained-resource(late)", graph,
×
438
                maintainedResourceAdmitUpdate(graph, -1));
×
439
        // URL-prefix fallback: re-run after the late-arrival sub-space admit so
440
        // any newly-validated children get their fallback edges suppressed (for
441
        // future inserts) and any newly-orphaned children pick up fallback edges.
442
        c.subSpacePrefix = runTierLabeled("subspace-prefix(late)", graph,
×
443
                subSpacePrefixFallbackUpdate(graph));
×
444
        // Preset-attachment late-arrival: catches assignments whose preset declaration or
445
        // admin grant only became valid in this same cycle. Runs before attachment(late)
446
        // so the non-admin late tiers below see this cycle's fresh preset-derived RAs.
447
        c.presetAttachment = runTierLabeled("preset-attachment(late)", graph,
×
448
                presetAttachmentValidationUpdate(graph, -1));
×
449
        // Ref-scoped preset-assignment late stamp: catches assignments whose authorizing
450
        // admin grant only became valid this cycle (the load filter would skip the older
451
        // assignment nanopub). Mirrors the preset-attachment late sweep above.
452
        c.presetAssignmentRef = runTierLabeled("preset-assignment-ref(late)", graph,
×
453
                presetAssignmentRefStampUpdate(graph, -1));
×
454
        c.attachment = runTierLabeled("attachment(late)", graph,
×
455
                attachmentValidationUpdate(graph, -1));
×
456
        c.maintainer = runTierLabeled("maintainer(late)", graph,
×
457
                nonAdminTierUpdate(graph, -1, GEN.MAINTAINER_ROLE, PUBLISHER_IS_ADMIN));
×
458
        c.member = runTierLabeled("member(admin-pub,late)", graph,
×
459
                nonAdminTierUpdate(graph, -1, GEN.MEMBER_ROLE, PUBLISHER_IS_ADMIN));
×
460
        c.member += runTierLabeled("member(maint-pub,late)", graph,
×
461
                nonAdminTierUpdate(graph, -1,
×
462
                        GEN.MEMBER_ROLE, publisherIsTieredRole(GEN.MAINTAINER_ROLE)));
×
463
        c.observer = runTierLabeled("observer(admin-pub,late)", graph,
×
464
                nonAdminTierUpdate(graph, -1, GEN.OBSERVER_ROLE, PUBLISHER_IS_ADMIN));
×
465
        c.observer += runTierLabeled("observer(maint-pub,late)", graph,
×
466
                nonAdminTierUpdate(graph, -1,
×
467
                        GEN.OBSERVER_ROLE, publisherIsTieredRole(GEN.MAINTAINER_ROLE)));
×
468
        c.observer += runTierLabeled("observer(member-pub,late)", graph,
×
469
                nonAdminTierUpdate(graph, -1,
×
470
                        GEN.OBSERVER_ROLE, publisherIsTieredRole(GEN.MEMBER_ROLE)));
×
471
        c.observer += runTierLabeled("observer(self,late)", graph,
×
472
                nonAdminTierUpdate(graph, -1, GEN.OBSERVER_ROLE, PUBLISHER_IS_SELF));
×
473
        return c;
×
474
    }
475

476
    /**
477
     * Cheap ASK: did any new {@code npa:RoleDeclaration} extraction land in the
478
     * load-number delta {@code (lastProcessed, ∞)}? Used by the late-arrival
479
     * trigger so an RD that arrives in the same cycle as a matching candidate
480
     * still gets validated.
481
     */
482
    boolean newRoleDeclarationsArrived(long lastProcessed) {
483
        String ask = String.format("""
×
484
                PREFIX npa: <%1$s>
485
                ASK {
486
                  GRAPH <%2$s> {
487
                    ?rd a npa:RoleDeclaration ;
488
                        npa:viaNanopub ?np .
489
                  }
490
                  GRAPH <%3$s> {
491
                    ?np npa:hasLoadNumber ?ln .
492
                    FILTER (?ln > %4$d)
493
                  }
494
                }
495
                """, NPA.NAMESPACE, SpacesVocab.SPACES_GRAPH, NPA.GRAPH, lastProcessed);
×
496
        return runAsk(ask);
×
497
    }
498

499
    /**
500
     * Cheap ASK: did any new {@code npa:PresetAssignment} or {@code npa:PresetDeclaration}
501
     * extraction land in the load-number delta {@code (lastProcessed, ∞)}? Drives the
502
     * late-arrival re-run so a preset assignment that arrives in the same cycle as its
503
     * declaration (or admin grant) still materializes, and so an arriving newer assignment
504
     * triggers the deactivation/latest-wins re-evaluation.
505
     */
506
    boolean newPresetAssignmentsArrived(long lastProcessed) {
507
        String ask = String.format("""
×
508
                PREFIX npa: <%1$s>
509
                ASK {
510
                  GRAPH <%2$s> {
511
                    ?x a ?t ;
512
                       npa:viaNanopub ?np .
513
                    FILTER (?t = npa:PresetAssignment || ?t = npa:PresetDeclaration)
514
                  }
515
                  GRAPH <%3$s> {
516
                    ?np npa:hasLoadNumber ?ln .
517
                    FILTER (?ln > %4$d)
518
                  }
519
                }
520
                """, NPA.NAMESPACE, SpacesVocab.SPACES_GRAPH, NPA.GRAPH, lastProcessed);
×
521
        return runAsk(ask);
×
522
    }
523

524
    // ---------------- Tier UPDATE loops ----------------
525

526
    /**
527
     * Per-tier inserted-triple tallies for one build or cycle. Counts the sum
528
     * of {@code (graphSize_after - graphSize_before)} across all iterations of
529
     * each tier's fixed-point INSERT loop — i.e. inserted *triples*, not
530
     * distinct subjects (a single RoleInstantiation insert writes 4–5 triples).
531
     *
532
     * <p>Used internally by the {@link #runIncrementalCycle structuralAdds}
533
     * boolean check (we only care whether any tier inserted at all).
534
     * Not what the log lines report: see {@link TierSubjectTotals} +
535
     * {@link #computeTierSubjectTotals} for the distinct-subject totals
536
     * surfaced to operators.
537
     */
538
    static final class TierInsertedTriples {
×
539
        int admin;
540
        int alias;
541
        int presetAttachment;
542
        int presetAssignmentRef;
543
        int attachment;
544
        int maintainer;
545
        int member;
546
        int observer;
547
        int subSpace;
548
        int subSpacePrefix;
549
        int maintainedResource;
550
    }
551

552
    /**
553
     * Snapshot of distinct-subject totals in a space-state graph at a moment
554
     * in time. Independent of which tier-loop added each subject.
555
     */
556
    record TierSubjectTotals(long adminRIs, long attachmentRAs, long nonAdminRIs) {}
36✔
557

558
    /**
559
     * Runs the five tier loops in order: admin → {@code gen:hasRole} attachment
560
     * validation → maintainer → member → observer. Each loop iterates a SPARQL
561
     * INSERT to fixed point (no new triples added). Returns per-tier counts.
562
     *
563
     * @param graph         target space-state graph
564
     * @param lastProcessed load-number horizon; use {@code -1} for full build
565
     */
566
    TierInsertedTriples runAllTierLoops(IRI graph, long lastProcessed) {
567
        TierInsertedTriples c = new TierInsertedTriples();
×
568
        c.admin = runTierLabeled("admin", graph, adminTierUpdate(graph, lastProcessed));
×
569
        // Alias admit runs after the admin closure has settled (both the authority
570
        // gate and the anti-hijack check read the admin set) and before attachment /
571
        // role tiers (their alias-aware admin lookups consume the npa:sameAsSpace edge
572
        // this pass emits). See issue #113.
573
        c.alias = runTierLabeled("alias", graph, aliasAdmitUpdate(graph, lastProcessed));
×
574
        // Sub-space admit runs after admin closure has settled (Mode A + Mode B both
575
        // need the admin set). Independent of role tiers — order between subspace
576
        // and attachment / maintainer / member / observer doesn't matter.
577
        c.subSpace = runTierLabeled("subspace", graph, subSpaceAdmitUpdate(graph, lastProcessed));
×
578
        // Maintained-resource admit also depends only on the admin closure. Single
579
        // Mode A: publisher must be admin of the maintaining space. No co-declaration
580
        // partner, no URL-prefix fallback.
581
        c.maintainedResource = runTierLabeled("maintained-resource", graph,
×
582
                maintainedResourceAdmitUpdate(graph, lastProcessed));
×
583
        // URL-prefix sub-space fallback runs after the explicit-declaration admit
584
        // pass commits so the per-child suppression check sees this cycle's fresh
585
        // validations. No load filter — depends on which Spaces exist, not on
586
        // delta-arrivals; the dedup FILTER NOT EXISTS prevents re-insertion.
587
        c.subSpacePrefix = runTierLabeled("subspace-prefix", graph,
×
588
                subSpacePrefixFallbackUpdate(graph));
×
589
        // Preset-attachment runs immediately before the regular attachment tier so the
590
        // gen:RoleAssignment rows it materializes (from active, admin-authored preset
591
        // assignments) are picked up by the downstream non-admin tiers in the same pass,
592
        // exactly like directly-published attachments. See
593
        // doc/design-preset-role-materialization.md.
594
        c.presetAttachment = runTierLabeled("preset-attachment", graph,
×
595
                presetAttachmentValidationUpdate(graph, lastProcessed));
×
596
        // Ref-scoped preset-assignment listing stamp (issue #122). Display-only leaf —
597
        // independent of the role tiers and of structuralAdds; order doesn't matter.
598
        c.presetAssignmentRef = runTierLabeled("preset-assignment-ref", graph,
×
599
                presetAssignmentRefStampUpdate(graph, lastProcessed));
×
600
        c.attachment = runTierLabeled("attachment", graph,
×
601
                attachmentValidationUpdate(graph, lastProcessed));
×
602
        c.maintainer = runTierLabeled("maintainer", graph, nonAdminTierUpdate(graph, lastProcessed,
×
603
                GEN.MAINTAINER_ROLE, PUBLISHER_IS_ADMIN));
604
        // Member tier: admin OR maintainer publisher — split into two simpler updates
605
        // so the query planner doesn't struggle with the UNION.
606
        c.member = runTierLabeled("member(admin-pub)", graph, nonAdminTierUpdate(graph, lastProcessed,
×
607
                GEN.MEMBER_ROLE, PUBLISHER_IS_ADMIN));
608
        c.member += runTierLabeled("member(maint-pub)", graph, nonAdminTierUpdate(graph, lastProcessed,
×
609
                GEN.MEMBER_ROLE, publisherIsTieredRole(GEN.MAINTAINER_ROLE)));
×
610
        // Observer tier: self-evidence OR a downward grant from any higher tier.
611
        // ObserverRole is the default tier when a role definition omits an
612
        // explicit subclass (see "Role types" in design-space-repositories.md), so
613
        // most "X assigned Y this role" nanopubs land here. Restricting the tier
614
        // to PUBLISHER_IS_SELF would silently drop those grants. The four
615
        // sub-loops mirror the trust-state's downward-only chain: admin grants
616
        // anything; maintainers and members grant observer; everyone may
617
        // self-attest.
618
        c.observer = runTierLabeled("observer(admin-pub)", graph, nonAdminTierUpdate(graph, lastProcessed,
×
619
                GEN.OBSERVER_ROLE, PUBLISHER_IS_ADMIN));
620
        c.observer += runTierLabeled("observer(maint-pub)", graph, nonAdminTierUpdate(graph, lastProcessed,
×
621
                GEN.OBSERVER_ROLE, publisherIsTieredRole(GEN.MAINTAINER_ROLE)));
×
622
        c.observer += runTierLabeled("observer(member-pub)", graph, nonAdminTierUpdate(graph, lastProcessed,
×
623
                GEN.OBSERVER_ROLE, publisherIsTieredRole(GEN.MEMBER_ROLE)));
×
624
        c.observer += runTierLabeled("observer(self)", graph, nonAdminTierUpdate(graph, lastProcessed,
×
625
                GEN.OBSERVER_ROLE, PUBLISHER_IS_SELF));
626
        return c;
×
627
    }
628

629
    /**
630
     * Builds a publisher constraint requiring the publisher to be a validated holder
631
     * of the given tier's role (maintainer or member) in the target space.
632
     * Owns its own AccountState resolution so ?publisher is bound through the
633
     * targeted (pkh → agent) lookup rather than enumerated.
634
     */
635
    private static String publisherIsTieredRole(IRI tierClass) {
636
        // Re-keyed on the assignment's ref (alias → canonical already resolved by the
637
        // attachment tier). Relies on materialized non-admin RIs carrying their role
638
        // property (npa:regularProperty / npa:inverseProperty) — supplied by the
639
        // enrichment in nonAdminTierUpdate; without it this constraint matched nothing.
640
        return """
×
641
                ?acct a npa:AccountState ;
642
                      npa:pubkey ?pkh ;
643
                      npa:agent  ?publisher .
644
                ?tierRI a gen:RoleInstantiation ;
645
                        npa:forSpaceRef ?spaceRef ;
646
                        npa:forAgent ?publisher .
647
                ?rdT a npa:RoleDeclaration ;
648
                     npa:hasRoleType <%1$s> .
649
                { ?tierRI npa:regularProperty ?predT . ?rdT gen:hasRegularProperty ?predT . }
650
                UNION
651
                { ?tierRI npa:inverseProperty ?predT . ?rdT gen:hasInverseProperty ?predT . }
652
                """.formatted(tierClass);
×
653
    }
654

655
    /** Wraps {@link #runTierLoop} with tier-name context for logs/exceptions. */
656
    private int runTierLabeled(String tier, IRI graph, String sparqlUpdate) {
657
        try {
658
            return runTierLoop(graph, sparqlUpdate);
×
659
        } catch (RuntimeException ex) {
×
660
            logger.error("AuthorityResolver: tier={} failed with SPARQL UPDATE:\n{}\n", tier, sparqlUpdate, ex);
×
661
            throw ex;
×
662
        }
663
    }
664

665
    /**
666
     * Runs a single tier's INSERT to fixed point. Counts rows by probing
667
     * graph size before/after each INSERT; stops when the size doesn't change.
668
     *
669
     * @return total number of triples inserted by this tier across all iterations
670
     */
671
    int runTierLoop(IRI graph, String sparqlUpdate) {
672
        int total = 0;
×
673
        long before = graphSize(graph);
×
674
        while (true) {
675
            // Note: no explicit transaction wrapping here. In tests we observed that
676
            // HTTPRepository's RDF4J-transaction protocol silently no-op'd cross-graph
677
            // SPARQL UPDATEs with UNION sub-patterns inside conn.begin()/commit(),
678
            // while the same UPDATE POSTed directly to /statements applied correctly.
679
            // A bare prepareUpdate().execute() takes the direct /statements path and
680
            // runs the UPDATE atomically per SPARQL 1.1 semantics — which is all we
681
            // need; there's nothing else to commit atomically alongside the UPDATE.
682
            try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
683
                conn.prepareUpdate(QueryLanguage.SPARQL, sparqlUpdate).execute();
×
684
            }
685
            long after = graphSize(graph);
×
686
            long added = after - before;
×
687
            if (added <= 0) break;
×
688
            total += added;
×
689
            before = after;
×
690
        }
×
691
        return total;
×
692
    }
693

694
    private long graphSize(IRI graph) {
695
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
696
            return conn.size(graph);
×
697
        }
698
    }
699

700
    /**
701
     * Distinct-subject totals in the given space-state graph, broken down by
702
     * RoleInstantiation kind (admin-pinned vs not) and RoleAssignment.
703
     * Three SELECT-COUNT queries — cheap, called once per build/cycle for
704
     * the user-facing log line. Returns zeros on failure (logged) so a flaky
705
     * count read can't wedge the cycle.
706
     */
707
    TierSubjectTotals computeTierSubjectTotals(IRI graph) {
708
        long adminRIs       = countDistinctSubjects(graph, """
×
709
                ?ri a gen:RoleInstantiation ; npa:inverseProperty gen:hasAdmin .
710
                """, "ri");
711
        long attachmentRAs  = countDistinctSubjects(graph, """
×
712
                ?ra a gen:RoleAssignment .
713
                """, "ra");
714
        long nonAdminRIs    = countDistinctSubjects(graph, """
×
715
                ?ri a gen:RoleInstantiation .
716
                FILTER NOT EXISTS { ?ri npa:inverseProperty gen:hasAdmin }
717
                """, "ri");
718
        return new TierSubjectTotals(adminRIs, attachmentRAs, nonAdminRIs);
×
719
    }
720

721
    private long countDistinctSubjects(IRI graph, String wherePattern, String varName) {
722
        String query = String.format("""
×
723
                PREFIX npa: <%1$s>
724
                PREFIX gen: <%2$s>
725
                SELECT (COUNT(DISTINCT ?%3$s) AS ?n) WHERE {
726
                  GRAPH <%4$s> {
727
                    %5$s
728
                  }
729
                }
730
                """, NPA.NAMESPACE, GEN.NAMESPACE, varName, graph, wherePattern);
731
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO);
×
732
             TupleQueryResult r = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) {
×
733
            if (!r.hasNext()) return 0;
×
734
            return Long.parseLong(r.next().getBinding("n").getValue().stringValue());
×
735
        } catch (Exception ex) {
×
736
            logger.warn("AuthorityResolver: countDistinctSubjects on {} failed: {}",
×
737
                    graph, ex.toString());
×
738
            return 0;
×
739
        }
740
    }
741

742
    // ---------------- SPARQL templates ----------------
743

744
    /**
745
     * Reusable invalidation filter on a bound nanopub-IRI variable. Pass the bare
746
     * variable name (no leading {@code ?}); e.g. {@code invalidationFilter("np")}
747
     * produces an outer-scoped {@code FILTER NOT EXISTS { GRAPH npa:graph
748
     * { ?_inv_np npx:invalidates ?np . } }}.
749
     *
750
     * <p>Joins on the raw {@code npx:invalidates} triple in {@code npa:graph},
751
     * which {@link com.knowledgepixels.query.NanopubLoader} writes into the
752
     * spaces repo from two complementary directions, making the filter symmetric
753
     * in load order:
754
     * <ul>
755
     *   <li>At the invalidator's own load: the loader's space-repo trigger fires
756
     *       whenever the nanopub has either its own space-relevant extractions
757
     *       OR an {@code npx:invalidates}/{@code npx:retracts}/{@code npx:supersedes}
758
     *       triple, so a pure-retraction nanopub still lands its raw triple plus
759
     *       {@code npa:hasLoadNumber} stamp in {@code npa:graph}.</li>
760
     *   <li>At the invalidated target's load (when the invalidator landed
761
     *       earlier): {@code NanopubLoader.getInvalidatingStatements} reads the
762
     *       triple back from the meta repo and mirrors it into the target's own
763
     *       write to the spaces repo.</li>
764
     * </ul>
765
     *
766
     * <p>The earlier shape joined on a structured {@code npa:Invalidation} entry
767
     * in {@code npa:spacesGraph} that was only emitted on the invalidator's side
768
     * AND only when the invalidated target's meta had already loaded, leaving a
769
     * window where a superseding nanopub loaded before its target produced no
770
     * entry and the stale row was never filtered out (see also the matching
771
     * change in the tier-specific {@code *InvalidationCheckWhere}/{@code
772
     * *InvalidationDelete} templates below).
773
     *
774
     * <p>Important: this filter must be placed OUTSIDE the surrounding
775
     * {@code GRAPH npa:spacesGraph { ... }} block, not nested inside it. When
776
     * nested, RDF4J's planner couples the FILTER NOT EXISTS evaluation into the
777
     * join order (per-row scan multiplied by the candidate set), which we
778
     * measured turning a 39ms query into a 60s+ timeout on the live observer-tier
779
     * data. Outside the GRAPH block, the planner defers the filter until
780
     * {@code ?np}/{@code ?rdNp} are bound and does a targeted index lookup.
781
     *
782
     * <p>Variable names must match {@code [A-Za-z0-9_]+} per SPARQL grammar —
783
     * embedding a {@code ?} inside {@code ?_inv_?np} would yield a parse error.
784
     */
785
    private static String invalidationFilter(String bareVarName) {
786
        return "FILTER NOT EXISTS { GRAPH <" + NPA.GRAPH + "> {"
30✔
787
                + " ?_inv_" + bareVarName
788
                + " <" + NPX.INVALIDATES + "> ?" + bareVarName + " . "
789
                + samePublisherClause("_inv_" + bareVarName, bareVarName)
6✔
790
                + " } }";
791
    }
792

793
    /**
794
     * SPARQL triple pair (placed inside a {@code GRAPH npa:graph { ... }} block)
795
     * requiring the invalidating nanopub and its target to share a signing public
796
     * key — the self-retraction authority gate for issue #112. Without it, the
797
     * materializer honors {@code npx:invalidates}/{@code retracts}/{@code supersedes}
798
     * from <em>any</em> validly-signed nanopub, so any agent can erase another
799
     * space's materialized state (griefing/DoS of the view — fail-closed, no
800
     * privilege escalation, but real). Additions are already admin-gated; this is
801
     * the symmetric gate on removals.
802
     *
803
     * <p>Both {@code npa:hasValidSignatureForPublicKeyHash} triples live in
804
     * {@code npa:graph} of the spaces repo: the target via its own space-load, the
805
     * invalidator via the symmetric retractor propagation in
806
     * {@link com.knowledgepixels.query.NanopubLoader} (forward {@code
807
     * loadInvalidateStatements} + reverse {@code loadInvalidatorIntoSpacesRepo}),
808
     * so the join is populated regardless of load order.
809
     *
810
     * <p>"Same pubkey" is intentionally stricter than "same agent": a retraction
811
     * signed by a different key the author owns (key rotation) is not honored, and
812
     * cross-admin supersession is out of scope here (would need an admin-authority
813
     * arm). The pubkey-bridge variable is suffixed with {@code targetVar} so two
814
     * filters in one query (e.g. on {@code ?np} and {@code ?rdNp}) don't collide.
815
     *
816
     * @param invVar    invalidator nanopub variable name (no leading {@code ?})
817
     * @param targetVar invalidated-target nanopub variable name (no leading {@code ?})
818
     */
819
    private static String samePublisherClause(String invVar, String targetVar) {
820
        String pk = "?_invpk_" + targetVar;
9✔
821
        return "?" + invVar + " <" + NPA.HAS_VALID_SIGNATURE_FOR_PUBLIC_KEY_HASH + "> " + pk + " . "
30✔
822
                + "?" + targetVar + " <" + NPA.HAS_VALID_SIGNATURE_FOR_PUBLIC_KEY_HASH + "> " + pk + " .";
823
    }
824

825
    /**
826
     * Admin tier: seed from {@code npadef:...hasRootAdmin} (trusted by construction)
827
     * plus closed-over admin grants; insert any {@code gen:RoleInstantiation} with
828
     * {@code npa:inverseProperty gen:hasAdmin} whose publisher (resolved via mirrored
829
     * trust-approved AccountState) is already in the admin set.
830
     *
831
     * <p>The seed is gated by {@link #spaceRefAliveFilter} (not the per-nanopub
832
     * {@code invalidationFilter("defNp")}): the {@code hasRootAdmin} seed is anchored
833
     * to the root NPID, which is the immutable space-ref identity, so superseding the
834
     * root <em>nanopub</em> with a continuation revision must not strip the seed —
835
     * only retracting every definition of the ref removes it. See issue #110.
836
     */
837
    static String adminTierUpdate(IRI graph, long lastProcessed) {
838
        // Order tuned for RDF4J's evaluator:
839
        //   1. Anchor on the small (seed UNION closed-over) set to bind ?publisher
840
        //      and ?space cheaply.
841
        //   2. Resolve ?pkh from the mirrored AccountState row (?publisher bound).
842
        //   3. Probe instantiations using the now-bound (?space, ?pkh) — targeted
843
        //      lookup, not a full RoleInstantiation scan.
844
        //   4. Load-number filter on bound ?np.
845
        //   5. Dedup at the end.
846
        // Authority is keyed on the space *ref* (npa:forSpaceRef), not the bare Space
847
        // IRI: two refs that share an IRI but have different roots are independent
848
        // domains (see doc/design-spaceref-isolation.md). The instantiation evidence in
849
        // the extraction graph is IRI-keyed (a gen:hasAdmin nanopub names the bare IRI),
850
        // so we project it per-ref by joining each instantiation naming ?space to the
851
        // admin rows of every ref of ?space whose admin set contains the publisher. The
852
        // inserted subject is minted per (?ri, ?spaceRef) so one instantiation validating
853
        // into N refs yields N distinct rows. TRANSITIONAL-DUAL-EMIT (Phase 4: remove):
854
        // forSpace is still emitted alongside forSpaceRef so the not-yet-migrated
855
        // downstream tiers / pre-ref read queries keep functioning on a mixed-version
856
        // fleet; it is dropped once everything keys on forSpaceRef.
857
        return """
69✔
858
                PREFIX npa:  <%1$s>
859
                PREFIX gen:  <%2$s>
860
                INSERT { GRAPH <%3$s> {
861
                  ?sri a gen:RoleInstantiation ;
862
                       npa:forSpaceRef ?spaceRef ;
863
                       npa:forSpace ?space ;
864
                       npa:inverseProperty gen:hasAdmin ;
865
                       npa:forAgent ?agent ;
866
                       npa:viaNanopub ?np .
867
                } }
868
                WHERE {
869
                  # 1. Anchor: who is already an admin of which space ref?
870
                  {
871
                    # Seed branch: root-admin of a space ref that is still alive
872
                    # (has at least one non-invalidated definition). NOT filtered on
873
                    # ?def's own invalidation — superseding the root nanopub with a
874
                    # continuation revision must keep the seed; only a fully-retracted
875
                    # ref drops it (issue #110).
876
                    GRAPH <%4$s> {
877
                      ?def a npa:SpaceDefinition ;
878
                           npa:forSpaceRef  ?spaceRef ;
879
                           npa:hasRootAdmin ?publisher .
880
                      ?spaceRef npa:spaceIri ?space .
881
                    }
882
                    %7$s
883
                  }
884
                  UNION
885
                  {
886
                    # Closed-over branch: an existing admin of this ref. Recurse on the
887
                    # ref, then resolve its bare IRI to probe the IRI-keyed instantiation.
888
                    GRAPH <%3$s> {
889
                      ?prev a gen:RoleInstantiation ;
890
                            npa:forSpaceRef     ?spaceRef ;
891
                            npa:inverseProperty gen:hasAdmin ;
892
                            npa:forAgent        ?publisher .
893
                    }
894
                    GRAPH <%4$s> {
895
                      ?spaceRef npa:spaceIri ?space .
896
                    }
897
                  }
898
                  # 2. Mirror: resolve ?publisher → ?pkh via the trust-approved row.
899
                  GRAPH <%3$s> {
900
                    ?acct a npa:AccountState ;
901
                          npa:agent  ?publisher ;
902
                          npa:pubkey ?pkh .
903
                  }
904
                  # 3. Targeted instantiation lookup by space + pubkey (IRI-keyed).
905
                  GRAPH <%4$s> {
906
                    ?ri a gen:RoleInstantiation ;
907
                        npa:forSpace        ?space ;
908
                        npa:inverseProperty gen:hasAdmin ;
909
                        npa:forAgent        ?agent ;
910
                        npa:pubkeyHash      ?pkh ;
911
                        npa:viaNanopub      ?np .
912
                  }
913
                  # 3a. Mint the per-ref state subject: (?ri, ?spaceRef) → ?sri.
914
                  BIND(IRI(CONCAT(STR(?ri), "__", ENCODE_FOR_URI(STR(?spaceRef)))) AS ?sri)
915
                  %6$s
916
                  # 4. Load-number filter on bound ?np.
917
                  GRAPH <%8$s> {
918
                    ?np npa:hasLoadNumber ?ln .
919
                    FILTER (?ln > %5$d)
920
                  }
921
                  # 5. Dedup last — keyed on (ref, agent).
922
                  FILTER NOT EXISTS { GRAPH <%3$s> {
923
                    ?existing a gen:RoleInstantiation ;
924
                              npa:forSpaceRef ?spaceRef ;
925
                              npa:forAgent ?agent ;
926
                              npa:inverseProperty gen:hasAdmin .
927
                  } }
928
                }
929
                """.formatted(
3✔
930
                NPA.NAMESPACE,
931
                GEN.NAMESPACE,
932
                graph,
933
                SpacesVocab.SPACES_GRAPH,
934
                lastProcessed,
15✔
935
                invalidationFilter("np"),
12✔
936
                spaceRefAliveFilter(),
18✔
937
                NPA.GRAPH);
938
    }
939

940
    /**
941
     * Seed-survival filter for the admin tier (issue #110). The {@code hasRootAdmin}
942
     * seed is anchored to the root NPID, which is the immutable space-ref identity, so
943
     * it must survive supersession of the root <em>nanopub</em> by a continuation
944
     * revision (a later definition re-roots to the same ref via
945
     * {@code gen:hasRootDefinition} and so carries no {@code hasRootAdmin} of its own).
946
     * The previous {@code invalidationFilter("defNp")} dropped the seed the moment the
947
     * root revision was superseded, leaving the whole admin closure — and everything
948
     * cascading from it — unmaterialized for any space whose definition had ever been
949
     * updated.
950
     *
951
     * <p>Expressed positively: the seed survives iff the space ref still has at least
952
     * one non-invalidated {@link SpacesVocab#SPACE_DEFINITION}. A fully-retracted ref
953
     * (every definition invalidated) has no live definition, so the {@code FILTER
954
     * EXISTS} fails and the seed correctly disappears. Anchored on the already-bound
955
     * {@code ?spaceRef}, so it's a targeted lookup over that ref's (few) definitions.
956
     */
957
    private static String spaceRefAliveFilter() {
958
        return """
33✔
959
                FILTER EXISTS {
960
                  GRAPH <%1$s> {
961
                    ?liveDef a npa:SpaceDefinition ;
962
                             npa:forSpaceRef ?spaceRef ;
963
                             npa:viaNanopub  ?liveNp .
964
                  }
965
                  %2$s
966
                }
967
                """.formatted(SpacesVocab.SPACES_GRAPH, invalidationFilter("liveNp"));
9✔
968
    }
969

970
    /**
971
     * {@code gen:hasRole} attachment validation: an attachment is validated iff its
972
     * publisher is already a validated admin of the target space. Adds
973
     * {@code gen:RoleAssignment} rows to the space-state graph.
974
     */
975
    static String attachmentValidationUpdate(IRI graph, long lastProcessed) {
976
        // Ref-keyed (see doc/design-spaceref-isolation.md). The attachment names a bare
977
        // Space IRI; it is validated per-ref for every ref of that IRI whose admin set
978
        // contains the publisher (direct), or — when the named IRI is an owl:sameAs alias
979
        // — for the canonical ref it maps to (issue #113). ?targetRef is the ref the
980
        // RoleAssignment attaches to; the inserted subject is minted per (?ra, ?targetRef)
981
        // so one attachment validating into N refs yields N distinct rows.
982
        // TRANSITIONAL-DUAL-EMIT (Phase 4: remove): forSpace (the attached IRI, possibly an
983
        // alias) is kept so the non-admin tier can probe the IRI-keyed instantiations
984
        // naming it, and so pre-ref read queries keep functioning on a mixed-version fleet.
985
        return """
69✔
986
                PREFIX npa:  <%1$s>
987
                PREFIX gen:  <%2$s>
988
                INSERT { GRAPH <%3$s> {
989
                  ?ra2 a gen:RoleAssignment ;
990
                       npa:forSpaceRef ?targetRef ;
991
                       npa:forSpace ?space ;
992
                       gen:hasRole  ?role ;
993
                       npa:viaNanopub ?np .
994
                } }
995
                WHERE {
996
                  GRAPH <%4$s> {
997
                    ?ra a gen:RoleAssignment ;
998
                        npa:forSpace ?space ;
999
                        gen:hasRole  ?role ;
1000
                        npa:pubkeyHash ?pkh ;
1001
                        npa:viaNanopub ?np .
1002
                  }
1003
                  GRAPH <%7$s> {
1004
                    ?np npa:hasLoadNumber ?ln .
1005
                    FILTER (?ln > %5$d)
1006
                  }
1007
                  GRAPH <%3$s> {
1008
                    ?acct a npa:AccountState ;
1009
                          npa:agent  ?publisher ;
1010
                          npa:pubkey ?pkh .
1011
                  }
1012
                  # Per-ref admin gate. ?targetRef = a ref of ?space the publisher admins
1013
                  # (direct), or the canonical ref ?space is an owl:sameAs alias of.
1014
                  {
1015
                    GRAPH <%4$s> { ?targetRef npa:spaceIri ?space . }
1016
                    GRAPH <%3$s> {
1017
                      ?adminRI a gen:RoleInstantiation ;
1018
                               npa:forSpaceRef ?targetRef ;
1019
                               npa:inverseProperty gen:hasAdmin ;
1020
                               npa:forAgent ?publisher .
1021
                    }
1022
                  }
1023
                  UNION
1024
                  {
1025
                    GRAPH <%3$s> {
1026
                      ?space npa:sameAsSpace ?targetRef .
1027
                      ?adminRI a gen:RoleInstantiation ;
1028
                               npa:forSpaceRef ?targetRef ;
1029
                               npa:inverseProperty gen:hasAdmin ;
1030
                               npa:forAgent ?publisher .
1031
                    }
1032
                  }
1033
                  BIND(IRI(CONCAT(STR(?ra), "__", ENCODE_FOR_URI(STR(?targetRef)))) AS ?ra2)
1034
                  %6$s
1035
                  FILTER NOT EXISTS { GRAPH <%3$s> {
1036
                    ?existing a gen:RoleAssignment ;
1037
                              npa:forSpaceRef ?targetRef ;
1038
                              gen:hasRole  ?role .
1039
                  } }
1040
                }
1041
                """.formatted(
3✔
1042
                NPA.NAMESPACE,
1043
                GEN.NAMESPACE,
1044
                graph,
1045
                SpacesVocab.SPACES_GRAPH,
1046
                lastProcessed,
15✔
1047
                invalidationFilter("np"),
18✔
1048
                NPA.GRAPH);
1049
    }
1050

1051
    /**
1052
     * Preset-bundled role materialization (Nanodash issue #302). For each active,
1053
     * admin-authored {@code gen:PresetAssignment} targeting a {@code gen:Space}, inserts
1054
     * one {@code gen:RoleAssignment} per role the preset bundles — exactly as if
1055
     * {@code <space> gen:hasRole <role>} had been published by the assignment's publisher.
1056
     * The materialized rows carry {@code npa:derivedFromPreset} (the assignment nanopub)
1057
     * so the deactivation delete and read-side marking can scope to them without touching
1058
     * directly-published attachments. See {@code doc/design-preset-role-materialization.md}.
1059
     *
1060
     * <p>Activation is resolved by an <b>authorization-scoped latest-wins</b> over the
1061
     * {@code (preset, resource)} pair, NOT {@code npx:invalidates} (§3): the candidate set
1062
     * for the {@code MAX(dct:created)} comparison is restricted to assignments whose
1063
     * publisher is also a validated admin of the target ref, so an unauthorized key's newer
1064
     * assignment cannot shadow an admin's activation (the #113-class anti-hijack rule).
1065
     */
1066
    static String presetAttachmentValidationUpdate(IRI graph, long lastProcessed) {
1067
        // Ref-keyed like attachmentValidationUpdate: the assignment names a bare resource
1068
        // IRI; it is validated per-ref for every Space ref of that IRI whose admin set
1069
        // contains the publisher. The inserted subject is minted per (assignment, ref, role)
1070
        // — one assignment fans out to N roles and N refs. Non-Space targets resolve no
1071
        // ?targetRef and so insert nothing (correct no-op; maintained-resource / individual
1072
        // targets are future work, see design doc §2). TRANSITIONAL-DUAL-EMIT (Phase 4:
1073
        // remove): forSpace kept alongside forSpaceRef so the non-admin tiers can probe the
1074
        // IRI-keyed instantiations and pre-ref read queries keep functioning.
1075
        return """
69✔
1076
                PREFIX npa:  <%1$s>
1077
                PREFIX gen:  <%2$s>
1078
                INSERT { GRAPH <%3$s> {
1079
                  ?ra2 a gen:RoleAssignment ;
1080
                       npa:forSpaceRef ?targetRef ;
1081
                       npa:forSpace    ?resource ;
1082
                       gen:hasRole     ?role ;
1083
                       npa:viaNanopub  ?assignNp ;
1084
                       npa:derivedFromPreset ?assignNp .
1085
                } }
1086
                WHERE {
1087
                  # 1. Anchor: active preset assignments in the extraction graph.
1088
                  GRAPH <%4$s> {
1089
                    ?pa a npa:PresetAssignment ;
1090
                        npa:ofPreset    ?preset ;
1091
                        npa:forResource ?resource ;
1092
                        npa:isActivated true ;
1093
                        npa:pubkeyHash  ?pkh ;
1094
                        npa:viaNanopub  ?assignNp ;
1095
                        <http://purl.org/dc/terms/created> ?created .
1096
                  }
1097
                  # 2. Load-number filter on the assignment nanopub.
1098
                  GRAPH <%7$s> {
1099
                    ?assignNp npa:hasLoadNumber ?ln .
1100
                    FILTER (?ln > %5$d)
1101
                  }
1102
                  # 3. Resolve publisher pkh -> agent via the mirrored trust-approved row.
1103
                  GRAPH <%3$s> {
1104
                    ?acct a npa:AccountState ;
1105
                          npa:agent  ?publisher ;
1106
                          npa:pubkey ?pkh .
1107
                  }
1108
                  # 4. Target must be a Space ref the publisher admins — direct, or the
1109
                  #    canonical ref ?resource is an owl:sameAs alias of (issue #113 parity
1110
                  #    with attachmentValidationUpdate, so a preset assigned against an alias
1111
                  #    IRI still materializes against the canonical ref).
1112
                  {
1113
                    GRAPH <%4$s> { ?targetRef npa:spaceIri ?resource . }
1114
                    GRAPH <%3$s> {
1115
                      ?adminRI a gen:RoleInstantiation ;
1116
                               npa:forSpaceRef ?targetRef ;
1117
                               npa:inverseProperty gen:hasAdmin ;
1118
                               npa:forAgent ?publisher .
1119
                    }
1120
                  }
1121
                  UNION
1122
                  {
1123
                    GRAPH <%3$s> {
1124
                      ?resource npa:sameAsSpace ?targetRef .
1125
                      ?adminRI a gen:RoleInstantiation ;
1126
                               npa:forSpaceRef ?targetRef ;
1127
                               npa:inverseProperty gen:hasAdmin ;
1128
                               npa:forAgent ?publisher .
1129
                    }
1130
                  }
1131
                  # 5. Resolve the assignment's referenced preset IRI (node or kind) to its
1132
                  #    canonical kind, mirroring how Nanodash views key on dct:isVersionOf
1133
                  #    (ViewDisplay.getViewKindIri). Every declaration carries npa:ofPreset for
1134
                  #    both its node IRI and kind, so either reference maps to the same ?kind.
1135
                  GRAPH <%4$s> {
1136
                    ?pdMap a npa:PresetDeclaration ;
1137
                           npa:ofPreset   ?preset ;
1138
                           npa:presetKind ?kind .
1139
                  }
1140
                  # 5a. Roles come from the LATEST live declaration of that kind, restricted to
1141
                  #     Space-targeted presets — so a superseded preset version's roles never leak
1142
                  #     (the per-view-kind latest-wins, ported to materialization).
1143
                  GRAPH <%4$s> {
1144
                    ?pd a npa:PresetDeclaration ;
1145
                        npa:presetKind           ?kind ;
1146
                        npa:presetRole           ?role ;
1147
                        npa:appliesToInstancesOf gen:Space ;
1148
                        npa:viaNanopub           ?pdNp ;
1149
                        <http://purl.org/dc/terms/created> ?pdCreated .
1150
                  }
1151
                  # 5b. Latest-declaration-per-kind: reject if a newer LIVE declaration of the
1152
                  #     same kind exists (tiebreak on subject IRI for equal timestamps).
1153
                  FILTER NOT EXISTS {
1154
                    GRAPH <%4$s> {
1155
                      ?pdNewer a npa:PresetDeclaration ;
1156
                               npa:presetKind ?kind ;
1157
                               npa:viaNanopub ?pdNpNewer ;
1158
                               <http://purl.org/dc/terms/created> ?pdCreatedNewer .
1159
                      FILTER (?pdCreatedNewer > ?pdCreated
1160
                              || (?pdCreatedNewer = ?pdCreated && STR(?pdNewer) > STR(?pd)))
1161
                    }
1162
                    %8$s
1163
                  }
1164
                  # 5c. The chosen declaration must itself be live (not superseded/retracted).
1165
                  %9$s
1166
                  # 6. Mint the per (assignment, ref, role) subject.
1167
                  BIND(IRI(CONCAT(STR(?pa), "__", ENCODE_FOR_URI(STR(?targetRef)),
1168
                                  "__", ENCODE_FOR_URI(STR(?role)))) AS ?ra2)
1169
                  # 7. Authorization-scoped latest-wins (anti-hijack, design doc §3): reject
1170
                  #    if a newer same-(preset,resource) assignment exists whose publisher is
1171
                  #    ALSO a validated admin of ?targetRef. Filtering the shadowing candidate
1172
                  #    to admin-authored rows BEFORE taking the latest is what stops an
1173
                  #    unauthorized key from suppressing an admin's activation. Placed after
1174
                  #    the main vars are bound so the planner defers it (RDF4J quirk).
1175
                  FILTER NOT EXISTS {
1176
                    GRAPH <%4$s> {
1177
                      ?paNewer a npa:PresetAssignment ;
1178
                               npa:ofPreset    ?preset ;
1179
                               npa:forResource ?resource ;
1180
                               npa:pubkeyHash  ?pkhNewer ;
1181
                               <http://purl.org/dc/terms/created> ?createdNewer .
1182
                      FILTER (?createdNewer > ?created
1183
                              || (?createdNewer = ?created && STR(?paNewer) > STR(?pa)))
1184
                    }
1185
                    GRAPH <%3$s> {
1186
                      ?acctNewer a npa:AccountState ;
1187
                                 npa:agent  ?publisherNewer ;
1188
                                 npa:pubkey ?pkhNewer .
1189
                      ?adminRINewer a gen:RoleInstantiation ;
1190
                                    npa:forSpaceRef ?targetRef ;
1191
                                    npa:inverseProperty gen:hasAdmin ;
1192
                                    npa:forAgent ?publisherNewer .
1193
                    }
1194
                  }
1195
                  # 8. Defensive: drop if the assignment nanopub itself was hard-retracted.
1196
                  %6$s
1197
                  # 9. Dedup last — keyed on (ref, role).
1198
                  FILTER NOT EXISTS { GRAPH <%3$s> {
1199
                    ?existing a gen:RoleAssignment ;
1200
                              npa:forSpaceRef ?targetRef ;
1201
                              gen:hasRole ?role .
1202
                  } }
1203
                }
1204
                """.formatted(
3✔
1205
                NPA.NAMESPACE,
1206
                GEN.NAMESPACE,
1207
                graph,
1208
                SpacesVocab.SPACES_GRAPH,
1209
                lastProcessed,
15✔
1210
                invalidationFilter("assignNp"),
27✔
1211
                NPA.GRAPH,
1212
                invalidationFilter("pdNpNewer"),
15✔
1213
                invalidationFilter("pdNp"));
6✔
1214
    }
1215

1216
    /**
1217
     * Stamps a ref-scoped, admin-validated mirror of each {@code npa:PresetAssignment}
1218
     * into the state graph (issue #122). The publisher-agnostic extraction row
1219
     * ({@link SpacesExtractor#extractPresetAssignment}) is keyed only by
1220
     * {@code npa:forResource}, so a consumer listing a space's preset assignments by IRI
1221
     * sees the union across <em>all</em> refs claiming that IRI. This stamp adds
1222
     * {@code npa:forSpaceRef ?targetRef} so the "Assigned presets" listing is no longer
1223
     * merged across refs of the same IRI — the one remaining About-tab listing that still
1224
     * merged across refs (every other ref-scoped listing already has a {@code forSpaceRef}
1225
     * companion).
1226
     *
1227
     * <p>Faithful per-assignment mirror — deliberately <em>not</em> role-gated and
1228
     * <em>not</em> latest-wins-resolved, unlike {@link #presetAttachmentValidationUpdate}:
1229
     * <ul>
1230
     *   <li>No {@code npa:PresetDeclaration}/role join, so a preset that bundles only
1231
     *       <em>views</em> (no roles) is still listed.</li>
1232
     *   <li>Emits active <em>and</em> deactivated rows (carries {@code npa:isActivated})
1233
     *       so the listing can show state; a deactivation is just a newer admin-authored
1234
     *       row, so no {@code dct:created}-driven removal is needed here (contrast §4.4).</li>
1235
     *   <li>Latest-wins is deferred to the consumer query, which ranges only over these
1236
     *       admin-authored rows — so it is authorization-scoped for free (design §3): a
1237
     *       non-admin of the ref can never get a row stamped, so it cannot enter the
1238
     *       latest-wins race.</li>
1239
     * </ul>
1240
     *
1241
     * <p>Display-only leaf: nothing downstream derives from these rows (contrast the
1242
     * preset-derived {@code gen:RoleAssignment}), so the caller must <em>not</em> feed this
1243
     * tier's count into {@code structuralAdds}. The {@code npa:forSpaceRef} predicate also
1244
     * distinguishes a stamped row from the IRI-keyed extraction row (which never carries it),
1245
     * so {@link #presetAssignmentRefInvalidationDelete} can target exactly these rows.
1246
     * Reuses steps 1–4 of {@link #presetAttachmentValidationUpdate}; see
1247
     * doc/design-preset-role-materialization.md §3 and issue #122.
1248
     */
1249
    static String presetAssignmentRefStampUpdate(IRI graph, long lastProcessed) {
1250
        return """
69✔
1251
                PREFIX npa:  <%1$s>
1252
                PREFIX gen:  <%2$s>
1253
                INSERT { GRAPH <%3$s> {
1254
                  ?paRef a npa:PresetAssignment ;
1255
                         npa:ofPreset    ?preset ;
1256
                         npa:forResource ?resource ;
1257
                         npa:forSpaceRef ?targetRef ;
1258
                         npa:isActivated ?activated ;
1259
                         npa:viaNanopub  ?assignNp ;
1260
                         <http://purl.org/dc/terms/created> ?created .
1261
                } }
1262
                WHERE {
1263
                  # 1. Anchor: every assignment row (active or not) in the extraction graph.
1264
                  GRAPH <%4$s> {
1265
                    ?pa a npa:PresetAssignment ;
1266
                        npa:ofPreset    ?preset ;
1267
                        npa:forResource ?resource ;
1268
                        npa:isActivated ?activated ;
1269
                        npa:pubkeyHash  ?pkh ;
1270
                        npa:viaNanopub  ?assignNp ;
1271
                        <http://purl.org/dc/terms/created> ?created .
1272
                  }
1273
                  # 2. Load-number filter on the assignment nanopub (delta window).
1274
                  GRAPH <%6$s> {
1275
                    ?assignNp npa:hasLoadNumber ?ln .
1276
                    FILTER (?ln > %5$d)
1277
                  }
1278
                  # 3. Resolve publisher pkh -> agent via the mirrored trust-approved row.
1279
                  GRAPH <%3$s> {
1280
                    ?acct a npa:AccountState ;
1281
                          npa:agent  ?publisher ;
1282
                          npa:pubkey ?pkh .
1283
                  }
1284
                  # 4. Target must be a Space ref the publisher admins. ?targetRef = that ref;
1285
                  #    fan-out to N refs the publisher admins (per-ref isolation, consistent
1286
                  #    with the role materializer and design-spaceref-isolation.md). Direct,
1287
                  #    or the canonical ref ?resource is an owl:sameAs alias of (issue #113),
1288
                  #    so an assignment naming an alias is still listed under the canonical ref.
1289
                  {
1290
                    GRAPH <%4$s> { ?targetRef npa:spaceIri ?resource . }
1291
                    GRAPH <%3$s> {
1292
                      ?adminRI a gen:RoleInstantiation ;
1293
                               npa:forSpaceRef ?targetRef ;
1294
                               npa:inverseProperty gen:hasAdmin ;
1295
                               npa:forAgent ?publisher .
1296
                    }
1297
                  }
1298
                  UNION
1299
                  {
1300
                    GRAPH <%3$s> {
1301
                      ?resource npa:sameAsSpace ?targetRef .
1302
                      ?adminRI a gen:RoleInstantiation ;
1303
                               npa:forSpaceRef ?targetRef ;
1304
                               npa:inverseProperty gen:hasAdmin ;
1305
                               npa:forAgent ?publisher .
1306
                    }
1307
                  }
1308
                  # 5. Defensive: drop if the assignment nanopub itself was hard-retracted.
1309
                  %7$s
1310
                  # 6. Mint per (assignment, ref); dedup on the bound subject. No latest-wins
1311
                  #    here — a deactivation is just a newer admin-authored row, and the
1312
                  #    consumer resolves latest dct:created per (preset,resource) over these
1313
                  #    admin-authored rows (so the resolution is authorization-scoped).
1314
                  BIND(IRI(CONCAT(STR(?pa), "__", ENCODE_FOR_URI(STR(?targetRef)))) AS ?paRef)
1315
                  FILTER NOT EXISTS { GRAPH <%3$s> { ?paRef a npa:PresetAssignment . } }
1316
                }
1317
                """.formatted(
3✔
1318
                NPA.NAMESPACE,
1319
                GEN.NAMESPACE,
1320
                graph,
1321
                SpacesVocab.SPACES_GRAPH,
1322
                lastProcessed,
27✔
1323
                NPA.GRAPH,
1324
                invalidationFilter("assignNp"));
6✔
1325
    }
1326

1327
    /**
1328
     * Non-admin tier publisher constraints (inserted as a SPARQL sub-pattern).
1329
     * Each constraint owns the AccountState (pkh → agent) lookup so the join
1330
     * variable is bound through a targeted pattern. The observer-self variant
1331
     * binds {@code npa:agent ?agent} directly — no separate {@code ?publisher}
1332
     * variable, no post-join equality filter — which lets the planner anchor
1333
     * the AccountState lookup on the already-bound {@code ?agent} instead of
1334
     * enumerating all approved publishers and filtering at the end.
1335
     */
1336
    static final String PUBLISHER_IS_ADMIN = """
1337
            ?acct a npa:AccountState ;
1338
                  npa:pubkey ?pkh ;
1339
                  npa:agent  ?publisher .
1340
            # Admin of the assignment's ref. The ref already resolves alias →
1341
            # canonical (the attachment tier bound ?spaceRef through the owl:sameAs
1342
            # alias edge for aliased IRIs, issue #113), so no alias arm is needed here.
1343
            ?adminRI a gen:RoleInstantiation ;
1344
                     npa:forSpaceRef ?spaceRef ;
1345
                     npa:inverseProperty gen:hasAdmin ;
1346
                     npa:forAgent ?publisher .
1347
            """;
1348

1349
    /** Observer self-evidence: the assignee's own pubkey signed the instantiation. */
1350
    static final String PUBLISHER_IS_SELF = """
1351
            ?acct a npa:AccountState ;
1352
                  npa:pubkey ?pkh ;
1353
                  npa:agent  ?agent .
1354
            """;
1355

1356
    /**
1357
     * Maintainer / Member / Observer tier INSERT. Same shape: find an instantiation
1358
     * whose predicate matches a RoleDeclaration of the given tier attached to the
1359
     * target space, and whose publisher passes the tier-specific constraint.
1360
     */
1361
    static String nonAdminTierUpdate(IRI graph, long lastProcessed,
1362
                                     IRI tierClass, String publisherConstraint) {
1363
        // Order tuned for RDF4J's evaluator (which executes BGPs roughly in order).
1364
        // The crucial choice is the *anchor*: instantiation-first plans send the
1365
        // planner exploring the full ~thousands of candidate RIs and only filter
1366
        // by tier at the very end. Attachment-first anchors on the small set of
1367
        // gen:RoleAssignment rows already validated in this space-state graph
1368
        // (~hundreds, often zero) and walks outward by bound (?role, ?space).
1369
        //
1370
        //   1. Anchor on RoleAssignments in this space-state graph (small).
1371
        //   1a. Resolve the IRIs that denote the assignment's ref — its canonical
1372
        //      IRI plus any validated owl:sameAs aliases — so an instantiation that
1373
        //      names an alias of the space still matches (issue #113). Bound here so
1374
        //      the instantiation lookup below stays anchored by ?instSpace.
1375
        //   2. Match the tier-pinned RoleDeclaration by ?role.
1376
        //   3. Pair role-decl direction to instantiation direction in one UNION
1377
        //      so only (reg, reg)/(inv, inv) combos are explored.
1378
        //   4. Targeted instantiation lookup — (?instSpace, ?pred) are bound.
1379
        //   5. Publisher constraint (incl. AccountState resolution).
1380
        //   6. Load-number filter on bound ?np.
1381
        //   7. Dedup at the end.
1382
        return """
69✔
1383
                PREFIX npa:  <%1$s>
1384
                PREFIX gen:  <%2$s>
1385
                INSERT { GRAPH <%3$s> {
1386
                  ?ri2 a gen:RoleInstantiation ;
1387
                       npa:forSpaceRef ?spaceRef ;
1388
                       # TRANSITIONAL-DUAL-EMIT (Phase 4: remove): forSpace alongside
1389
                       # forSpaceRef so pre-ref read queries (e.g. get-space-members) keep
1390
                       # functioning on a mixed-version fleet; downstream tiers key on the ref.
1391
                       npa:forSpace ?space ;
1392
                       npa:forAgent ?agent ;
1393
                       ?dirPred ?pred ;
1394
                       # Persist the tier and role IRI that are already bound at this point —
1395
                       # the loop's tierClass arg (%7$s) and the anchoring attachment's ?role
1396
                       # (step 1) — so ref-scoped consumers key on identity rather than
1397
                       # re-deriving the tier from the bare predicate against GLOBAL
1398
                       # RoleDeclarations. The bare-predicate re-derivation bleeds tiers
1399
                       # across spaces that declare the same predicate at different tiers
1400
                       # (issue #125): consumers should match ?ri2 npa:hasRoleType <tier>
1401
                       # / gen:hasRole ?role, exactly as the *-roles-ref queries do.
1402
                       npa:hasRoleType <%7$s> ;
1403
                       gen:hasRole ?role ;
1404
                       npa:viaNanopub ?np .
1405
                } }
1406
                WHERE {
1407
                  # 1. Anchor: validated attachments in this space-state graph (ref-keyed).
1408
                  GRAPH <%3$s> {
1409
                    ?ra a gen:RoleAssignment ;
1410
                        gen:hasRole     ?role ;
1411
                        npa:forSpaceRef ?spaceRef ;
1412
                        npa:forSpace    ?space .
1413
                  }
1414
                  # 1a. The IRIs that denote this ref: its canonical IRI, plus any validated
1415
                  #     owl:sameAs aliases of it (issue #113) — so an instantiation naming an
1416
                  #     alias of the space still materializes here. Bound BEFORE the
1417
                  #     instantiation BGP so that lookup stays anchored by ?instSpace (planner
1418
                  #     note above); ?spaceRef is already bound, so each arm is a targeted
1419
                  #     lookup yielding a tiny IRI set. The alias arm only follows admin-
1420
                  #     validated npa:sameAsSpace edges, so it grants no authority the admin
1421
                  #     tier would not (anti-hijack is enforced upstream, not relaxed here).
1422
                  {
1423
                    GRAPH <%4$s> { ?spaceRef npa:spaceIri ?instSpace . }
1424
                  }
1425
                  UNION
1426
                  {
1427
                    GRAPH <%3$s> { ?instSpace npa:sameAsSpace ?spaceRef . }
1428
                  }
1429
                  # 2. Tier-pinned RoleDeclaration (?role bound from the attachment). Its
1430
                  #    nanopub's invalidation is intentionally NOT consulted (see step 7), so
1431
                  #    no ?rdNp binding is needed.
1432
                  GRAPH <%4$s> {
1433
                    ?rd a npa:RoleDeclaration ;
1434
                        npa:hasRoleType <%7$s> ;
1435
                        npa:role        ?role .
1436
                    # 3. Pair role-decl direction to the instantiation in one UNION so only
1437
                    #    matching combos are explored, binding (?instSpace, ?agent) per arm.
1438
                    #    ?dirPred carries the resolved direction so the materialized row
1439
                    #    records the role property (read by get-space-members and
1440
                    #    publisherIsTieredRole) — identical shape whichever arm matched.
1441
                    #
1442
                    #    The first two arms handle instantiations the extractor already
1443
                    #    classified (npa:regularProperty / npa:inverseProperty). The last two
1444
                    #    resolve a custom predicate the extractor left neutral (npa:rolePredicate
1445
                    #    with raw npa:bindingSubject / npa:bindingObject): the role declaration
1446
                    #    supplies the direction, which fixes which raw endpoint is the space vs
1447
                    #    the agent. INVERSE = <space> pred <agent>; REGULAR = <agent> pred <space>.
1448
                    {
1449
                      ?rd gen:hasRegularProperty ?pred .
1450
                      ?ri npa:regularProperty ?pred ;
1451
                          npa:forSpace ?instSpace ;
1452
                          npa:forAgent ?agent .
1453
                      BIND(npa:regularProperty AS ?dirPred)
1454
                    }
1455
                    UNION
1456
                    {
1457
                      ?rd gen:hasInverseProperty ?pred .
1458
                      ?ri npa:inverseProperty ?pred ;
1459
                          npa:forSpace ?instSpace ;
1460
                          npa:forAgent ?agent .
1461
                      BIND(npa:inverseProperty AS ?dirPred)
1462
                    }
1463
                    UNION
1464
                    {
1465
                      ?rd gen:hasInverseProperty ?pred .
1466
                      ?ri npa:rolePredicate   ?pred ;
1467
                          npa:bindingSubject  ?instSpace ;
1468
                          npa:bindingObject   ?agent .
1469
                      BIND(npa:inverseProperty AS ?dirPred)
1470
                    }
1471
                    UNION
1472
                    {
1473
                      ?rd gen:hasRegularProperty ?pred .
1474
                      ?ri npa:rolePredicate   ?pred ;
1475
                          npa:bindingObject   ?instSpace ;
1476
                          npa:bindingSubject  ?agent .
1477
                      BIND(npa:regularProperty AS ?dirPred)
1478
                    }
1479
                    # 4. Common instantiation columns. ?instSpace was resolved to this ref
1480
                    #    above (canonical or owl:sameAs alias), so an alias-named instantiation
1481
                    #    joins the same ?spaceRef as a canonical one. The materialized row still
1482
                    #    carries npa:forSpace ?space (the attachment's IRI) for the transitional
1483
                    #    dual-emit, so pre-ref reads see the member under the space's primary IRI.
1484
                    ?ri a gen:RoleInstantiation ;
1485
                        npa:pubkeyHash ?pkh ;
1486
                        npa:viaNanopub ?np .
1487
                  }
1488
                  # 5. Publisher constraint (incl. AccountState resolution).
1489
                  GRAPH <%3$s> {
1490
                    %8$s
1491
                  }
1492
                  # 5a. Mint the per-ref state subject: (?ri, ?spaceRef) → ?ri2.
1493
                  BIND(IRI(CONCAT(STR(?ri), "__", ENCODE_FOR_URI(STR(?spaceRef)))) AS ?ri2)
1494
                  # 6. Load-number filter on bound ?np.
1495
                  GRAPH <%9$s> {
1496
                    ?np npa:hasLoadNumber ?ln .
1497
                    FILTER (?ln > %5$d)
1498
                  }
1499
                  # 7. Instantiation invalidation filter — outside the GRAPH block so the
1500
                  #    planner defers it until ?np is bound. Role-DECLARATION invalidation is
1501
                  #    deliberately NOT consulted: the tier already anchors on the admin-
1502
                  #    validated attachment (?ra), which is removed when an admin retracts it,
1503
                  #    so admin control is fully enforced there. Letting the declaration's
1504
                  #    author (usually not the space admin) supersede/retract their declaration
1505
                  #    strip a space's members is the same cross-author-strip anti-pattern as
1506
                  #    issue #112. Role IRIs are version-pinned, so the attached definition is
1507
                  #    immutable regardless of the declaration nanopub's later lifecycle.
1508
                  %6$s
1509
                  # 8. Dedup last — keyed on (ref, agent, nanopub).
1510
                  FILTER NOT EXISTS { GRAPH <%3$s> {
1511
                    ?existing a gen:RoleInstantiation ;
1512
                              npa:forSpaceRef ?spaceRef ;
1513
                              npa:forAgent ?agent ;
1514
                              npa:viaNanopub ?np .
1515
                  } }
1516
                }
1517
                """.formatted(
3✔
1518
                NPA.NAMESPACE,
1519
                GEN.NAMESPACE,
1520
                graph,
1521
                SpacesVocab.SPACES_GRAPH,
1522
                lastProcessed,
15✔
1523
                invalidationFilter("np"),
42✔
1524
                tierClass,
1525
                publisherConstraint,
1526
                NPA.GRAPH);
1527
    }
1528

1529
    /**
1530
     * Sub-space admit pass. Copies validated {@code npa:SubSpaceDeclaration}
1531
     * extraction rows into the space-state graph (preserving the {@code npasub:}
1532
     * subject) and emits convenience {@code <child> npa:isSubSpaceOf <parent>} and
1533
     * {@code <parent> npa:hasSubSpace <child>} direct triples. Two satisfaction
1534
     * modes joined by UNION:
1535
     * <ul>
1536
     *   <li>Mode A — the declaration's publisher is a validated admin of both the
1537
     *       child and the parent space.</li>
1538
     *   <li>Mode B — a different non-invalidated declaration for the same
1539
     *       {@code (child, parent)} pair exists, and the two publishers between
1540
     *       them cover both admin sides (i.e. one of them is admin of the child,
1541
     *       one of them is admin of the parent — possibly the same one twice if
1542
     *       both happen to be admin of both).</li>
1543
     * </ul>
1544
     *
1545
     * <p>Mode-B late-arrival: when only the partner declaration is new in this
1546
     * cycle (the primary is older than {@code lastProcessed}), the load-number
1547
     * filter on {@code ?np} excludes the candidate. The late-arrival sweep
1548
     * ({@link #runDownstreamWithoutLoadFilter}) re-runs this pass without the
1549
     * load filter and catches it.
1550
     */
1551
    static String subSpaceAdmitUpdate(IRI graph, long lastProcessed) {
1552
        return """
69✔
1553
                PREFIX npa: <%1$s>
1554
                PREFIX gen: <%2$s>
1555
                INSERT { GRAPH <%3$s> {
1556
                  ?d a npa:SubSpaceDeclaration ;
1557
                     npa:childSpace  ?child ;
1558
                     npa:parentSpace ?parent ;
1559
                     npa:viaNanopub  ?np .
1560
                  ?childRef  npa:isSubSpaceOf ?parentRef .
1561
                  ?parentRef npa:hasSubSpace  ?childRef  .
1562
                  # TRANSITIONAL-DUAL-EMIT (Phase 1.5; remove in Phase 4): IRI-valued
1563
                  # sub-space edge alongside the ref-to-ref one, so pre-ref published
1564
                  # queries that key on the bare Space IRI keep binding on a mixed-version
1565
                  # fleet. See doc/report-2026-06-12-mixed-fleet-spaceref-breakage.md.
1566
                  ?child  npa:isSubSpaceOf ?parent .
1567
                  ?parent npa:hasSubSpace  ?child  .
1568
                } }
1569
                WHERE {
1570
                  # 1. Anchor: candidate declarations from the extraction graph.
1571
                  GRAPH <%4$s> {
1572
                    ?d a npa:SubSpaceDeclaration ;
1573
                       npa:childSpace  ?child ;
1574
                       npa:parentSpace ?parent ;
1575
                       npa:pubkeyHash  ?pkh ;
1576
                       npa:viaNanopub  ?np .
1577
                  }
1578
                  # 2. Mirror: resolve ?pkh → ?publisher via the trust-approved row.
1579
                  GRAPH <%3$s> {
1580
                    ?acct a npa:AccountState ;
1581
                          npa:pubkey ?pkh ;
1582
                          npa:agent  ?publisher .
1583
                  }
1584
                  # 3. Authority gate, ref-keyed. The edge is emitted ref-to-ref between
1585
                  #    the child ref and parent ref the authorizing admin governs; the
1586
                  #    admin rows' dual-emitted npa:forSpace binds the refs to the child /
1587
                  #    parent IRIs (cross-product when an IRI has several governed refs).
1588
                  {
1589
                    # Mode A — publisher is admin of BOTH a child ref and a parent ref.
1590
                    GRAPH <%3$s> {
1591
                      ?riC a gen:RoleInstantiation ;
1592
                           npa:inverseProperty gen:hasAdmin ;
1593
                           npa:forSpace ?child ;
1594
                           npa:forSpaceRef ?childRef ;
1595
                           npa:forAgent ?publisher .
1596
                      ?riP a gen:RoleInstantiation ;
1597
                           npa:inverseProperty gen:hasAdmin ;
1598
                           npa:forSpace ?parent ;
1599
                           npa:forSpaceRef ?parentRef ;
1600
                           npa:forAgent ?publisher .
1601
                    }
1602
                  }
1603
                  UNION
1604
                  {
1605
                    # Mode B — co-declaration whose publisher covers the side this
1606
                    # one's publisher doesn't. Between {publisher, publisher2},
1607
                    # both admin sides must be covered.
1608
                    GRAPH <%4$s> {
1609
                      ?d2 a npa:SubSpaceDeclaration ;
1610
                          npa:childSpace  ?child ;
1611
                          npa:parentSpace ?parent ;
1612
                          npa:pubkeyHash  ?pkh2 ;
1613
                          npa:viaNanopub  ?np2 .
1614
                      FILTER (?np2 != ?np)
1615
                    }
1616
                    %8$s
1617
                    GRAPH <%3$s> {
1618
                      ?acct2 a npa:AccountState ;
1619
                             npa:pubkey ?pkh2 ;
1620
                             npa:agent  ?publisher2 .
1621
                      ?riA a gen:RoleInstantiation ;
1622
                           npa:inverseProperty gen:hasAdmin ;
1623
                           npa:forSpace ?child ;
1624
                           npa:forSpaceRef ?childRef .
1625
                      { ?riA npa:forAgent ?publisher } UNION { ?riA npa:forAgent ?publisher2 }
1626
                      ?riB a gen:RoleInstantiation ;
1627
                           npa:inverseProperty gen:hasAdmin ;
1628
                           npa:forSpace ?parent ;
1629
                           npa:forSpaceRef ?parentRef .
1630
                      { ?riB npa:forAgent ?publisher } UNION { ?riB npa:forAgent ?publisher2 }
1631
                    }
1632
                  }
1633
                  # 4. Invalidation filter on the primary declaration's nanopub.
1634
                  %6$s
1635
                  # 5. Load-number filter on bound ?np.
1636
                  GRAPH <%7$s> {
1637
                    ?np npa:hasLoadNumber ?ln .
1638
                    FILTER (?ln > %5$d)
1639
                  }
1640
                  # 6. Dedup last — on the emitted ref-to-ref edge.
1641
                  FILTER NOT EXISTS { GRAPH <%3$s> {
1642
                    ?childRef npa:isSubSpaceOf ?parentRef .
1643
                  } }
1644
                }
1645
                """.formatted(
3✔
1646
                NPA.NAMESPACE,
1647
                GEN.NAMESPACE,
1648
                graph,
1649
                SpacesVocab.SPACES_GRAPH,
1650
                lastProcessed,
15✔
1651
                invalidationFilter("np"),
27✔
1652
                NPA.GRAPH,
1653
                invalidationFilter("np2"));
6✔
1654
    }
1655

1656
    /**
1657
     * Maintained-resource admit pass. Copies validated
1658
     * {@code npa:MaintainedResourceDeclaration} extraction rows into the space-state
1659
     * graph (preserving the {@code npamrd:} subject) and emits convenience
1660
     * {@code <r> npa:isMaintainedBy <s>} and {@code <s> npa:hasMaintainedResource <r>}
1661
     * direct triples. Single satisfaction mode:
1662
     * <ul>
1663
     *   <li>Mode A — the declaration's publisher is a validated admin of the
1664
     *       maintaining space.</li>
1665
     * </ul>
1666
     *
1667
     * <p>No Mode B because only one space is involved; the two-sides-must-be-covered
1668
     * concern that drives sub-space Mode B doesn't apply. Late-arrival is still
1669
     * possible (declaration lands before the publisher's admin grant becomes valid):
1670
     * the load-number filter on {@code ?np} excludes the candidate, and the
1671
     * late-arrival sweep ({@link #runDownstreamWithoutLoadFilter}) re-runs this pass
1672
     * without the load filter and catches it.
1673
     */
1674
    static String maintainedResourceAdmitUpdate(IRI graph, long lastProcessed) {
1675
        return """
69✔
1676
                PREFIX npa: <%1$s>
1677
                PREFIX gen: <%2$s>
1678
                INSERT { GRAPH <%3$s> {
1679
                  ?d a npa:MaintainedResourceDeclaration ;
1680
                     npa:resourceIri     ?r ;
1681
                     npa:maintainerSpace ?s ;
1682
                     npa:viaNanopub      ?np .
1683
                  ?r npa:isMaintainedBy        ?sRef .
1684
                  ?sRef npa:hasMaintainedResource ?r .
1685
                  # TRANSITIONAL-DUAL-EMIT (Phase 1.5; remove in Phase 4): IRI-valued
1686
                  # maintained-resource edge alongside the resource→ref one, so pre-ref
1687
                  # published queries (e.g. get-view-displays' maintained hop) keep binding
1688
                  # on a mixed-version fleet. This is the edge whose absence broke 1.15.0 —
1689
                  # see doc/report-2026-06-12-mixed-fleet-spaceref-breakage.md.
1690
                  ?r npa:isMaintainedBy        ?s .
1691
                  ?s npa:hasMaintainedResource ?r .
1692
                } }
1693
                WHERE {
1694
                  # 1. Anchor: candidate declarations from the extraction graph.
1695
                  GRAPH <%4$s> {
1696
                    ?d a npa:MaintainedResourceDeclaration ;
1697
                       npa:resourceIri     ?r ;
1698
                       npa:maintainerSpace ?s ;
1699
                       npa:pubkeyHash      ?pkh ;
1700
                       npa:viaNanopub      ?np .
1701
                  }
1702
                  # 2. Mirror: resolve ?pkh → ?publisher via the trust-approved row.
1703
                  GRAPH <%3$s> {
1704
                    ?acct a npa:AccountState ;
1705
                          npa:pubkey ?pkh ;
1706
                          npa:agent  ?publisher .
1707
                    # 3. Authority gate (Mode A only): publisher is admin of a ref of the
1708
                    #    maintaining space. ?sRef = that ref (resource → ref edge).
1709
                    ?riA a gen:RoleInstantiation ;
1710
                         npa:inverseProperty gen:hasAdmin ;
1711
                         npa:forSpace ?s ;
1712
                         npa:forSpaceRef ?sRef ;
1713
                         npa:forAgent ?publisher .
1714
                  }
1715
                  # 4. Invalidation filter on the declaration's nanopub.
1716
                  %6$s
1717
                  # 5. Load-number filter on bound ?np.
1718
                  GRAPH <%7$s> {
1719
                    ?np npa:hasLoadNumber ?ln .
1720
                    FILTER (?ln > %5$d)
1721
                  }
1722
                  # 6. Dedup last — on the emitted resource → ref edge.
1723
                  FILTER NOT EXISTS { GRAPH <%3$s> {
1724
                    ?r npa:isMaintainedBy ?sRef .
1725
                  } }
1726
                }
1727
                """.formatted(
3✔
1728
                NPA.NAMESPACE,
1729
                GEN.NAMESPACE,
1730
                graph,
1731
                SpacesVocab.SPACES_GRAPH,
1732
                lastProcessed,
15✔
1733
                invalidationFilter("np"),
18✔
1734
                NPA.GRAPH);
1735
    }
1736

1737
    /**
1738
     * Space-alias admit pass (issue #113). Copies validated
1739
     * {@code npa:SpaceAliasDeclaration} extraction rows into the space-state graph
1740
     * (preserving the {@code npaalias:} subject) and emits the directional
1741
     * {@code <alias> npa:sameAsSpace <canonical>} edge consumed by the alias-aware
1742
     * admin-authority lookups in {@link #attachmentValidationUpdate},
1743
     * {@link #PUBLISHER_IS_ADMIN}, and {@link #publisherIsTieredRole}.
1744
     *
1745
     * <p>Two gates, both read against the (already-settled) admin closure in the
1746
     * space-state graph:
1747
     * <ul>
1748
     *   <li><b>Authority</b> — the declaration's publisher (resolved via the mirrored
1749
     *       trust-approved {@code AccountState}) is a validated admin of the
1750
     *       <em>canonical</em> space. The alias is declared inside the canonical
1751
     *       space's own {@code gen:Space} nanopub, so this is the same evidence rule
1752
     *       as a {@code gen:hasRole} attachment.</li>
1753
     *   <li><b>Anti-hijack</b> — the alias must not be an independently-governed live
1754
     *       space: it must have no admin who is not also an admin of the canonical
1755
     *       space ({@code admins(alias) ⊆ admins(canonical)}). The common rename case
1756
     *       (the alias's own definition was superseded, so it has no live admin
1757
     *       closure) passes trivially; an attacker publishing
1758
     *       {@code <evil> owl:sameAs <activeSpace>} is rejected because the active
1759
     *       space has admins not in evil's set.</li>
1760
     * </ul>
1761
     *
1762
     * <p>Late-arrival: when the canonical admin grant only becomes valid in the same
1763
     * cycle as the declaration, the load-number filter on {@code ?np} excludes the
1764
     * candidate; the late-arrival sweep ({@link #runDownstreamWithoutLoadFilter})
1765
     * re-runs this pass without the load filter and catches it.
1766
     */
1767
    static String aliasAdmitUpdate(IRI graph, long lastProcessed) {
1768
        // Ref-keyed (see doc/design-spaceref-isolation.md). The declaration names bare
1769
        // canonical/alias IRIs. It is admitted per canonical *ref* whose admin set
1770
        // contains the publisher; the emitted edge is ref-valued on the canonical side
1771
        // (<alias> npa:sameAsSpace <canonicalRef>), which is what the alias-aware admin
1772
        // lookups in the attachment tier consume. Anti-hijack compares the alias IRI's
1773
        // admins against that specific canonical ref's admins — strictly tighter than the
1774
        // old bare-IRI form.
1775
        return """
69✔
1776
                PREFIX npa: <%1$s>
1777
                PREFIX gen: <%2$s>
1778
                INSERT { GRAPH <%3$s> {
1779
                  ?d a npa:SpaceAliasDeclaration ;
1780
                     npa:canonicalSpace ?canonical ;
1781
                     npa:aliasSpace     ?alias ;
1782
                     npa:viaNanopub     ?np .
1783
                  ?alias npa:sameAsSpace ?canonRef .
1784
                  # TRANSITIONAL-DUAL-EMIT (Phase 1.5; remove in Phase 4): IRI-valued
1785
                  # alias edge alongside the ref-valued one, so pre-ref published queries
1786
                  # that resolve owl:sameAs by bare canonical IRI keep binding on a
1787
                  # mixed-version fleet. Internal alias-aware lookups (attachment tier)
1788
                  # join through npa:forSpaceRef, which is ref-valued, so this IRI-valued
1789
                  # object never satisfies them — it is inert internally, read-only for
1790
                  # legacy consumers. See doc/report-2026-06-12-mixed-fleet-spaceref-breakage.md.
1791
                  ?alias npa:sameAsSpace ?canonical .
1792
                } }
1793
                WHERE {
1794
                  # 1. Anchor: candidate alias declarations from the extraction graph.
1795
                  GRAPH <%4$s> {
1796
                    ?d a npa:SpaceAliasDeclaration ;
1797
                       npa:canonicalSpace ?canonical ;
1798
                       npa:aliasSpace     ?alias ;
1799
                       npa:pubkeyHash     ?pkh ;
1800
                       npa:viaNanopub     ?np .
1801
                  }
1802
                  # 2. Authority gate per canonical ref: ?canonRef is a ref of ?canonical
1803
                  #    whose admin set contains the declaration's publisher.
1804
                  GRAPH <%4$s> { ?canonRef npa:spaceIri ?canonical . }
1805
                  GRAPH <%3$s> {
1806
                    ?acct a npa:AccountState ;
1807
                          npa:pubkey ?pkh ;
1808
                          npa:agent  ?publisher .
1809
                    ?adminRI a gen:RoleInstantiation ;
1810
                             npa:inverseProperty gen:hasAdmin ;
1811
                             npa:forSpaceRef ?canonRef ;
1812
                             npa:forAgent ?publisher .
1813
                  }
1814
                  # 3. Anti-hijack: the alias IRI must have no admin who is not also an
1815
                  #    admin of this canonical ref (admins(alias) ⊆ admins(canonRef)).
1816
                  FILTER NOT EXISTS {
1817
                    GRAPH <%3$s> {
1818
                      ?aliasAdmin a gen:RoleInstantiation ;
1819
                                  npa:inverseProperty gen:hasAdmin ;
1820
                                  npa:forSpace ?alias ;
1821
                                  npa:forAgent ?otherAgent .
1822
                    }
1823
                    FILTER NOT EXISTS {
1824
                      GRAPH <%3$s> {
1825
                        ?canonAdmin a gen:RoleInstantiation ;
1826
                                    npa:inverseProperty gen:hasAdmin ;
1827
                                    npa:forSpaceRef ?canonRef ;
1828
                                    npa:forAgent ?otherAgent .
1829
                      }
1830
                    }
1831
                  }
1832
                  # 4. Invalidation filter on the declaration's nanopub.
1833
                  %6$s
1834
                  # 5. Load-number filter on bound ?np.
1835
                  GRAPH <%7$s> {
1836
                    ?np npa:hasLoadNumber ?ln .
1837
                    FILTER (?ln > %5$d)
1838
                  }
1839
                  # 6. Dedup last — on the emitted (alias, canonical ref) edge.
1840
                  FILTER NOT EXISTS { GRAPH <%3$s> {
1841
                    ?alias npa:sameAsSpace ?canonRef .
1842
                  } }
1843
                }
1844
                """.formatted(
3✔
1845
                NPA.NAMESPACE,
1846
                GEN.NAMESPACE,
1847
                graph,
1848
                SpacesVocab.SPACES_GRAPH,
1849
                lastProcessed,
15✔
1850
                invalidationFilter("np"),
18✔
1851
                NPA.GRAPH);
1852
    }
1853

1854
    /**
1855
     * URL-prefix sub-space fallback admit pass. For every pair of {@code SpaceRef}
1856
     * aggregates where the child's {@code npa:hasIdPrefix} matches the parent's
1857
     * {@code npa:spaceIri}, emits convenience {@code <child> npa:isSubSpaceOf <parent>}
1858
     * and {@code <parent> npa:hasSubSpace <child>} direct triples plus a reified
1859
     * {@code npa:DerivedSubSpaceLink} tag carrying {@code npa:derivationKind
1860
     * npa:byUrlPrefix} so consumers can hide derived edges.
1861
     *
1862
     * <p>Per-child suppression: any validated {@code npa:SubSpaceDeclaration} on the
1863
     * child in {@code npass:<…>} suppresses every fallback edge for that child.
1864
     * Suppression checks the validated set (not raw extraction-graph declarations)
1865
     * so an unapproved or in-flight Mode B declaration doesn't silently hide both
1866
     * the URL-prefix fallback and the (still-invalid) explicit relation.
1867
     *
1868
     * <p>Run order: must run after {@link #subSpaceAdmitUpdate} commits in the
1869
     * same cycle so the suppression check sees this cycle's freshly-validated
1870
     * declarations.
1871
     *
1872
     * <p>No load-number filter: the fallback depends on which Spaces exist (parent
1873
     * + child {@code SpaceRef}s), not on which were just added. Always full-scan;
1874
     * the dedup {@code FILTER NOT EXISTS} on the tag IRI prevents re-insertion.
1875
     *
1876
     * <p>No invalidation handling: derived edges have no source nanopub. Two
1877
     * staleness modes: (a) child later gets first validated declaration → old
1878
     * derived edges stay sticky until the next periodic rebuild (same policy as
1879
     * admin-RI invalidation); (b) child loses last validated declaration → the
1880
     * regular fallback pass on the next cycle re-engages, adds derived edges
1881
     * incrementally, no rebuild needed.
1882
     */
1883
    static String subSpacePrefixFallbackUpdate(IRI graph) {
1884
        return """
48✔
1885
                PREFIX npa: <%1$s>
1886
                INSERT { GRAPH <%2$s> {
1887
                  ?childRef  npa:isSubSpaceOf ?parentRef .
1888
                  ?parentRef npa:hasSubSpace  ?childRef  .
1889
                  # TRANSITIONAL-DUAL-EMIT (Phase 1.5; remove in Phase 4): IRI-valued
1890
                  # derived sub-space edge alongside the ref-to-ref one, mirroring the
1891
                  # explicit sub-space pass, so pre-ref published queries keep binding on a
1892
                  # mixed-version fleet. See doc/report-2026-06-12-mixed-fleet-spaceref-breakage.md.
1893
                  ?child  npa:isSubSpaceOf ?parent .
1894
                  ?parent npa:hasSubSpace  ?child  .
1895
                  ?tagIri a npa:DerivedSubSpaceLink ;
1896
                          npa:childSpace     ?child ;
1897
                          npa:parentSpace    ?parent ;
1898
                          npa:derivationKind npa:byUrlPrefix .
1899
                } }
1900
                WHERE {
1901
                  # 1. Anchor: child SpaceRef → its path-prefixes (extracted at load
1902
                  #    time from the Space IRI; see SpacesExtractor.enumerateIdPrefixes).
1903
                  GRAPH <%3$s> {
1904
                    ?childRef  npa:spaceIri    ?child ;
1905
                               npa:hasIdPrefix ?parent .
1906
                    # 2. Parent SpaceRef must exist for the same IRI as the prefix.
1907
                    ?parentRef npa:spaceIri    ?parent .
1908
                  }
1909
                  # 3. Suppress fallback for any child that has a validated declaration
1910
                  #    in this state graph. Per-child IRI, all-or-nothing.
1911
                  FILTER NOT EXISTS {
1912
                    GRAPH <%2$s> {
1913
                      ?d a npa:SubSpaceDeclaration ;
1914
                         npa:childSpace ?child .
1915
                    }
1916
                  }
1917
                  # 4. Mint a deterministic tag IRI per (child ref, parent ref) — the edge
1918
                  #    is emitted ref-to-ref, so the tag and dedup are per ref-pair.
1919
                  BIND(IRI(CONCAT("http://purl.org/nanopub/admin/derivedlink/",
1920
                                  MD5(CONCAT(STR(?childRef), "|", STR(?parentRef))))) AS ?tagIri)
1921
                  # 5. Dedup: don't re-insert if this tag is already present.
1922
                  FILTER NOT EXISTS {
1923
                    GRAPH <%2$s> {
1924
                      ?tagIri a npa:DerivedSubSpaceLink .
1925
                    }
1926
                  }
1927
                }
1928
                """.formatted(
3✔
1929
                NPA.NAMESPACE,
1930
                graph,
1931
                SpacesVocab.SPACES_GRAPH);
1932
    }
1933

1934
    // ---------------- Invalidation templates (incremental cycle) ----------------
1935

1936
    /**
1937
     * WHERE clause shared by the admin-RI invalidation ASK precheck and the
1938
     * matching DELETE. Identifies admin-tier {@code gen:RoleInstantiation} rows
1939
     * in the space-state graph whose {@code npa:viaNanopub} is the target of an
1940
     * {@code npx:invalidates} triple in {@code npa:graph} whose subject nanopub
1941
     * has a load number in {@code (lastProcessed, ∞)}.
1942
     */
1943
    static String adminInvalidationCheckWhere(IRI graph, long lastProcessed) {
1944
        return String.format("""
60✔
1945
                  GRAPH <%1$s> {
1946
                    ?ri a gen:RoleInstantiation ;
1947
                        npa:inverseProperty gen:hasAdmin ;
1948
                        npa:viaNanopub ?np .
1949
                  }
1950
                  GRAPH <%2$s> {
1951
                    ?invNp <%3$s> ?np ;
1952
                           npa:hasLoadNumber ?ln .
1953
                    FILTER (?ln > %4$d)
1954
                    %5$s
1955
                  }
1956
                """, graph, NPA.GRAPH, NPX.INVALIDATES, lastProcessed,
18✔
1957
                samePublisherClause("invNp", "np"));
6✔
1958
    }
1959

1960
    /** DELETE template for admin-tier RoleInstantiations whose source nanopub was invalidated. */
1961
    static String adminInvalidationDelete(IRI graph, long lastProcessed) {
1962
        return String.format("""
63✔
1963
                PREFIX npa: <%1$s>
1964
                PREFIX gen: <%2$s>
1965
                DELETE { GRAPH <%3$s> {
1966
                  ?ri ?p ?o .
1967
                } }
1968
                WHERE {
1969
                  GRAPH <%3$s> { ?ri ?p ?o . }
1970
                %4$s
1971
                }
1972
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
1973
                adminInvalidationCheckWhere(graph, lastProcessed));
6✔
1974
    }
1975

1976
    /** WHERE clause for RoleAssignment invalidation. */
1977
    static String roleAssignmentInvalidationCheckWhere(IRI graph, long lastProcessed) {
1978
        return String.format("""
60✔
1979
                  GRAPH <%1$s> {
1980
                    ?ra a gen:RoleAssignment ;
1981
                        npa:viaNanopub ?np .
1982
                  }
1983
                  GRAPH <%2$s> {
1984
                    ?invNp <%3$s> ?np ;
1985
                           npa:hasLoadNumber ?ln .
1986
                    FILTER (?ln > %4$d)
1987
                    %5$s
1988
                  }
1989
                """, graph, NPA.GRAPH, NPX.INVALIDATES, lastProcessed,
18✔
1990
                samePublisherClause("invNp", "np"));
6✔
1991
    }
1992

1993
    /** DELETE template for RoleAssignments whose source nanopub was invalidated. */
1994
    static String roleAssignmentInvalidationDelete(IRI graph, long lastProcessed) {
1995
        return String.format("""
63✔
1996
                PREFIX npa: <%1$s>
1997
                PREFIX gen: <%2$s>
1998
                DELETE { GRAPH <%3$s> {
1999
                  ?ra ?p ?o .
2000
                } }
2001
                WHERE {
2002
                  GRAPH <%3$s> { ?ra ?p ?o . }
2003
                %4$s
2004
                }
2005
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
2006
                roleAssignmentInvalidationCheckWhere(graph, lastProcessed));
6✔
2007
    }
2008

2009
    /**
2010
     * DELETE template for non-admin (leaf-tier) RoleInstantiations whose source
2011
     * nanopub was invalidated. Identified as {@code gen:RoleInstantiation} rows
2012
     * lacking the admin-pinning {@code npa:inverseProperty gen:hasAdmin} triple.
2013
     * No flag is set; leaf-tier removals are recoverable on the next cycle.
2014
     */
2015
    static String leafTierInvalidationDelete(IRI graph, long lastProcessed) {
2016
        return String.format("""
84✔
2017
                PREFIX npa: <%1$s>
2018
                PREFIX gen: <%2$s>
2019
                DELETE { GRAPH <%3$s> {
2020
                  ?ri ?p ?o .
2021
                } }
2022
                WHERE {
2023
                  GRAPH <%3$s> {
2024
                    ?ri a gen:RoleInstantiation ;
2025
                        npa:viaNanopub ?np .
2026
                    FILTER NOT EXISTS { ?ri npa:inverseProperty gen:hasAdmin }
2027
                    ?ri ?p ?o .
2028
                  }
2029
                  GRAPH <%4$s> {
2030
                    ?invNp <%5$s> ?np ;
2031
                           npa:hasLoadNumber ?ln .
2032
                    FILTER (?ln > %6$d)
2033
                    %7$s
2034
                  }
2035
                }
2036
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
2037
                NPA.GRAPH, NPX.INVALIDATES, lastProcessed,
18✔
2038
                samePublisherClause("invNp", "np"));
6✔
2039
    }
2040

2041
    /**
2042
     * WHERE clause shared by the sub-space invalidation ASK precheck and the
2043
     * matching DELETE. Identifies validated {@code npa:SubSpaceDeclaration} rows
2044
     * in the space-state graph whose {@code npa:viaNanopub} is the target of an
2045
     * {@code npx:invalidates} triple in {@code npa:graph} whose subject nanopub
2046
     * has a load number in {@code (lastProcessed, ∞)}.
2047
     */
2048
    static String subSpaceInvalidationCheckWhere(IRI graph, long lastProcessed) {
2049
        return String.format("""
60✔
2050
                  GRAPH <%1$s> {
2051
                    ?d a npa:SubSpaceDeclaration ;
2052
                       npa:viaNanopub ?np .
2053
                  }
2054
                  GRAPH <%2$s> {
2055
                    ?invNp <%3$s> ?np ;
2056
                           npa:hasLoadNumber ?ln .
2057
                    FILTER (?ln > %4$d)
2058
                    %5$s
2059
                  }
2060
                """, graph, NPA.GRAPH, NPX.INVALIDATES, lastProcessed,
18✔
2061
                samePublisherClause("invNp", "np"));
6✔
2062
    }
2063

2064
    /**
2065
     * DELETE template for validated {@code npa:SubSpaceDeclaration} rows whose
2066
     * source nanopub was invalidated. Removes the per-declaration row by subject;
2067
     * the convenience direct triples ({@code <child> npa:isSubSpaceOf <parent>}
2068
     * and inverse) are left sticky and cleaned by the next periodic full rebuild
2069
     * (same staleness policy as admin-RI invalidation — see {@code
2070
     * doc/design-space-repositories.md} on the structural-rebuild flag).
2071
     */
2072
    static String subSpaceInvalidationDelete(IRI graph, long lastProcessed) {
2073
        return String.format("""
63✔
2074
                PREFIX npa: <%1$s>
2075
                PREFIX gen: <%2$s>
2076
                DELETE { GRAPH <%3$s> {
2077
                  ?d ?p ?o .
2078
                } }
2079
                WHERE {
2080
                  GRAPH <%3$s> { ?d ?p ?o . }
2081
                %4$s
2082
                }
2083
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
2084
                subSpaceInvalidationCheckWhere(graph, lastProcessed));
6✔
2085
    }
2086

2087
    /**
2088
     * DELETE template for validated {@code npa:MaintainedResourceDeclaration} rows
2089
     * whose source nanopub was invalidated. Removes the per-declaration row by
2090
     * subject; the convenience direct triples ({@code <r> npa:isMaintainedBy <s>}
2091
     * and inverse) are left sticky and cleaned by the next periodic full rebuild
2092
     * (same staleness policy as sub-space declaration invalidation, but without
2093
     * the structural-rebuild flag — maintained-resource is a leaf relation, no
2094
     * downstream consumers depend on its closure).
2095
     */
2096
    static String maintainedResourceInvalidationDelete(IRI graph, long lastProcessed) {
2097
        return String.format("""
84✔
2098
                PREFIX npa: <%1$s>
2099
                PREFIX gen: <%2$s>
2100
                DELETE { GRAPH <%3$s> {
2101
                  ?d ?p ?o .
2102
                } }
2103
                WHERE {
2104
                  GRAPH <%3$s> {
2105
                    ?d a npa:MaintainedResourceDeclaration ;
2106
                       npa:viaNanopub ?np .
2107
                    ?d ?p ?o .
2108
                  }
2109
                  GRAPH <%4$s> {
2110
                    ?invNp <%5$s> ?np ;
2111
                           npa:hasLoadNumber ?ln .
2112
                    FILTER (?ln > %6$d)
2113
                    %7$s
2114
                  }
2115
                }
2116
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
2117
                NPA.GRAPH, NPX.INVALIDATES, lastProcessed,
18✔
2118
                samePublisherClause("invNp", "np"));
6✔
2119
    }
2120

2121
    /**
2122
     * WHERE clause shared by the alias invalidation ASK precheck and the matching
2123
     * DELETE. Identifies validated {@code npa:SpaceAliasDeclaration} rows in the
2124
     * space-state graph whose {@code npa:viaNanopub} is the target of an
2125
     * {@code npx:invalidates} triple in {@code npa:graph} whose subject nanopub has a
2126
     * load number in {@code (lastProcessed, ∞)}.
2127
     */
2128
    static String aliasInvalidationCheckWhere(IRI graph, long lastProcessed) {
2129
        return String.format("""
60✔
2130
                  GRAPH <%1$s> {
2131
                    ?d a npa:SpaceAliasDeclaration ;
2132
                       npa:viaNanopub ?np .
2133
                  }
2134
                  GRAPH <%2$s> {
2135
                    ?invNp <%3$s> ?np ;
2136
                           npa:hasLoadNumber ?ln .
2137
                    FILTER (?ln > %4$d)
2138
                    %5$s
2139
                  }
2140
                """, graph, NPA.GRAPH, NPX.INVALIDATES, lastProcessed,
18✔
2141
                samePublisherClause("invNp", "np"));
6✔
2142
    }
2143

2144
    /**
2145
     * DELETE template for validated {@code npa:SpaceAliasDeclaration} rows whose
2146
     * source nanopub was invalidated. Removes the per-declaration row by subject; the
2147
     * convenience {@code <alias> npa:sameAsSpace <canonical>} edge is left sticky and
2148
     * cleaned by the next periodic full rebuild (same staleness policy as sub-space
2149
     * declaration invalidation — the alias feeds the authority closure, so this kind
2150
     * is structural and flips {@code npa:needsFullRebuild}).
2151
     */
2152
    static String aliasInvalidationDelete(IRI graph, long lastProcessed) {
2153
        return String.format("""
63✔
2154
                PREFIX npa: <%1$s>
2155
                PREFIX gen: <%2$s>
2156
                DELETE { GRAPH <%3$s> {
2157
                  ?d ?p ?o .
2158
                } }
2159
                WHERE {
2160
                  GRAPH <%3$s> { ?d ?p ?o . }
2161
                %4$s
2162
                }
2163
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
2164
                aliasInvalidationCheckWhere(graph, lastProcessed));
6✔
2165
    }
2166

2167
    /**
2168
     * WHERE clause shared by the preset-deactivation ASK precheck and the matching DELETE
2169
     * (Nanodash issue #302). Binds {@code ?ra} = a materialized preset-derived
2170
     * {@code gen:RoleAssignment} ({@code npa:derivedFromPreset}) for which a <em>newer,
2171
     * admin-authored</em> same-{@code (preset, resource)} assignment exists by
2172
     * {@code dct:created} (load number in {@code (lastProcessed, ∞)}). This is NOT an
2173
     * {@code npx:invalidates} check — preset activation is latest-wins by timestamp.
2174
     *
2175
     * <p>Authorization-scoped (anti-hijack, design doc §3/§4.4): the newer assignment's
2176
     * publisher must itself be a validated admin of the row's {@code npa:forSpaceRef}, so an
2177
     * unauthorized key's newer assignment can neither delete nor shadow an admin's
2178
     * materialized role. {@code dct:created} is written as a full IRI (not a {@code dct:}
2179
     * prefix) because {@link #wouldInvalidate}'s ASK wrapper only declares {@code npa:} /
2180
     * {@code gen:}.
2181
     */
2182
    static String presetDeactivationCheckWhere(IRI graph, long lastProcessed) {
2183
        return String.format("""
60✔
2184
                  GRAPH <%1$s> {
2185
                    ?ra a gen:RoleAssignment ;
2186
                        npa:derivedFromPreset ?assignNp ;
2187
                        npa:forSpaceRef ?targetRef .
2188
                  }
2189
                  GRAPH <%2$s> {
2190
                    ?pa a npa:PresetAssignment ;
2191
                        npa:viaNanopub  ?assignNp ;
2192
                        npa:ofPreset    ?preset ;
2193
                        npa:forResource ?resource ;
2194
                        <http://purl.org/dc/terms/created> ?created .
2195
                    ?paNewer a npa:PresetAssignment ;
2196
                             npa:ofPreset    ?preset ;
2197
                             npa:forResource ?resource ;
2198
                             npa:pubkeyHash  ?pkhNewer ;
2199
                             npa:viaNanopub  ?assignNpNewer ;
2200
                             <http://purl.org/dc/terms/created> ?createdNewer .
2201
                    FILTER (?createdNewer > ?created
2202
                            || (?createdNewer = ?created && STR(?paNewer) > STR(?pa)))
2203
                  }
2204
                  GRAPH <%3$s> {
2205
                    ?assignNpNewer npa:hasLoadNumber ?lnNewer .
2206
                    FILTER (?lnNewer > %4$d)
2207
                  }
2208
                  GRAPH <%1$s> {
2209
                    ?acctNewer a npa:AccountState ;
2210
                               npa:agent  ?publisherNewer ;
2211
                               npa:pubkey ?pkhNewer .
2212
                    ?adminRINewer a gen:RoleInstantiation ;
2213
                                  npa:forSpaceRef ?targetRef ;
2214
                                  npa:inverseProperty gen:hasAdmin ;
2215
                                  npa:forAgent ?publisherNewer .
2216
                  }
2217
                """, graph, SpacesVocab.SPACES_GRAPH, NPA.GRAPH, lastProcessed);
6✔
2218
    }
2219

2220
    /**
2221
     * DELETE template for preset-derived {@code gen:RoleAssignment} rows superseded by a
2222
     * newer admin-authored same-pair assignment (issue #302). Removes the whole row by
2223
     * subject; scoped via {@code npa:derivedFromPreset} so directly-published attachments
2224
     * are never touched. The {@link #presetAttachmentValidationUpdate} re-INSERT in the
2225
     * same cycle re-materializes the pair iff the newest assignment is still active.
2226
     */
2227
    static String presetDeactivationDelete(IRI graph, long lastProcessed) {
2228
        return String.format("""
63✔
2229
                PREFIX npa: <%1$s>
2230
                PREFIX gen: <%2$s>
2231
                DELETE { GRAPH <%3$s> {
2232
                  ?ra ?p ?o .
2233
                } }
2234
                WHERE {
2235
                  GRAPH <%3$s> { ?ra ?p ?o . }
2236
                %4$s
2237
                }
2238
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
2239
                presetDeactivationCheckWhere(graph, lastProcessed));
6✔
2240
    }
2241

2242
    /**
2243
     * DELETE template for ref-scoped preset-assignment stamps ({@link
2244
     * #presetAssignmentRefStampUpdate}) whose underlying assignment nanopub was
2245
     * hard-retracted (issue #122). Removes the whole row by subject; scoped to
2246
     * state-graph {@code npa:PresetAssignment} rows that carry {@code npa:forSpaceRef}
2247
     * (the IRI-keyed extraction rows never do), so it can never touch them.
2248
     *
2249
     * <p>Leaf delete — no structural flag: nothing downstream derives from a listing
2250
     * stamp, so a stale row only mis-displays a retracted assignment until this cycle's
2251
     * delete runs. Admin-grant revocation is bounded by the periodic full rebuild (same
2252
     * sticky-convenience policy as the alias / sub-space declaration edges). A
2253
     * <em>deactivation</em> needs no delete here: it is represented as a newer
2254
     * admin-authored stamp with {@code npa:isActivated false}, resolved by the consumer's
2255
     * latest-wins.
2256
     */
2257
    static String presetAssignmentRefInvalidationDelete(IRI graph, long lastProcessed) {
2258
        return String.format("""
84✔
2259
                PREFIX npa: <%1$s>
2260
                PREFIX gen: <%2$s>
2261
                DELETE { GRAPH <%3$s> {
2262
                  ?paRef ?p ?o .
2263
                } }
2264
                WHERE {
2265
                  GRAPH <%3$s> {
2266
                    ?paRef a npa:PresetAssignment ;
2267
                           npa:forSpaceRef ?targetRef ;
2268
                           npa:viaNanopub  ?assignNp .
2269
                    ?paRef ?p ?o .
2270
                  }
2271
                  GRAPH <%4$s> {
2272
                    ?invNp <%5$s> ?assignNp ;
2273
                           npa:hasLoadNumber ?ln .
2274
                    FILTER (?ln > %6$d)
2275
                    %7$s
2276
                  }
2277
                }
2278
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
2279
                NPA.GRAPH, NPX.INVALIDATES, lastProcessed,
18✔
2280
                samePublisherClause("invNp", "assignNp"));
6✔
2281
    }
2282

2283
    /** Wraps an ASK by joining the shared prefixes. */
2284
    private boolean wouldInvalidate(IRI graph, long lastProcessed,
2285
                                    boolean adminPinned, String whereClause) {
2286
        // adminPinned is informational only — kept to make call sites read clearly;
2287
        // the WHERE clause already encodes the kind via its own type predicates.
2288
        String ask = String.format("""
×
2289
                PREFIX npa: <%1$s>
2290
                PREFIX gen: <%2$s>
2291
                ASK { %3$s }
2292
                """, NPA.NAMESPACE, GEN.NAMESPACE, whereClause);
2293
        return runAsk(ask);
×
2294
    }
2295

2296
    private boolean runAsk(String sparql) {
2297
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
2298
            return conn.prepareBooleanQuery(QueryLanguage.SPARQL, sparql).evaluate();
×
2299
        }
2300
    }
2301

2302
    private void executeUpdate(String sparqlUpdate) {
2303
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
2304
            conn.prepareUpdate(QueryLanguage.SPARQL, sparqlUpdate).execute();
×
2305
        }
2306
    }
×
2307

2308
    // ---------------- Mirror step ----------------
2309

2310
    /**
2311
     * Copies trust-approved {@code npa:AccountState} rows from {@code npat:<T>}
2312
     * in the {@code trust} repo into {@code newGraph} in the {@code spaces} repo,
2313
     * inside one spaces-side serializable transaction.
2314
     *
2315
     * @return number of rows mirrored (useful for metrics / logging)
2316
     */
2317
    int mirrorTrustState(String trustStateHash, IRI newGraph) {
2318
        IRI trustStateIri = NPAT.forHash(trustStateHash);
×
2319
        int count = 0;
×
2320
        try (RepositoryConnection trustConn = TripleStore.get().getRepoConnection(TRUST_REPO);
×
2321
             RepositoryConnection spacesConn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
2322
            trustConn.begin(IsolationLevels.READ_COMMITTED);
×
2323
            spacesConn.begin(IsolationLevels.SERIALIZABLE);
×
2324
            // Walk rdf:type triples in the trust state's graph; for each AccountState,
2325
            // check status and copy the approved ones verbatim (minus status-specific
2326
            // detail triples, which we don't need for validation).
2327
            try (RepositoryResult<Statement> typeRows = trustConn.getStatements(
×
2328
                    null, RDF.TYPE, NPA_ACCOUNT_STATE, trustStateIri)) {
2329
                while (typeRows.hasNext()) {
×
2330
                    Statement st = typeRows.next();
×
2331
                    if (!(st.getSubject() instanceof IRI accountStateIri)) continue;
×
2332
                    Value status = trustConn.getStatements(accountStateIri, NPA_TRUST_STATUS, null, trustStateIri)
×
2333
                            .stream().findFirst().map(Statement::getObject).orElse(null);
×
2334
                    if (!(status instanceof IRI statusIri) || !APPROVED_SET.contains(statusIri)) continue;
×
2335
                    Value agent = trustConn.getStatements(accountStateIri, NPA_AGENT, null, trustStateIri)
×
2336
                            .stream().findFirst().map(Statement::getObject).orElse(null);
×
2337
                    Value pubkey = trustConn.getStatements(accountStateIri, NPA_PUBKEY, null, trustStateIri)
×
2338
                            .stream().findFirst().map(Statement::getObject).orElse(null);
×
2339
                    if (agent == null || pubkey == null) {
×
2340
                        logger.warn("AuthorityResolver.mirror: account {} missing agent or pubkey; skipping",
×
2341
                                accountStateIri);
2342
                        continue;
×
2343
                    }
2344
                    spacesConn.add(accountStateIri, RDF.TYPE, NPA_ACCOUNT_STATE, newGraph);
×
2345
                    spacesConn.add(accountStateIri, NPA_AGENT, agent, newGraph);
×
2346
                    spacesConn.add(accountStateIri, NPA_PUBKEY, pubkey, newGraph);
×
2347
                    spacesConn.add(accountStateIri, NPA_TRUST_STATUS, statusIri, newGraph);
×
2348
                    count++;
×
2349
                }
×
2350
            }
2351
            // Mirror canonical foaf:name triples for approved agents. The trust
2352
            // loader emits one per agent (across approved keys, MAX(ratio) wins).
2353
            // Copying them into the space-state graph means consumers reading
2354
            // ?agent foaf:name ?n inside the state graph hit local data, with no
2355
            // cross-repo SERVICE.
2356
            try (RepositoryResult<Statement> nameRows = trustConn.getStatements(
×
2357
                    null, FOAF.NAME, null, trustStateIri)) {
2358
                while (nameRows.hasNext()) {
×
2359
                    Statement st = nameRows.next();
×
2360
                    spacesConn.add(st.getSubject(), st.getPredicate(), st.getObject(), newGraph);
×
2361
                }
×
2362
            }
2363
            spacesConn.commit();
×
2364
            trustConn.commit();
×
2365
        }
2366
        return count;
×
2367
    }
2368

2369
    // ---------------- Pointer + counter helpers ----------------
2370

2371
    /**
2372
     * Reads the current {@code npa:hasCurrentSpaceState} pointer from the
2373
     * {@code npa:graph} admin graph of the {@code spaces} repo. Returns
2374
     * {@code null} if no pointer exists yet.
2375
     */
2376
    IRI getCurrentSpaceStateGraph() {
2377
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
2378
            Value v = Utils.getObjectForPattern(conn, NPA.GRAPH, NPA.THIS_REPO,
×
2379
                    SpacesVocab.HAS_CURRENT_SPACE_STATE);
2380
            return (v instanceof IRI iri) ? iri : null;
×
2381
        } catch (Exception ex) {
×
2382
            logger.warn("AuthorityResolver: failed to read hasCurrentSpaceState pointer: {}", ex.toString());
×
2383
            return null;
×
2384
        }
2385
    }
2386

2387
    long getCurrentLoadCounter() {
2388
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
2389
            Value v = Utils.getObjectForPattern(conn, NPA.GRAPH, NPA.THIS_REPO,
×
2390
                    SpacesVocab.CURRENT_LOAD_COUNTER);
2391
            if (v == null) return 0;
×
2392
            try {
2393
                return Long.parseLong(v.stringValue());
×
2394
            } catch (NumberFormatException ex) {
×
2395
                logger.warn("AuthorityResolver: non-numeric currentLoadCounter: {}", v);
×
2396
                return 0;
×
2397
            }
2398
        } catch (Exception ex) {
×
2399
            logger.warn("AuthorityResolver: failed to read currentLoadCounter: {}", ex.toString());
×
2400
            return 0;
×
2401
        }
2402
    }
2403

2404
    /**
2405
     * Atomic pointer flip: a single SPARQL {@code DELETE … INSERT … WHERE}
2406
     * replaces the old pointer with the new one in one statement, so readers
2407
     * never see a zero-pointer window.
2408
     */
2409
    void flipPointer(IRI newGraph) {
2410
        String update = String.format("""
×
2411
                DELETE { GRAPH <%s> { <%s> <%s> ?old } }
2412
                INSERT { GRAPH <%s> { <%s> <%s> <%s> } }
2413
                WHERE  { OPTIONAL { GRAPH <%s> { <%s> <%s> ?old } } }
2414
                """,
2415
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.HAS_CURRENT_SPACE_STATE,
2416
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.HAS_CURRENT_SPACE_STATE, newGraph,
2417
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.HAS_CURRENT_SPACE_STATE);
2418
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
2419
            conn.begin(IsolationLevels.SERIALIZABLE);
×
2420
            conn.prepareUpdate(QueryLanguage.SPARQL, update).execute();
×
2421
            conn.commit();
×
2422
        }
2423
    }
×
2424

2425
    void writeProcessedUpTo(IRI graph, long loadCounter) {
2426
        String update = String.format("""
×
2427
                DELETE { GRAPH <%s> { <%s> <%s> ?old } }
2428
                INSERT { GRAPH <%s> { <%s> <%s> "%d"^^<http://www.w3.org/2001/XMLSchema#long> } }
2429
                WHERE  { OPTIONAL { GRAPH <%s> { <%s> <%s> ?old } } }
2430
                """,
2431
                graph, graph, SpacesVocab.PROCESSED_UP_TO,
2432
                graph, graph, SpacesVocab.PROCESSED_UP_TO, loadCounter,
×
2433
                graph, graph, SpacesVocab.PROCESSED_UP_TO);
2434
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
2435
            conn.begin(IsolationLevels.SERIALIZABLE);
×
2436
            conn.prepareUpdate(QueryLanguage.SPARQL, update).execute();
×
2437
            conn.commit();
×
2438
        }
2439
    }
×
2440

2441
    /**
2442
     * Reads {@code processedUpTo} from the given space-state graph.
2443
     * Returns {@code -1} if absent (graph not fully built yet).
2444
     */
2445
    long readProcessedUpTo(IRI graph) {
2446
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
2447
            String query = String.format(
×
2448
                    "SELECT ?n WHERE { GRAPH <%s> { <%s> <%s> ?n } }",
2449
                    graph, graph, SpacesVocab.PROCESSED_UP_TO);
2450
            try (TupleQueryResult r = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) {
×
2451
                if (!r.hasNext()) return -1;
×
2452
                BindingSet b = r.next();
×
2453
                return Long.parseLong(b.getBinding("n").getValue().stringValue());
×
2454
            }
×
2455
        } catch (Exception ex) {
×
2456
            logger.warn("AuthorityResolver: failed to read processedUpTo for {}: {}", graph, ex.toString());
×
2457
            return -1;
×
2458
        }
2459
    }
2460

2461
    /**
2462
     * Reads the {@code npa:needsFullRebuild} flag (boolean literal) from
2463
     * {@code npa:graph} in the {@code spaces} repo. Defaults to {@code false}
2464
     * when the triple is absent.
2465
     */
2466
    boolean readNeedsFullRebuild() {
2467
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
2468
            Value v = Utils.getObjectForPattern(conn, NPA.GRAPH, NPA.THIS_REPO,
×
2469
                    SpacesVocab.NEEDS_FULL_REBUILD);
2470
            return v != null && Boolean.parseBoolean(v.stringValue());
×
2471
        } catch (Exception ex) {
×
2472
            logger.warn("AuthorityResolver: failed to read needsFullRebuild: {}", ex.toString());
×
2473
            return false;
×
2474
        }
2475
    }
2476

2477
    void setNeedsFullRebuild() {
2478
        writeNeedsFullRebuild(true);
×
2479
    }
×
2480

2481
    void clearNeedsFullRebuild() {
2482
        writeNeedsFullRebuild(false);
×
2483
    }
×
2484

2485
    private void writeNeedsFullRebuild(boolean value) {
2486
        String update = String.format("""
×
2487
                DELETE { GRAPH <%s> { <%s> <%s> ?old } }
2488
                INSERT { GRAPH <%s> { <%s> <%s> "%s"^^<http://www.w3.org/2001/XMLSchema#boolean> } }
2489
                WHERE  { OPTIONAL { GRAPH <%s> { <%s> <%s> ?old } } }
2490
                """,
2491
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.NEEDS_FULL_REBUILD,
2492
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.NEEDS_FULL_REBUILD, value,
×
2493
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.NEEDS_FULL_REBUILD);
2494
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
2495
            conn.begin(IsolationLevels.SERIALIZABLE);
×
2496
            conn.prepareUpdate(QueryLanguage.SPARQL, update).execute();
×
2497
            conn.commit();
×
2498
        }
2499
    }
×
2500

2501
    void dropGraph(IRI graph) {
2502
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
2503
            conn.begin(IsolationLevels.SERIALIZABLE);
×
2504
            conn.clear(graph);
×
2505
            conn.commit();
×
2506
            logger.info("AuthorityResolver: dropped old space-state graph {}", graph);
×
2507
        }
2508
    }
×
2509

2510
    // ---------------- Trust-repo pointer lookup (used by TrustStateRegistry's bootstrap) ----------------
2511

2512
    /**
2513
     * Queries the {@code trust} repo directly for the current trust-state hash.
2514
     * Prefer {@link TrustStateRegistry#getCurrentHash()} in normal operation —
2515
     * this helper exists for tests and diagnostics.
2516
     *
2517
     * @return the current trust-state hash, or empty if none is set
2518
     */
2519
    Optional<String> readTrustRepoCurrentHash() {
2520
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(TRUST_REPO)) {
×
2521
            Value v = Utils.getObjectForPattern(conn, NPA.GRAPH, NPA.THIS_REPO,
×
2522
                    NPA_HAS_CURRENT_TRUST_STATE);
2523
            if (!(v instanceof IRI iri)) return Optional.empty();
×
2524
            String s = iri.stringValue();
×
2525
            if (!s.startsWith(NPAT.NAMESPACE)) return Optional.empty();
×
2526
            return Optional.of(s.substring(NPAT.NAMESPACE.length()));
×
2527
        } catch (Exception ex) {
×
2528
            logger.warn("AuthorityResolver: failed to read trust-repo current pointer: {}", ex.toString());
×
2529
            return Optional.empty();
×
2530
        }
2531
    }
2532

2533
    private static String abbrev(String hash) {
2534
        return hash.length() > 12 ? hash.substring(0, 12) + "…" : hash;
×
2535
    }
2536

2537
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc