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

knowledgepixels / nanopub-query / 28159148486

25 Jun 2026 09:03AM UTC coverage: 61.063% (-0.2%) from 61.236%
28159148486

Pull #133

github

web-flow
Merge 2cb13611d into 6c8216805
Pull Request #133: fix(trust): mirror authorizing introNanopub onto AccountState (#125 finding #4)

541 of 982 branches covered (55.09%)

Branch coverage included in aggregate %.

1584 of 2498 relevant lines covered (63.41%)

9.64 hits per line

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

20.03
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_VIA_NANOPUB = vf.createIRI(NPA.NAMESPACE, "viaNanopub");
15✔
72
    private static final IRI NPA_LOADED = vf.createIRI(NPA.NAMESPACE, "loaded");
15✔
73
    private static final IRI NPA_TO_LOAD = vf.createIRI(NPA.NAMESPACE, "toLoad");
15✔
74

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

85
    private static AuthorityResolver instance;
86

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

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

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

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

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

119
    // ---------------- Public entry points ----------------
120

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

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

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

206
    // ---------------- Full build ----------------
207

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

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

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

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

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

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

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

263
    // ---------------- Incremental cycle ----------------
264

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

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

332
        writeProcessedUpTo(graph, currentLoadCounter);
×
333

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

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

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

497
    /**
498
     * Cheap ASK: did any new {@code npa:RoleDeclaration} extraction land in the
499
     * load-number delta {@code (lastProcessed, ∞)}? Used by the late-arrival
500
     * trigger so an RD that arrives in the same cycle as a matching candidate
501
     * still gets validated.
502
     */
503
    boolean newRoleDeclarationsArrived(long lastProcessed) {
504
        String ask = String.format("""
×
505
                PREFIX npa: <%1$s>
506
                ASK {
507
                  GRAPH <%2$s> {
508
                    ?rd a npa:RoleDeclaration ;
509
                        npa:viaNanopub ?np .
510
                  }
511
                  GRAPH <%3$s> {
512
                    ?np npa:hasLoadNumber ?ln .
513
                    FILTER (?ln > %4$d)
514
                  }
515
                }
516
                """, NPA.NAMESPACE, SpacesVocab.SPACES_GRAPH, NPA.GRAPH, lastProcessed);
×
517
        return runAsk(ask);
×
518
    }
519

520
    /**
521
     * Cheap ASK: did any new {@code npa:PresetAssignment} or {@code npa:PresetDeclaration}
522
     * extraction land in the load-number delta {@code (lastProcessed, ∞)}? Drives the
523
     * late-arrival re-run so a preset assignment that arrives in the same cycle as its
524
     * declaration (or admin grant) still materializes, and so an arriving newer assignment
525
     * triggers the deactivation/latest-wins re-evaluation.
526
     */
527
    boolean newPresetAssignmentsArrived(long lastProcessed) {
528
        String ask = String.format("""
×
529
                PREFIX npa: <%1$s>
530
                ASK {
531
                  GRAPH <%2$s> {
532
                    ?x a ?t ;
533
                       npa:viaNanopub ?np .
534
                    FILTER (?t = npa:PresetAssignment || ?t = npa:PresetDeclaration)
535
                  }
536
                  GRAPH <%3$s> {
537
                    ?np npa:hasLoadNumber ?ln .
538
                    FILTER (?ln > %4$d)
539
                  }
540
                }
541
                """, NPA.NAMESPACE, SpacesVocab.SPACES_GRAPH, NPA.GRAPH, lastProcessed);
×
542
        return runAsk(ask);
×
543
    }
544

545
    // ---------------- Tier UPDATE loops ----------------
546

547
    /**
548
     * Per-tier inserted-triple tallies for one build or cycle. Counts the sum
549
     * of {@code (graphSize_after - graphSize_before)} across all iterations of
550
     * each tier's fixed-point INSERT loop — i.e. inserted *triples*, not
551
     * distinct subjects (a single RoleInstantiation insert writes 4–5 triples).
552
     *
553
     * <p>Used internally by the {@link #runIncrementalCycle structuralAdds}
554
     * boolean check (we only care whether any tier inserted at all).
555
     * Not what the log lines report: see {@link TierSubjectTotals} +
556
     * {@link #computeTierSubjectTotals} for the distinct-subject totals
557
     * surfaced to operators.
558
     */
559
    static final class TierInsertedTriples {
×
560
        int admin;
561
        int alias;
562
        int presetAttachment;
563
        int presetAssignmentRef;
564
        int attachment;
565
        int maintainer;
566
        int member;
567
        int observer;
568
        int subSpace;
569
        int subSpacePrefix;
570
        int maintainedResource;
571
        int governingSpaceRef;
572
    }
573

574
    /**
575
     * Snapshot of distinct-subject totals in a space-state graph at a moment
576
     * in time. Independent of which tier-loop added each subject.
577
     */
578
    record TierSubjectTotals(long adminRIs, long attachmentRAs, long nonAdminRIs) {}
36✔
579

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

657
    /**
658
     * Builds a publisher constraint requiring the publisher to be a validated holder
659
     * of the given tier's role (maintainer or member) in the target space.
660
     * Owns its own AccountState resolution so ?publisher is bound through the
661
     * targeted (pkh → agent) lookup rather than enumerated.
662
     */
663
    private static String publisherIsTieredRole(IRI tierClass) {
664
        // Re-keyed on the assignment's ref (alias → canonical already resolved by the
665
        // attachment tier). Relies on materialized non-admin RIs carrying their role
666
        // property (npa:regularProperty / npa:inverseProperty) — supplied by the
667
        // enrichment in nonAdminTierUpdate; without it this constraint matched nothing.
668
        return """
×
669
                ?acct a npa:AccountState ;
670
                      npa:pubkey ?pkh ;
671
                      npa:agent  ?publisher .
672
                ?tierRI a gen:RoleInstantiation ;
673
                        npa:forSpaceRef ?spaceRef ;
674
                        npa:forAgent ?publisher .
675
                ?rdT a npa:RoleDeclaration ;
676
                     npa:hasRoleType <%1$s> .
677
                { ?tierRI npa:regularProperty ?predT . ?rdT gen:hasRegularProperty ?predT . }
678
                UNION
679
                { ?tierRI npa:inverseProperty ?predT . ?rdT gen:hasInverseProperty ?predT . }
680
                """.formatted(tierClass);
×
681
    }
682

683
    /** Wraps {@link #runTierLoop} with tier-name context for logs/exceptions. */
684
    private int runTierLabeled(String tier, IRI graph, String sparqlUpdate) {
685
        try {
686
            return runTierLoop(graph, sparqlUpdate);
×
687
        } catch (RuntimeException ex) {
×
688
            logger.error("AuthorityResolver: tier={} failed with SPARQL UPDATE:\n{}\n", tier, sparqlUpdate, ex);
×
689
            throw ex;
×
690
        }
691
    }
692

693
    /**
694
     * Runs a single tier's INSERT to fixed point. Counts rows by probing
695
     * graph size before/after each INSERT; stops when the size doesn't change.
696
     *
697
     * @return total number of triples inserted by this tier across all iterations
698
     */
699
    int runTierLoop(IRI graph, String sparqlUpdate) {
700
        int total = 0;
×
701
        long before = graphSize(graph);
×
702
        while (true) {
703
            // Note: no explicit transaction wrapping here. In tests we observed that
704
            // HTTPRepository's RDF4J-transaction protocol silently no-op'd cross-graph
705
            // SPARQL UPDATEs with UNION sub-patterns inside conn.begin()/commit(),
706
            // while the same UPDATE POSTed directly to /statements applied correctly.
707
            // A bare prepareUpdate().execute() takes the direct /statements path and
708
            // runs the UPDATE atomically per SPARQL 1.1 semantics — which is all we
709
            // need; there's nothing else to commit atomically alongside the UPDATE.
710
            try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
711
                conn.prepareUpdate(QueryLanguage.SPARQL, sparqlUpdate).execute();
×
712
            }
713
            long after = graphSize(graph);
×
714
            long added = after - before;
×
715
            if (added <= 0) break;
×
716
            total += added;
×
717
            before = after;
×
718
        }
×
719
        return total;
×
720
    }
721

722
    private long graphSize(IRI graph) {
723
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
724
            return conn.size(graph);
×
725
        }
726
    }
727

728
    /**
729
     * Distinct-subject totals in the given space-state graph, broken down by
730
     * RoleInstantiation kind (admin-pinned vs not) and RoleAssignment.
731
     * Three SELECT-COUNT queries — cheap, called once per build/cycle for
732
     * the user-facing log line. Returns zeros on failure (logged) so a flaky
733
     * count read can't wedge the cycle.
734
     */
735
    TierSubjectTotals computeTierSubjectTotals(IRI graph) {
736
        long adminRIs       = countDistinctSubjects(graph, """
×
737
                ?ri a gen:RoleInstantiation ; npa:inverseProperty gen:hasAdmin .
738
                """, "ri");
739
        long attachmentRAs  = countDistinctSubjects(graph, """
×
740
                ?ra a gen:RoleAssignment .
741
                """, "ra");
742
        long nonAdminRIs    = countDistinctSubjects(graph, """
×
743
                ?ri a gen:RoleInstantiation .
744
                FILTER NOT EXISTS { ?ri npa:inverseProperty gen:hasAdmin }
745
                """, "ri");
746
        return new TierSubjectTotals(adminRIs, attachmentRAs, nonAdminRIs);
×
747
    }
748

749
    private long countDistinctSubjects(IRI graph, String wherePattern, String varName) {
750
        String query = String.format("""
×
751
                PREFIX npa: <%1$s>
752
                PREFIX gen: <%2$s>
753
                SELECT (COUNT(DISTINCT ?%3$s) AS ?n) WHERE {
754
                  GRAPH <%4$s> {
755
                    %5$s
756
                  }
757
                }
758
                """, NPA.NAMESPACE, GEN.NAMESPACE, varName, graph, wherePattern);
759
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO);
×
760
             TupleQueryResult r = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) {
×
761
            if (!r.hasNext()) return 0;
×
762
            return Long.parseLong(r.next().getBinding("n").getValue().stringValue());
×
763
        } catch (Exception ex) {
×
764
            logger.warn("AuthorityResolver: countDistinctSubjects on {} failed: {}",
×
765
                    graph, ex.toString());
×
766
            return 0;
×
767
        }
768
    }
769

770
    // ---------------- SPARQL templates ----------------
771

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

821
    /**
822
     * SPARQL triple pair (placed inside a {@code GRAPH npa:graph { ... }} block)
823
     * requiring the invalidating nanopub and its target to share a signing public
824
     * key — the self-retraction authority gate for issue #112. Without it, the
825
     * materializer honors {@code npx:invalidates}/{@code retracts}/{@code supersedes}
826
     * from <em>any</em> validly-signed nanopub, so any agent can erase another
827
     * space's materialized state (griefing/DoS of the view — fail-closed, no
828
     * privilege escalation, but real). Additions are already admin-gated; this is
829
     * the symmetric gate on removals.
830
     *
831
     * <p>Both {@code npa:hasValidSignatureForPublicKeyHash} triples live in
832
     * {@code npa:graph} of the spaces repo: the target via its own space-load, the
833
     * invalidator via the symmetric retractor propagation in
834
     * {@link com.knowledgepixels.query.NanopubLoader} (forward {@code
835
     * loadInvalidateStatements} + reverse {@code loadInvalidatorIntoSpacesRepo}),
836
     * so the join is populated regardless of load order.
837
     *
838
     * <p>"Same pubkey" is intentionally stricter than "same agent": a retraction
839
     * signed by a different key the author owns (key rotation) is not honored, and
840
     * cross-admin supersession is out of scope here (would need an admin-authority
841
     * arm). The pubkey-bridge variable is suffixed with {@code targetVar} so two
842
     * filters in one query (e.g. on {@code ?np} and {@code ?rdNp}) don't collide.
843
     *
844
     * @param invVar    invalidator nanopub variable name (no leading {@code ?})
845
     * @param targetVar invalidated-target nanopub variable name (no leading {@code ?})
846
     */
847
    private static String samePublisherClause(String invVar, String targetVar) {
848
        String pk = "?_invpk_" + targetVar;
9✔
849
        return "?" + invVar + " <" + NPA.HAS_VALID_SIGNATURE_FOR_PUBLIC_KEY_HASH + "> " + pk + " . "
30✔
850
                + "?" + targetVar + " <" + NPA.HAS_VALID_SIGNATURE_FOR_PUBLIC_KEY_HASH + "> " + pk + " .";
851
    }
852

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

972
    /**
973
     * Seed-survival filter for the admin tier (issue #110). The {@code hasRootAdmin}
974
     * seed is anchored to the root NPID, which is the immutable space-ref identity, so
975
     * it must survive supersession of the root <em>nanopub</em> by a continuation
976
     * revision (a later definition re-roots to the same ref via
977
     * {@code gen:hasRootDefinition} and so carries no {@code hasRootAdmin} of its own).
978
     * The previous {@code invalidationFilter("defNp")} dropped the seed the moment the
979
     * root revision was superseded, leaving the whole admin closure — and everything
980
     * cascading from it — unmaterialized for any space whose definition had ever been
981
     * updated.
982
     *
983
     * <p>Expressed positively: the seed survives iff the space ref still has at least
984
     * one non-invalidated {@link SpacesVocab#SPACE_DEFINITION}. A fully-retracted ref
985
     * (every definition invalidated) has no live definition, so the {@code FILTER
986
     * EXISTS} fails and the seed correctly disappears. Anchored on the already-bound
987
     * {@code ?spaceRef}, so it's a targeted lookup over that ref's (few) definitions.
988
     */
989
    private static String spaceRefAliveFilter() {
990
        return """
33✔
991
                FILTER EXISTS {
992
                  GRAPH <%1$s> {
993
                    ?liveDef a npa:SpaceDefinition ;
994
                             npa:forSpaceRef ?spaceRef ;
995
                             npa:viaNanopub  ?liveNp .
996
                  }
997
                  %2$s
998
                }
999
                """.formatted(SpacesVocab.SPACES_GRAPH, invalidationFilter("liveNp"));
9✔
1000
    }
1001

1002
    /**
1003
     * {@code gen:hasRole} attachment validation: an attachment is validated iff its
1004
     * publisher is already a validated admin of the target space. Adds
1005
     * {@code gen:RoleAssignment} rows to the space-state graph.
1006
     */
1007
    static String attachmentValidationUpdate(IRI graph, long lastProcessed) {
1008
        // Ref-keyed (see doc/design-spaceref-isolation.md). The attachment names a bare
1009
        // Space IRI; it is validated per-ref for every ref of that IRI whose admin set
1010
        // contains the publisher (direct), or — when the named IRI is an owl:sameAs alias
1011
        // — for the canonical ref it maps to (issue #113). ?targetRef is the ref the
1012
        // RoleAssignment attaches to; the inserted subject is minted per (?ra, ?targetRef)
1013
        // so one attachment validating into N refs yields N distinct rows.
1014
        // TRANSITIONAL-DUAL-EMIT (Phase 4: remove): forSpace (the attached IRI, possibly an
1015
        // alias) is kept so the non-admin tier can probe the IRI-keyed instantiations
1016
        // naming it, and so pre-ref read queries keep functioning on a mixed-version fleet.
1017
        return """
69✔
1018
                PREFIX npa:  <%1$s>
1019
                PREFIX gen:  <%2$s>
1020
                INSERT { GRAPH <%3$s> {
1021
                  ?ra2 a gen:RoleAssignment ;
1022
                       npa:forSpaceRef ?targetRef ;
1023
                       npa:forSpace ?space ;
1024
                       gen:hasRole  ?role ;
1025
                       npa:viaNanopub ?np .
1026
                } }
1027
                WHERE {
1028
                  GRAPH <%4$s> {
1029
                    ?ra a gen:RoleAssignment ;
1030
                        npa:forSpace ?space ;
1031
                        gen:hasRole  ?role ;
1032
                        npa:pubkeyHash ?pkh ;
1033
                        npa:viaNanopub ?np .
1034
                  }
1035
                  GRAPH <%7$s> {
1036
                    ?np npa:hasLoadNumber ?ln .
1037
                    FILTER (?ln > %5$d)
1038
                  }
1039
                  GRAPH <%3$s> {
1040
                    ?acct a npa:AccountState ;
1041
                          npa:agent  ?publisher ;
1042
                          npa:pubkey ?pkh .
1043
                  }
1044
                  # Per-ref admin gate. ?targetRef = a ref of ?space the publisher admins
1045
                  # (direct), or the canonical ref ?space is an owl:sameAs alias of.
1046
                  {
1047
                    GRAPH <%4$s> { ?targetRef npa:spaceIri ?space . }
1048
                    GRAPH <%3$s> {
1049
                      ?adminRI a gen:RoleInstantiation ;
1050
                               npa:forSpaceRef ?targetRef ;
1051
                               npa:inverseProperty gen:hasAdmin ;
1052
                               npa:forAgent ?publisher .
1053
                    }
1054
                  }
1055
                  UNION
1056
                  {
1057
                    GRAPH <%3$s> {
1058
                      ?space npa:sameAsSpace ?targetRef .
1059
                      ?adminRI a gen:RoleInstantiation ;
1060
                               npa:forSpaceRef ?targetRef ;
1061
                               npa:inverseProperty gen:hasAdmin ;
1062
                               npa:forAgent ?publisher .
1063
                    }
1064
                  }
1065
                  BIND(IRI(CONCAT(STR(?ra), "__", ENCODE_FOR_URI(STR(?targetRef)))) AS ?ra2)
1066
                  %6$s
1067
                  FILTER NOT EXISTS { GRAPH <%3$s> {
1068
                    ?existing a gen:RoleAssignment ;
1069
                              npa:forSpaceRef ?targetRef ;
1070
                              gen:hasRole  ?role .
1071
                  } }
1072
                }
1073
                """.formatted(
3✔
1074
                NPA.NAMESPACE,
1075
                GEN.NAMESPACE,
1076
                graph,
1077
                SpacesVocab.SPACES_GRAPH,
1078
                lastProcessed,
15✔
1079
                invalidationFilter("np"),
18✔
1080
                NPA.GRAPH);
1081
    }
1082

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

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

1359
    /**
1360
     * Non-admin tier publisher constraints (inserted as a SPARQL sub-pattern).
1361
     * Each constraint owns the AccountState (pkh → agent) lookup so the join
1362
     * variable is bound through a targeted pattern. The observer-self variant
1363
     * binds {@code npa:agent ?agent} directly — no separate {@code ?publisher}
1364
     * variable, no post-join equality filter — which lets the planner anchor
1365
     * the AccountState lookup on the already-bound {@code ?agent} instead of
1366
     * enumerating all approved publishers and filtering at the end.
1367
     */
1368
    static final String PUBLISHER_IS_ADMIN = """
1369
            ?acct a npa:AccountState ;
1370
                  npa:pubkey ?pkh ;
1371
                  npa:agent  ?publisher .
1372
            # Admin of the assignment's ref. The ref already resolves alias →
1373
            # canonical (the attachment tier bound ?spaceRef through the owl:sameAs
1374
            # alias edge for aliased IRIs, issue #113), so no alias arm is needed here.
1375
            ?adminRI a gen:RoleInstantiation ;
1376
                     npa:forSpaceRef ?spaceRef ;
1377
                     npa:inverseProperty gen:hasAdmin ;
1378
                     npa:forAgent ?publisher .
1379
            """;
1380

1381
    /** Observer self-evidence: the assignee's own pubkey signed the instantiation. */
1382
    static final String PUBLISHER_IS_SELF = """
1383
            ?acct a npa:AccountState ;
1384
                  npa:pubkey ?pkh ;
1385
                  npa:agent  ?agent .
1386
            """;
1387

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

1561
    /**
1562
     * Sub-space admit pass. Copies validated {@code npa:SubSpaceDeclaration}
1563
     * extraction rows into the space-state graph (preserving the {@code npasub:}
1564
     * subject) and emits convenience {@code <child> npa:isSubSpaceOf <parent>} and
1565
     * {@code <parent> npa:hasSubSpace <child>} direct triples. Two satisfaction
1566
     * modes joined by UNION:
1567
     * <ul>
1568
     *   <li>Mode A — the declaration's publisher is a validated admin of both the
1569
     *       child and the parent space.</li>
1570
     *   <li>Mode B — a different non-invalidated declaration for the same
1571
     *       {@code (child, parent)} pair exists, and the two publishers between
1572
     *       them cover both admin sides (i.e. one of them is admin of the child,
1573
     *       one of them is admin of the parent — possibly the same one twice if
1574
     *       both happen to be admin of both).</li>
1575
     * </ul>
1576
     *
1577
     * <p>Mode-B late-arrival: when only the partner declaration is new in this
1578
     * cycle (the primary is older than {@code lastProcessed}), the load-number
1579
     * filter on {@code ?np} excludes the candidate. The late-arrival sweep
1580
     * ({@link #runDownstreamWithoutLoadFilter}) re-runs this pass without the
1581
     * load filter and catches it.
1582
     */
1583
    static String subSpaceAdmitUpdate(IRI graph, long lastProcessed) {
1584
        return """
69✔
1585
                PREFIX npa: <%1$s>
1586
                PREFIX gen: <%2$s>
1587
                INSERT { GRAPH <%3$s> {
1588
                  ?d a npa:SubSpaceDeclaration ;
1589
                     npa:childSpace  ?child ;
1590
                     npa:parentSpace ?parent ;
1591
                     npa:viaNanopub  ?np .
1592
                  ?childRef  npa:isSubSpaceOf ?parentRef .
1593
                  ?parentRef npa:hasSubSpace  ?childRef  .
1594
                  # Reified per-(nanopub, ref-pair) provenance link (issue #125 finding #5):
1595
                  # carries npa:viaNanopub plus both the ref and IRI endpoints, so the
1596
                  # invalidation cleanup can drop the convenience edges below once no
1597
                  # surviving link backs them — instead of leaving them sticky until the
1598
                  # next periodic full rebuild.
1599
                  ?ssLink a npa:SubSpaceLink ;
1600
                          npa:viaNanopub     ?np ;
1601
                          npa:childSpaceRef  ?childRef ;
1602
                          npa:parentSpaceRef ?parentRef ;
1603
                          npa:childSpace     ?child ;
1604
                          npa:parentSpace    ?parent .
1605
                  # TRANSITIONAL-DUAL-EMIT (Phase 1.5; remove in Phase 4): IRI-valued
1606
                  # sub-space edge alongside the ref-to-ref one, so pre-ref published
1607
                  # queries that key on the bare Space IRI keep binding on a mixed-version
1608
                  # fleet. See doc/report-2026-06-12-mixed-fleet-spaceref-breakage.md.
1609
                  ?child  npa:isSubSpaceOf ?parent .
1610
                  ?parent npa:hasSubSpace  ?child  .
1611
                } }
1612
                WHERE {
1613
                  # 1. Anchor: candidate declarations from the extraction graph.
1614
                  GRAPH <%4$s> {
1615
                    ?d a npa:SubSpaceDeclaration ;
1616
                       npa:childSpace  ?child ;
1617
                       npa:parentSpace ?parent ;
1618
                       npa:pubkeyHash  ?pkh ;
1619
                       npa:viaNanopub  ?np .
1620
                  }
1621
                  # 2. Mirror: resolve ?pkh → ?publisher via the trust-approved row.
1622
                  GRAPH <%3$s> {
1623
                    ?acct a npa:AccountState ;
1624
                          npa:pubkey ?pkh ;
1625
                          npa:agent  ?publisher .
1626
                  }
1627
                  # 3. Authority gate, ref-keyed. The edge is emitted ref-to-ref between
1628
                  #    the child ref and parent ref the authorizing admin governs; the
1629
                  #    admin rows' dual-emitted npa:forSpace binds the refs to the child /
1630
                  #    parent IRIs (cross-product when an IRI has several governed refs).
1631
                  {
1632
                    # Mode A — publisher is admin of BOTH a child ref and a parent ref.
1633
                    GRAPH <%3$s> {
1634
                      ?riC a gen:RoleInstantiation ;
1635
                           npa:inverseProperty gen:hasAdmin ;
1636
                           npa:forSpace ?child ;
1637
                           npa:forSpaceRef ?childRef ;
1638
                           npa:forAgent ?publisher .
1639
                      ?riP a gen:RoleInstantiation ;
1640
                           npa:inverseProperty gen:hasAdmin ;
1641
                           npa:forSpace ?parent ;
1642
                           npa:forSpaceRef ?parentRef ;
1643
                           npa:forAgent ?publisher .
1644
                    }
1645
                  }
1646
                  UNION
1647
                  {
1648
                    # Mode B — co-declaration whose publisher covers the side this
1649
                    # one's publisher doesn't. Between {publisher, publisher2},
1650
                    # both admin sides must be covered.
1651
                    GRAPH <%4$s> {
1652
                      ?d2 a npa:SubSpaceDeclaration ;
1653
                          npa:childSpace  ?child ;
1654
                          npa:parentSpace ?parent ;
1655
                          npa:pubkeyHash  ?pkh2 ;
1656
                          npa:viaNanopub  ?np2 .
1657
                      FILTER (?np2 != ?np)
1658
                    }
1659
                    %8$s
1660
                    GRAPH <%3$s> {
1661
                      ?acct2 a npa:AccountState ;
1662
                             npa:pubkey ?pkh2 ;
1663
                             npa:agent  ?publisher2 .
1664
                      ?riA a gen:RoleInstantiation ;
1665
                           npa:inverseProperty gen:hasAdmin ;
1666
                           npa:forSpace ?child ;
1667
                           npa:forSpaceRef ?childRef .
1668
                      { ?riA npa:forAgent ?publisher } UNION { ?riA npa:forAgent ?publisher2 }
1669
                      ?riB a gen:RoleInstantiation ;
1670
                           npa:inverseProperty gen:hasAdmin ;
1671
                           npa:forSpace ?parent ;
1672
                           npa:forSpaceRef ?parentRef .
1673
                      { ?riB npa:forAgent ?publisher } UNION { ?riB npa:forAgent ?publisher2 }
1674
                    }
1675
                  }
1676
                  # 4. Invalidation filter on the primary declaration's nanopub.
1677
                  %6$s
1678
                  # 5. Load-number filter on bound ?np.
1679
                  GRAPH <%7$s> {
1680
                    ?np npa:hasLoadNumber ?ln .
1681
                    FILTER (?ln > %5$d)
1682
                  }
1683
                  # 6. Mint the per-(nanopub, ref-pair) provenance link IRI and dedup on it
1684
                  #    (not on the bare edge). Keyed on ?np so every backing declaration of
1685
                  #    the same ref-pair records its own removable link; the convenience
1686
                  #    edges above are re-asserted idempotently.
1687
                  BIND(IRI(CONCAT("http://purl.org/nanopub/admin/spacelink/subspace/",
1688
                                  MD5(CONCAT(STR(?np), "|", STR(?childRef), "|", STR(?parentRef))))) AS ?ssLink)
1689
                  FILTER NOT EXISTS { GRAPH <%3$s> {
1690
                    ?ssLink a npa:SubSpaceLink .
1691
                  } }
1692
                }
1693
                """.formatted(
3✔
1694
                NPA.NAMESPACE,
1695
                GEN.NAMESPACE,
1696
                graph,
1697
                SpacesVocab.SPACES_GRAPH,
1698
                lastProcessed,
15✔
1699
                invalidationFilter("np"),
27✔
1700
                NPA.GRAPH,
1701
                invalidationFilter("np2"));
6✔
1702
    }
1703

1704
    /**
1705
     * Maintained-resource admit pass. Copies validated
1706
     * {@code npa:MaintainedResourceDeclaration} extraction rows into the space-state
1707
     * graph (preserving the {@code npamrd:} subject) and emits convenience
1708
     * {@code <r> npa:isMaintainedBy <s>} and {@code <s> npa:hasMaintainedResource <r>}
1709
     * direct triples. Single satisfaction mode:
1710
     * <ul>
1711
     *   <li>Mode A — the declaration's publisher is a validated admin of the
1712
     *       maintaining space.</li>
1713
     * </ul>
1714
     *
1715
     * <p>No Mode B because only one space is involved; the two-sides-must-be-covered
1716
     * concern that drives sub-space Mode B doesn't apply. Late-arrival is still
1717
     * possible (declaration lands before the publisher's admin grant becomes valid):
1718
     * the load-number filter on {@code ?np} excludes the candidate, and the
1719
     * late-arrival sweep ({@link #runDownstreamWithoutLoadFilter}) re-runs this pass
1720
     * without the load filter and catches it.
1721
     */
1722
    static String maintainedResourceAdmitUpdate(IRI graph, long lastProcessed) {
1723
        return """
69✔
1724
                PREFIX npa: <%1$s>
1725
                PREFIX gen: <%2$s>
1726
                INSERT { GRAPH <%3$s> {
1727
                  ?d a npa:MaintainedResourceDeclaration ;
1728
                     npa:resourceIri     ?r ;
1729
                     npa:maintainerSpace ?s ;
1730
                     npa:viaNanopub      ?np .
1731
                  ?r npa:isMaintainedBy        ?sRef .
1732
                  ?sRef npa:hasMaintainedResource ?r .
1733
                  # Uniform ref-valued resource→governing-space-ref edge (issue #130). The
1734
                  # same predicate the reflexive space self-edge uses, so a single consumer
1735
                  # hop covers both "resource maintained by space S" and "resource IS a space".
1736
                  # Backed by the same MaintainedResourceLink below, so the invalidation
1737
                  # cleanup sweeps it alongside isMaintainedBy.
1738
                  ?r npa:hasGoverningSpaceRef  ?sRef .
1739
                  # Reified per-(nanopub, resource→ref) provenance link (issue #125 finding
1740
                  # #5): lets the invalidation cleanup drop the convenience edges below once
1741
                  # no surviving link backs them, instead of leaving them sticky.
1742
                  ?mrLink a npa:MaintainedResourceLink ;
1743
                          npa:viaNanopub         ?np ;
1744
                          npa:resourceIri        ?r ;
1745
                          npa:maintainerSpaceRef ?sRef ;
1746
                          npa:maintainerSpace    ?s .
1747
                  # TRANSITIONAL-DUAL-EMIT (Phase 1.5; remove in Phase 4): IRI-valued
1748
                  # maintained-resource edge alongside the resource→ref one, so pre-ref
1749
                  # published queries (e.g. get-view-displays' maintained hop) keep binding
1750
                  # on a mixed-version fleet. This is the edge whose absence broke 1.15.0 —
1751
                  # see doc/report-2026-06-12-mixed-fleet-spaceref-breakage.md.
1752
                  ?r npa:isMaintainedBy        ?s .
1753
                  ?s npa:hasMaintainedResource ?r .
1754
                } }
1755
                WHERE {
1756
                  # 1. Anchor: candidate declarations from the extraction graph.
1757
                  GRAPH <%4$s> {
1758
                    ?d a npa:MaintainedResourceDeclaration ;
1759
                       npa:resourceIri     ?r ;
1760
                       npa:maintainerSpace ?s ;
1761
                       npa:pubkeyHash      ?pkh ;
1762
                       npa:viaNanopub      ?np .
1763
                  }
1764
                  # 2. Mirror: resolve ?pkh → ?publisher via the trust-approved row.
1765
                  GRAPH <%3$s> {
1766
                    ?acct a npa:AccountState ;
1767
                          npa:pubkey ?pkh ;
1768
                          npa:agent  ?publisher .
1769
                    # 3. Authority gate (Mode A only): publisher is admin of a ref of the
1770
                    #    maintaining space. ?sRef = that ref (resource → ref edge).
1771
                    ?riA a gen:RoleInstantiation ;
1772
                         npa:inverseProperty gen:hasAdmin ;
1773
                         npa:forSpace ?s ;
1774
                         npa:forSpaceRef ?sRef ;
1775
                         npa:forAgent ?publisher .
1776
                  }
1777
                  # 4. Invalidation filter on the declaration's nanopub.
1778
                  %6$s
1779
                  # 5. Load-number filter on bound ?np.
1780
                  GRAPH <%7$s> {
1781
                    ?np npa:hasLoadNumber ?ln .
1782
                    FILTER (?ln > %5$d)
1783
                  }
1784
                  # 6. Mint the per-(nanopub, resource→ref) provenance link IRI and dedup on
1785
                  #    it (not on the bare edge), so every backing declaration records its own
1786
                  #    removable link; the convenience edges above are re-asserted idempotently.
1787
                  BIND(IRI(CONCAT("http://purl.org/nanopub/admin/spacelink/maintained/",
1788
                                  MD5(CONCAT(STR(?np), "|", STR(?r), "|", STR(?sRef))))) AS ?mrLink)
1789
                  FILTER NOT EXISTS { GRAPH <%3$s> {
1790
                    ?mrLink a npa:MaintainedResourceLink .
1791
                  } }
1792
                }
1793
                """.formatted(
3✔
1794
                NPA.NAMESPACE,
1795
                GEN.NAMESPACE,
1796
                graph,
1797
                SpacesVocab.SPACES_GRAPH,
1798
                lastProcessed,
15✔
1799
                invalidationFilter("np"),
18✔
1800
                NPA.GRAPH);
1801
    }
1802

1803
    /**
1804
     * Space-alias admit pass (issue #113). Copies validated
1805
     * {@code npa:SpaceAliasDeclaration} extraction rows into the space-state graph
1806
     * (preserving the {@code npaalias:} subject) and emits the directional
1807
     * {@code <alias> npa:sameAsSpace <canonical>} edge consumed by the alias-aware
1808
     * admin-authority lookups in {@link #attachmentValidationUpdate},
1809
     * {@link #PUBLISHER_IS_ADMIN}, and {@link #publisherIsTieredRole}.
1810
     *
1811
     * <p>Two gates, both read against the (already-settled) admin closure in the
1812
     * space-state graph:
1813
     * <ul>
1814
     *   <li><b>Authority</b> — the declaration's publisher (resolved via the mirrored
1815
     *       trust-approved {@code AccountState}) is a validated admin of the
1816
     *       <em>canonical</em> space. The alias is declared inside the canonical
1817
     *       space's own {@code gen:Space} nanopub, so this is the same evidence rule
1818
     *       as a {@code gen:hasRole} attachment.</li>
1819
     *   <li><b>Anti-hijack</b> — the alias must not be an independently-governed live
1820
     *       space: it must have no admin who is not also an admin of the canonical
1821
     *       space ({@code admins(alias) ⊆ admins(canonical)}). The common rename case
1822
     *       (the alias's own definition was superseded, so it has no live admin
1823
     *       closure) passes trivially; an attacker publishing
1824
     *       {@code <evil> owl:sameAs <activeSpace>} is rejected because the active
1825
     *       space has admins not in evil's set.</li>
1826
     * </ul>
1827
     *
1828
     * <p>Late-arrival: when the canonical admin grant only becomes valid in the same
1829
     * cycle as the declaration, the load-number filter on {@code ?np} excludes the
1830
     * candidate; the late-arrival sweep ({@link #runDownstreamWithoutLoadFilter})
1831
     * re-runs this pass without the load filter and catches it.
1832
     */
1833
    static String aliasAdmitUpdate(IRI graph, long lastProcessed) {
1834
        // Ref-keyed (see doc/design-spaceref-isolation.md). The declaration names bare
1835
        // canonical/alias IRIs. It is admitted per canonical *ref* whose admin set
1836
        // contains the publisher; the emitted edge is ref-valued on the canonical side
1837
        // (<alias> npa:sameAsSpace <canonicalRef>), which is what the alias-aware admin
1838
        // lookups in the attachment tier consume. Anti-hijack compares the alias IRI's
1839
        // admins against that specific canonical ref's admins — strictly tighter than the
1840
        // old bare-IRI form.
1841
        return """
69✔
1842
                PREFIX npa: <%1$s>
1843
                PREFIX gen: <%2$s>
1844
                INSERT { GRAPH <%3$s> {
1845
                  ?d a npa:SpaceAliasDeclaration ;
1846
                     npa:canonicalSpace ?canonical ;
1847
                     npa:aliasSpace     ?alias ;
1848
                     npa:viaNanopub     ?np .
1849
                  ?alias npa:sameAsSpace ?canonRef .
1850
                  # Reified per-(nanopub, alias→canonical ref) provenance link (issue #125
1851
                  # finding #5). The alias edge feeds the admin-authority closure, so this
1852
                  # is the load-bearing case: the cleanup can now drop the edge when its
1853
                  # declaration is invalidated, rather than letting admin authority outlive
1854
                  # a retraction until the next periodic full rebuild.
1855
                  ?alLink a npa:SpaceAliasLink ;
1856
                          npa:viaNanopub        ?np ;
1857
                          npa:aliasSpace        ?alias ;
1858
                          npa:canonicalSpaceRef ?canonRef ;
1859
                          npa:canonicalSpace    ?canonical .
1860
                  # TRANSITIONAL-DUAL-EMIT (Phase 1.5; remove in Phase 4): IRI-valued
1861
                  # alias edge alongside the ref-valued one, so pre-ref published queries
1862
                  # that resolve owl:sameAs by bare canonical IRI keep binding on a
1863
                  # mixed-version fleet. Internal alias-aware lookups (attachment tier)
1864
                  # join through npa:forSpaceRef, which is ref-valued, so this IRI-valued
1865
                  # object never satisfies them — it is inert internally, read-only for
1866
                  # legacy consumers. See doc/report-2026-06-12-mixed-fleet-spaceref-breakage.md.
1867
                  ?alias npa:sameAsSpace ?canonical .
1868
                } }
1869
                WHERE {
1870
                  # 1. Anchor: candidate alias declarations from the extraction graph.
1871
                  GRAPH <%4$s> {
1872
                    ?d a npa:SpaceAliasDeclaration ;
1873
                       npa:canonicalSpace ?canonical ;
1874
                       npa:aliasSpace     ?alias ;
1875
                       npa:pubkeyHash     ?pkh ;
1876
                       npa:viaNanopub     ?np .
1877
                  }
1878
                  # 2. Authority gate per canonical ref: ?canonRef is a ref of ?canonical
1879
                  #    whose admin set contains the declaration's publisher.
1880
                  GRAPH <%4$s> { ?canonRef npa:spaceIri ?canonical . }
1881
                  GRAPH <%3$s> {
1882
                    ?acct a npa:AccountState ;
1883
                          npa:pubkey ?pkh ;
1884
                          npa:agent  ?publisher .
1885
                    ?adminRI a gen:RoleInstantiation ;
1886
                             npa:inverseProperty gen:hasAdmin ;
1887
                             npa:forSpaceRef ?canonRef ;
1888
                             npa:forAgent ?publisher .
1889
                  }
1890
                  # 3. Anti-hijack: the alias IRI must have no admin who is not also an
1891
                  #    admin of this canonical ref (admins(alias) ⊆ admins(canonRef)).
1892
                  FILTER NOT EXISTS {
1893
                    GRAPH <%3$s> {
1894
                      ?aliasAdmin a gen:RoleInstantiation ;
1895
                                  npa:inverseProperty gen:hasAdmin ;
1896
                                  npa:forSpace ?alias ;
1897
                                  npa:forAgent ?otherAgent .
1898
                    }
1899
                    FILTER NOT EXISTS {
1900
                      GRAPH <%3$s> {
1901
                        ?canonAdmin a gen:RoleInstantiation ;
1902
                                    npa:inverseProperty gen:hasAdmin ;
1903
                                    npa:forSpaceRef ?canonRef ;
1904
                                    npa:forAgent ?otherAgent .
1905
                      }
1906
                    }
1907
                  }
1908
                  # 4. Invalidation filter on the declaration's nanopub.
1909
                  %6$s
1910
                  # 5. Load-number filter on bound ?np.
1911
                  GRAPH <%7$s> {
1912
                    ?np npa:hasLoadNumber ?ln .
1913
                    FILTER (?ln > %5$d)
1914
                  }
1915
                  # 6. Mint the per-(nanopub, alias→canonical ref) provenance link IRI and
1916
                  #    dedup on it (not on the bare edge), so every backing declaration records
1917
                  #    its own removable link; the convenience edges above are re-asserted
1918
                  #    idempotently.
1919
                  BIND(IRI(CONCAT("http://purl.org/nanopub/admin/spacelink/alias/",
1920
                                  MD5(CONCAT(STR(?np), "|", STR(?alias), "|", STR(?canonRef))))) AS ?alLink)
1921
                  FILTER NOT EXISTS { GRAPH <%3$s> {
1922
                    ?alLink a npa:SpaceAliasLink .
1923
                  } }
1924
                }
1925
                """.formatted(
3✔
1926
                NPA.NAMESPACE,
1927
                GEN.NAMESPACE,
1928
                graph,
1929
                SpacesVocab.SPACES_GRAPH,
1930
                lastProcessed,
15✔
1931
                invalidationFilter("np"),
18✔
1932
                NPA.GRAPH);
1933
    }
1934

1935
    /**
1936
     * URL-prefix sub-space fallback admit pass. For every pair of {@code SpaceRef}
1937
     * aggregates where the child's {@code npa:hasIdPrefix} matches the parent's
1938
     * {@code npa:spaceIri}, emits convenience {@code <child> npa:isSubSpaceOf <parent>}
1939
     * and {@code <parent> npa:hasSubSpace <child>} direct triples plus a reified
1940
     * {@code npa:DerivedSubSpaceLink} tag carrying {@code npa:derivationKind
1941
     * npa:byUrlPrefix} so consumers can hide derived edges.
1942
     *
1943
     * <p>Per-child suppression: any validated {@code npa:SubSpaceDeclaration} on the
1944
     * child in {@code npass:<…>} suppresses every fallback edge for that child.
1945
     * Suppression checks the validated set (not raw extraction-graph declarations)
1946
     * so an unapproved or in-flight Mode B declaration doesn't silently hide both
1947
     * the URL-prefix fallback and the (still-invalid) explicit relation.
1948
     *
1949
     * <p>Run order: must run after {@link #subSpaceAdmitUpdate} commits in the
1950
     * same cycle so the suppression check sees this cycle's freshly-validated
1951
     * declarations.
1952
     *
1953
     * <p>No load-number filter: the fallback depends on which Spaces exist (parent
1954
     * + child {@code SpaceRef}s), not on which were just added. Always full-scan;
1955
     * the dedup {@code FILTER NOT EXISTS} on the tag IRI prevents re-insertion.
1956
     *
1957
     * <p>No invalidation handling: derived edges have no source nanopub. Two
1958
     * staleness modes: (a) child later gets first validated declaration → old
1959
     * derived edges stay sticky until the next periodic rebuild (same policy as
1960
     * admin-RI invalidation); (b) child loses last validated declaration → the
1961
     * regular fallback pass on the next cycle re-engages, adds derived edges
1962
     * incrementally, no rebuild needed.
1963
     */
1964
    static String subSpacePrefixFallbackUpdate(IRI graph) {
1965
        return """
48✔
1966
                PREFIX npa: <%1$s>
1967
                INSERT { GRAPH <%2$s> {
1968
                  ?childRef  npa:isSubSpaceOf ?parentRef .
1969
                  ?parentRef npa:hasSubSpace  ?childRef  .
1970
                  # TRANSITIONAL-DUAL-EMIT (Phase 1.5; remove in Phase 4): IRI-valued
1971
                  # derived sub-space edge alongside the ref-to-ref one, mirroring the
1972
                  # explicit sub-space pass, so pre-ref published queries keep binding on a
1973
                  # mixed-version fleet. See doc/report-2026-06-12-mixed-fleet-spaceref-breakage.md.
1974
                  ?child  npa:isSubSpaceOf ?parent .
1975
                  ?parent npa:hasSubSpace  ?child  .
1976
                  ?tagIri a npa:DerivedSubSpaceLink ;
1977
                          npa:childSpace     ?child ;
1978
                          npa:parentSpace    ?parent ;
1979
                          # Ref endpoints too (issue #125 finding #5), so the sub-space
1980
                          # orphan-sweep recognizes a prefix-derived ref edge as backed and
1981
                          # never deletes it. Derived links have no source nanopub, so they
1982
                          # are never invalidation-deleted; the fallback self-heals each cycle.
1983
                          npa:childSpaceRef  ?childRef ;
1984
                          npa:parentSpaceRef ?parentRef ;
1985
                          npa:derivationKind npa:byUrlPrefix .
1986
                } }
1987
                WHERE {
1988
                  # 1. Anchor: child SpaceRef → its path-prefixes (extracted at load
1989
                  #    time from the Space IRI; see SpacesExtractor.enumerateIdPrefixes).
1990
                  GRAPH <%3$s> {
1991
                    ?childRef  npa:spaceIri    ?child ;
1992
                               npa:hasIdPrefix ?parent .
1993
                    # 2. Parent SpaceRef must exist for the same IRI as the prefix.
1994
                    ?parentRef npa:spaceIri    ?parent .
1995
                  }
1996
                  # 3. Suppress fallback for any child that has a validated declaration
1997
                  #    in this state graph. Per-child IRI, all-or-nothing.
1998
                  FILTER NOT EXISTS {
1999
                    GRAPH <%2$s> {
2000
                      ?d a npa:SubSpaceDeclaration ;
2001
                         npa:childSpace ?child .
2002
                    }
2003
                  }
2004
                  # 4. Mint a deterministic tag IRI per (child ref, parent ref) — the edge
2005
                  #    is emitted ref-to-ref, so the tag and dedup are per ref-pair.
2006
                  BIND(IRI(CONCAT("http://purl.org/nanopub/admin/derivedlink/",
2007
                                  MD5(CONCAT(STR(?childRef), "|", STR(?parentRef))))) AS ?tagIri)
2008
                  # 5. Dedup: don't re-insert if this tag is already present.
2009
                  FILTER NOT EXISTS {
2010
                    GRAPH <%2$s> {
2011
                      ?tagIri a npa:DerivedSubSpaceLink .
2012
                    }
2013
                  }
2014
                }
2015
                """.formatted(
3✔
2016
                NPA.NAMESPACE,
2017
                graph,
2018
                SpacesVocab.SPACES_GRAPH);
2019
    }
2020

2021
    /**
2022
     * Reflexive governing-space-ref pass (issue #130). For every {@code SpaceRef}
2023
     * aggregate {@code ?spaceRef} (identified by {@code npa:spaceIri ?space} in the
2024
     * extraction graph), emits {@code <space> npa:hasGoverningSpaceRef <spaceRef>} into
2025
     * the space-state graph — the space pointing at its own ref through the same predicate
2026
     * a maintained resource uses to point at its maintaining space's ref (emitted in
2027
     * {@link #maintainedResourceAdmitUpdate}).
2028
     *
2029
     * <p>This removes the zero-hop special case from consumer authority gates: instead of
2030
     * {@code ?resource npa:isMaintainedBy? ?space} (a bare-IRI optional path that breaks
2031
     * once the hop is ref-valued), a consumer does a single mandatory
2032
     * {@code ?resource npa:hasGoverningSpaceRef ?spaceRef} that binds whether the resource
2033
     * is a maintained resource or a space itself. A space IRI claimed by several refs emits
2034
     * one edge per ref — the non-ref consumer variant's merged-across-refs behaviour falls
2035
     * out naturally; the ref variant pins {@code ?passedRef}.
2036
     *
2037
     * <p>Self-healing, like {@link #subSpacePrefixFallbackUpdate}: the edge has no source
2038
     * nanopub (it follows purely from a {@code SpaceRef} existing), so there is no
2039
     * invalidation handling and no load-number filter — always full-scan, with the dedup
2040
     * {@code FILTER NOT EXISTS} on the edge preventing re-insertion. A {@code SpaceRef}
2041
     * disappearing is itself a structural-rebuild event, which clears its reflexive edge.
2042
     */
2043
    static String governingSpaceRefReflexiveUpdate(IRI graph) {
2044
        return """
48✔
2045
                PREFIX npa: <%1$s>
2046
                INSERT { GRAPH <%2$s> {
2047
                  ?space npa:hasGoverningSpaceRef ?spaceRef .
2048
                } }
2049
                WHERE {
2050
                  GRAPH <%3$s> { ?spaceRef npa:spaceIri ?space . }
2051
                  FILTER NOT EXISTS { GRAPH <%2$s> {
2052
                    ?space npa:hasGoverningSpaceRef ?spaceRef .
2053
                  } }
2054
                }
2055
                """.formatted(
3✔
2056
                NPA.NAMESPACE,
2057
                graph,
2058
                SpacesVocab.SPACES_GRAPH);
2059
    }
2060

2061
    // ---------------- Invalidation templates (incremental cycle) ----------------
2062

2063
    /**
2064
     * WHERE clause shared by the admin-RI invalidation ASK precheck and the
2065
     * matching DELETE. Identifies admin-tier {@code gen:RoleInstantiation} rows
2066
     * in the space-state graph whose {@code npa:viaNanopub} is the target of an
2067
     * {@code npx:invalidates} triple in {@code npa:graph} whose subject nanopub
2068
     * has a load number in {@code (lastProcessed, ∞)}.
2069
     */
2070
    static String adminInvalidationCheckWhere(IRI graph, long lastProcessed) {
2071
        return String.format("""
60✔
2072
                  GRAPH <%1$s> {
2073
                    ?ri a gen:RoleInstantiation ;
2074
                        npa:inverseProperty gen:hasAdmin ;
2075
                        npa:viaNanopub ?np .
2076
                  }
2077
                  GRAPH <%2$s> {
2078
                    ?invNp <%3$s> ?np ;
2079
                           npa:hasLoadNumber ?ln .
2080
                    FILTER (?ln > %4$d)
2081
                    %5$s
2082
                  }
2083
                """, graph, NPA.GRAPH, NPX.INVALIDATES, lastProcessed,
18✔
2084
                samePublisherClause("invNp", "np"));
6✔
2085
    }
2086

2087
    /** DELETE template for admin-tier RoleInstantiations whose source nanopub was invalidated. */
2088
    static String adminInvalidationDelete(IRI graph, long lastProcessed) {
2089
        return String.format("""
63✔
2090
                PREFIX npa: <%1$s>
2091
                PREFIX gen: <%2$s>
2092
                DELETE { GRAPH <%3$s> {
2093
                  ?ri ?p ?o .
2094
                } }
2095
                WHERE {
2096
                  GRAPH <%3$s> { ?ri ?p ?o . }
2097
                %4$s
2098
                }
2099
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
2100
                adminInvalidationCheckWhere(graph, lastProcessed));
6✔
2101
    }
2102

2103
    /** WHERE clause for RoleAssignment invalidation. */
2104
    static String roleAssignmentInvalidationCheckWhere(IRI graph, long lastProcessed) {
2105
        return String.format("""
60✔
2106
                  GRAPH <%1$s> {
2107
                    ?ra a gen:RoleAssignment ;
2108
                        npa:viaNanopub ?np .
2109
                  }
2110
                  GRAPH <%2$s> {
2111
                    ?invNp <%3$s> ?np ;
2112
                           npa:hasLoadNumber ?ln .
2113
                    FILTER (?ln > %4$d)
2114
                    %5$s
2115
                  }
2116
                """, graph, NPA.GRAPH, NPX.INVALIDATES, lastProcessed,
18✔
2117
                samePublisherClause("invNp", "np"));
6✔
2118
    }
2119

2120
    /** DELETE template for RoleAssignments whose source nanopub was invalidated. */
2121
    static String roleAssignmentInvalidationDelete(IRI graph, long lastProcessed) {
2122
        return String.format("""
63✔
2123
                PREFIX npa: <%1$s>
2124
                PREFIX gen: <%2$s>
2125
                DELETE { GRAPH <%3$s> {
2126
                  ?ra ?p ?o .
2127
                } }
2128
                WHERE {
2129
                  GRAPH <%3$s> { ?ra ?p ?o . }
2130
                %4$s
2131
                }
2132
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
2133
                roleAssignmentInvalidationCheckWhere(graph, lastProcessed));
6✔
2134
    }
2135

2136
    /**
2137
     * DELETE template for non-admin (leaf-tier) RoleInstantiations whose source
2138
     * nanopub was invalidated. Identified as {@code gen:RoleInstantiation} rows
2139
     * lacking the admin-pinning {@code npa:inverseProperty gen:hasAdmin} triple.
2140
     * No flag is set; leaf-tier removals are recoverable on the next cycle.
2141
     */
2142
    static String leafTierInvalidationDelete(IRI graph, long lastProcessed) {
2143
        return String.format("""
84✔
2144
                PREFIX npa: <%1$s>
2145
                PREFIX gen: <%2$s>
2146
                DELETE { GRAPH <%3$s> {
2147
                  ?ri ?p ?o .
2148
                } }
2149
                WHERE {
2150
                  GRAPH <%3$s> {
2151
                    ?ri a gen:RoleInstantiation ;
2152
                        npa:viaNanopub ?np .
2153
                    FILTER NOT EXISTS { ?ri npa:inverseProperty gen:hasAdmin }
2154
                    ?ri ?p ?o .
2155
                  }
2156
                  GRAPH <%4$s> {
2157
                    ?invNp <%5$s> ?np ;
2158
                           npa:hasLoadNumber ?ln .
2159
                    FILTER (?ln > %6$d)
2160
                    %7$s
2161
                  }
2162
                }
2163
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
2164
                NPA.GRAPH, NPX.INVALIDATES, lastProcessed,
18✔
2165
                samePublisherClause("invNp", "np"));
6✔
2166
    }
2167

2168
    /**
2169
     * WHERE clause shared by the sub-space invalidation ASK precheck and the
2170
     * matching DELETE. Identifies validated {@code npa:SubSpaceDeclaration} rows
2171
     * in the space-state graph whose {@code npa:viaNanopub} is the target of an
2172
     * {@code npx:invalidates} triple in {@code npa:graph} whose subject nanopub
2173
     * has a load number in {@code (lastProcessed, ∞)}.
2174
     */
2175
    static String subSpaceInvalidationCheckWhere(IRI graph, long lastProcessed) {
2176
        return String.format("""
60✔
2177
                  GRAPH <%1$s> {
2178
                    ?d a npa:SubSpaceDeclaration ;
2179
                       npa:viaNanopub ?np .
2180
                  }
2181
                  GRAPH <%2$s> {
2182
                    ?invNp <%3$s> ?np ;
2183
                           npa:hasLoadNumber ?ln .
2184
                    FILTER (?ln > %4$d)
2185
                    %5$s
2186
                  }
2187
                """, graph, NPA.GRAPH, NPX.INVALIDATES, lastProcessed,
18✔
2188
                samePublisherClause("invNp", "np"));
6✔
2189
    }
2190

2191
    /**
2192
     * DELETE template for validated {@code npa:SubSpaceDeclaration} rows whose
2193
     * source nanopub was invalidated. Removes the per-declaration row by subject;
2194
     * the convenience direct triples ({@code <child> npa:isSubSpaceOf <parent>}
2195
     * and inverse) are then dropped by {@link #subSpaceConvenienceEdgeCleanup} in the
2196
     * same cycle (issue #125 finding #5) once no surviving link backs them.
2197
     */
2198
    static String subSpaceInvalidationDelete(IRI graph, long lastProcessed) {
2199
        return String.format("""
63✔
2200
                PREFIX npa: <%1$s>
2201
                PREFIX gen: <%2$s>
2202
                DELETE { GRAPH <%3$s> {
2203
                  ?d ?p ?o .
2204
                } }
2205
                WHERE {
2206
                  GRAPH <%3$s> { ?d ?p ?o . }
2207
                %4$s
2208
                }
2209
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
2210
                subSpaceInvalidationCheckWhere(graph, lastProcessed));
6✔
2211
    }
2212

2213
    /**
2214
     * DELETE template for validated {@code npa:MaintainedResourceDeclaration} rows
2215
     * whose source nanopub was invalidated. Removes the per-declaration row by
2216
     * subject; the convenience direct triples ({@code <r> npa:isMaintainedBy <s>}
2217
     * and inverse) are then dropped by {@link #maintainedResourceConvenienceEdgeCleanup}
2218
     * in the same cycle (issue #125 finding #5). No structural-rebuild flag —
2219
     * maintained-resource is a leaf relation, no downstream consumers depend on its
2220
     * closure, so the prompt edge cleanup fully resolves its invalidation.
2221
     */
2222
    static String maintainedResourceInvalidationDelete(IRI graph, long lastProcessed) {
2223
        return String.format("""
84✔
2224
                PREFIX npa: <%1$s>
2225
                PREFIX gen: <%2$s>
2226
                DELETE { GRAPH <%3$s> {
2227
                  ?d ?p ?o .
2228
                } }
2229
                WHERE {
2230
                  GRAPH <%3$s> {
2231
                    ?d a npa:MaintainedResourceDeclaration ;
2232
                       npa:viaNanopub ?np .
2233
                    ?d ?p ?o .
2234
                  }
2235
                  GRAPH <%4$s> {
2236
                    ?invNp <%5$s> ?np ;
2237
                           npa:hasLoadNumber ?ln .
2238
                    FILTER (?ln > %6$d)
2239
                    %7$s
2240
                  }
2241
                }
2242
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
2243
                NPA.GRAPH, NPX.INVALIDATES, lastProcessed,
18✔
2244
                samePublisherClause("invNp", "np"));
6✔
2245
    }
2246

2247
    /**
2248
     * WHERE clause shared by the alias invalidation ASK precheck and the matching
2249
     * DELETE. Identifies validated {@code npa:SpaceAliasDeclaration} rows in the
2250
     * space-state graph whose {@code npa:viaNanopub} is the target of an
2251
     * {@code npx:invalidates} triple in {@code npa:graph} whose subject nanopub has a
2252
     * load number in {@code (lastProcessed, ∞)}.
2253
     */
2254
    static String aliasInvalidationCheckWhere(IRI graph, long lastProcessed) {
2255
        return String.format("""
60✔
2256
                  GRAPH <%1$s> {
2257
                    ?d a npa:SpaceAliasDeclaration ;
2258
                       npa:viaNanopub ?np .
2259
                  }
2260
                  GRAPH <%2$s> {
2261
                    ?invNp <%3$s> ?np ;
2262
                           npa:hasLoadNumber ?ln .
2263
                    FILTER (?ln > %4$d)
2264
                    %5$s
2265
                  }
2266
                """, graph, NPA.GRAPH, NPX.INVALIDATES, lastProcessed,
18✔
2267
                samePublisherClause("invNp", "np"));
6✔
2268
    }
2269

2270
    /**
2271
     * DELETE template for validated {@code npa:SpaceAliasDeclaration} rows whose
2272
     * source nanopub was invalidated. Removes the per-declaration row by subject; the
2273
     * convenience {@code <alias> npa:sameAsSpace <canonical>} edge is then dropped by
2274
     * {@link #aliasConvenienceEdgeCleanup} in the same cycle (issue #125 finding #5),
2275
     * so an alias can no longer grant admin authority after its declaration is retracted.
2276
     * The alias feeds the authority closure, so this kind is still structural and flips
2277
     * {@code npa:needsFullRebuild} to bound any rows already derived through the edge.
2278
     */
2279
    static String aliasInvalidationDelete(IRI graph, long lastProcessed) {
2280
        return String.format("""
63✔
2281
                PREFIX npa: <%1$s>
2282
                PREFIX gen: <%2$s>
2283
                DELETE { GRAPH <%3$s> {
2284
                  ?d ?p ?o .
2285
                } }
2286
                WHERE {
2287
                  GRAPH <%3$s> { ?d ?p ?o . }
2288
                %4$s
2289
                }
2290
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
2291
                aliasInvalidationCheckWhere(graph, lastProcessed));
6✔
2292
    }
2293

2294
    /**
2295
     * WHERE clause shared by the maintained-resource invalidation ASK precheck and the
2296
     * matching cleanup. Identifies validated {@code npa:MaintainedResourceDeclaration}
2297
     * rows in the space-state graph whose {@code npa:viaNanopub} is the target of an
2298
     * {@code npx:invalidates} triple in {@code npa:graph} whose subject nanopub has a
2299
     * load number in {@code (lastProcessed, ∞)}.
2300
     */
2301
    static String maintainedResourceInvalidationCheckWhere(IRI graph, long lastProcessed) {
2302
        return String.format("""
×
2303
                  GRAPH <%1$s> {
2304
                    ?d a npa:MaintainedResourceDeclaration ;
2305
                       npa:viaNanopub ?np .
2306
                  }
2307
                  GRAPH <%2$s> {
2308
                    ?invNp <%3$s> ?np ;
2309
                           npa:hasLoadNumber ?ln .
2310
                    FILTER (?ln > %4$d)
2311
                    %5$s
2312
                  }
2313
                """, graph, NPA.GRAPH, NPX.INVALIDATES, lastProcessed,
×
2314
                samePublisherClause("invNp", "np"));
×
2315
    }
2316

2317
    /**
2318
     * Convenience-edge cleanup for invalidated sub-space declarations (issue #125
2319
     * finding #5). Run after {@link #subSpaceInvalidationDelete} (which removes the
2320
     * {@code npa:SubSpaceDeclaration} rows). Two phases as one multi-operation update:
2321
     * <ol>
2322
     *   <li>delete every {@code npa:SubSpaceLink} provenance link whose
2323
     *       {@code npa:viaNanopub} was invalidated (same {@code npx:invalidates} +
2324
     *       same-publisher gate as the declaration delete);</li>
2325
     *   <li>orphan-sweep: delete the convenience {@code npa:isSubSpaceOf} /
2326
     *       {@code npa:hasSubSpace} edges (both ref- and IRI-valued) that no surviving
2327
     *       link backs — neither a {@code npa:SubSpaceLink} (explicit declaration) nor a
2328
     *       {@code npa:DerivedSubSpaceLink} (URL-prefix fallback).</li>
2329
     * </ol>
2330
     * Edges backed by another surviving declaration or by the URL-prefix fallback are
2331
     * kept. The {@code npa:needsFullRebuild} flag still fires for the structural kind, so
2332
     * downstream rows derived through a removed edge remain rebuild-bounded; this only
2333
     * stops the convenience edges themselves from going sticky.
2334
     */
2335
    static String subSpaceConvenienceEdgeCleanup(IRI graph, long lastProcessed) {
2336
        return String.format("""
72✔
2337
                PREFIX npa: <%1$s>
2338
                # 1. Drop sub-space provenance links whose source nanopub was invalidated.
2339
                DELETE { GRAPH <%2$s> { ?l ?p ?o . } }
2340
                WHERE {
2341
                  GRAPH <%2$s> {
2342
                    ?l a npa:SubSpaceLink ;
2343
                       npa:viaNanopub ?np .
2344
                    ?l ?p ?o .
2345
                  }
2346
                  GRAPH <%3$s> {
2347
                    ?invNp <%4$s> ?np ;
2348
                           npa:hasLoadNumber ?ln .
2349
                    FILTER (?ln > %5$d)
2350
                    %6$s
2351
                  }
2352
                } ;
2353
                # 2. Orphan-sweep isSubSpaceOf edges (ref- and IRI-valued) with no backing link.
2354
                DELETE { GRAPH <%2$s> { ?c npa:isSubSpaceOf ?p . } }
2355
                WHERE {
2356
                  GRAPH <%2$s> {
2357
                    ?c npa:isSubSpaceOf ?p .
2358
                    FILTER NOT EXISTS {
2359
                      { ?l a npa:SubSpaceLink } UNION { ?l a npa:DerivedSubSpaceLink }
2360
                      { { ?l npa:childSpaceRef ?c . ?l npa:parentSpaceRef ?p }
2361
                        UNION
2362
                        { ?l npa:childSpace ?c . ?l npa:parentSpace ?p } }
2363
                    }
2364
                  }
2365
                } ;
2366
                # 3. Orphan-sweep the inverse hasSubSpace edges symmetrically.
2367
                DELETE { GRAPH <%2$s> { ?p npa:hasSubSpace ?c . } }
2368
                WHERE {
2369
                  GRAPH <%2$s> {
2370
                    ?p npa:hasSubSpace ?c .
2371
                    FILTER NOT EXISTS {
2372
                      { ?l a npa:SubSpaceLink } UNION { ?l a npa:DerivedSubSpaceLink }
2373
                      { { ?l npa:childSpaceRef ?c . ?l npa:parentSpaceRef ?p }
2374
                        UNION
2375
                        { ?l npa:childSpace ?c . ?l npa:parentSpace ?p } }
2376
                    }
2377
                  }
2378
                }
2379
                """, NPA.NAMESPACE, graph, NPA.GRAPH, NPX.INVALIDATES, lastProcessed,
18✔
2380
                samePublisherClause("invNp", "np"));
6✔
2381
    }
2382

2383
    /**
2384
     * Convenience-edge cleanup for invalidated maintained-resource declarations (issue
2385
     * #125 finding #5). Run after {@link #maintainedResourceInvalidationDelete}. Deletes
2386
     * the {@code npa:MaintainedResourceLink} provenance links whose source nanopub was
2387
     * invalidated, then orphan-sweeps the {@code npa:isMaintainedBy} /
2388
     * {@code npa:hasMaintainedResource} edges (ref- and IRI-valued) that no surviving link
2389
     * backs. See {@link #subSpaceConvenienceEdgeCleanup} for the two-phase structure.
2390
     */
2391
    static String maintainedResourceConvenienceEdgeCleanup(IRI graph, long lastProcessed) {
2392
        return String.format("""
72✔
2393
                PREFIX npa: <%1$s>
2394
                # 1. Drop maintained-resource provenance links whose source nanopub was invalidated.
2395
                DELETE { GRAPH <%2$s> { ?l ?p ?o . } }
2396
                WHERE {
2397
                  GRAPH <%2$s> {
2398
                    ?l a npa:MaintainedResourceLink ;
2399
                       npa:viaNanopub ?np .
2400
                    ?l ?p ?o .
2401
                  }
2402
                  GRAPH <%3$s> {
2403
                    ?invNp <%4$s> ?np ;
2404
                           npa:hasLoadNumber ?ln .
2405
                    FILTER (?ln > %5$d)
2406
                    %6$s
2407
                  }
2408
                } ;
2409
                # 2. Orphan-sweep isMaintainedBy edges (ref- and IRI-valued) with no backing link.
2410
                DELETE { GRAPH <%2$s> { ?r npa:isMaintainedBy ?o . } }
2411
                WHERE {
2412
                  GRAPH <%2$s> {
2413
                    ?r npa:isMaintainedBy ?o .
2414
                    FILTER NOT EXISTS {
2415
                      ?l a npa:MaintainedResourceLink ;
2416
                         npa:resourceIri ?r .
2417
                      { ?l npa:maintainerSpaceRef ?o } UNION { ?l npa:maintainerSpace ?o }
2418
                    }
2419
                  }
2420
                } ;
2421
                # 3. Orphan-sweep the inverse hasMaintainedResource edges symmetrically.
2422
                DELETE { GRAPH <%2$s> { ?o npa:hasMaintainedResource ?r . } }
2423
                WHERE {
2424
                  GRAPH <%2$s> {
2425
                    ?o npa:hasMaintainedResource ?r .
2426
                    FILTER NOT EXISTS {
2427
                      ?l a npa:MaintainedResourceLink ;
2428
                         npa:resourceIri ?r .
2429
                      { ?l npa:maintainerSpaceRef ?o } UNION { ?l npa:maintainerSpace ?o }
2430
                    }
2431
                  }
2432
                } ;
2433
                # 4. Orphan-sweep the maintained arm of hasGoverningSpaceRef (issue #130).
2434
                #    Only the ref-valued maintained edge is removed here — it is backed by a
2435
                #    MaintainedResourceLink. The reflexive space self-edge (subject = a space
2436
                #    IRI that has its own SpaceRef) is NOT a maintained edge and is left to the
2437
                #    self-healing reflexive pass, so the guard keeps any ?r that is itself a space.
2438
                DELETE { GRAPH <%2$s> { ?r npa:hasGoverningSpaceRef ?o . } }
2439
                WHERE {
2440
                  GRAPH <%2$s> {
2441
                    ?r npa:hasGoverningSpaceRef ?o .
2442
                    FILTER NOT EXISTS {
2443
                      ?l a npa:MaintainedResourceLink ;
2444
                         npa:resourceIri ?r ;
2445
                         npa:maintainerSpaceRef ?o .
2446
                    }
2447
                    FILTER NOT EXISTS { GRAPH <%7$s> { ?o npa:spaceIri ?r . } }
2448
                  }
2449
                }
2450
                """, NPA.NAMESPACE, graph, NPA.GRAPH, NPX.INVALIDATES, lastProcessed,
18✔
2451
                samePublisherClause("invNp", "np"), SpacesVocab.SPACES_GRAPH);
18✔
2452
    }
2453

2454
    /**
2455
     * Convenience-edge cleanup for invalidated space-alias declarations (issue #125
2456
     * finding #5 — the load-bearing case, since the alias edge feeds the admin-authority
2457
     * closure). Run after {@link #aliasInvalidationDelete}. Deletes the
2458
     * {@code npa:SpaceAliasLink} provenance links whose source nanopub was invalidated,
2459
     * then orphan-sweeps the {@code npa:sameAsSpace} edges (ref- and IRI-valued) that no
2460
     * surviving link backs. See {@link #subSpaceConvenienceEdgeCleanup} for the two-phase
2461
     * structure.
2462
     */
2463
    static String aliasConvenienceEdgeCleanup(IRI graph, long lastProcessed) {
2464
        return String.format("""
72✔
2465
                PREFIX npa: <%1$s>
2466
                # 1. Drop alias provenance links whose source nanopub was invalidated.
2467
                DELETE { GRAPH <%2$s> { ?l ?p ?o . } }
2468
                WHERE {
2469
                  GRAPH <%2$s> {
2470
                    ?l a npa:SpaceAliasLink ;
2471
                       npa:viaNanopub ?np .
2472
                    ?l ?p ?o .
2473
                  }
2474
                  GRAPH <%3$s> {
2475
                    ?invNp <%4$s> ?np ;
2476
                           npa:hasLoadNumber ?ln .
2477
                    FILTER (?ln > %5$d)
2478
                    %6$s
2479
                  }
2480
                } ;
2481
                # 2. Orphan-sweep sameAsSpace edges (ref- and IRI-valued) with no backing link.
2482
                DELETE { GRAPH <%2$s> { ?alias npa:sameAsSpace ?o . } }
2483
                WHERE {
2484
                  GRAPH <%2$s> {
2485
                    ?alias npa:sameAsSpace ?o .
2486
                    FILTER NOT EXISTS {
2487
                      ?l a npa:SpaceAliasLink ;
2488
                         npa:aliasSpace ?alias .
2489
                      { ?l npa:canonicalSpaceRef ?o } UNION { ?l npa:canonicalSpace ?o }
2490
                    }
2491
                  }
2492
                }
2493
                """, NPA.NAMESPACE, graph, NPA.GRAPH, NPX.INVALIDATES, lastProcessed,
18✔
2494
                samePublisherClause("invNp", "np"));
6✔
2495
    }
2496

2497
    /**
2498
     * WHERE clause shared by the preset-deactivation ASK precheck and the matching DELETE
2499
     * (Nanodash issue #302). Binds {@code ?ra} = a materialized preset-derived
2500
     * {@code gen:RoleAssignment} ({@code npa:derivedFromPreset}) for which a <em>newer,
2501
     * admin-authored</em> same-{@code (preset, resource)} assignment exists by
2502
     * {@code dct:created} (load number in {@code (lastProcessed, ∞)}). This is NOT an
2503
     * {@code npx:invalidates} check — preset activation is latest-wins by timestamp.
2504
     *
2505
     * <p>Authorization-scoped (anti-hijack, design doc §3/§4.4): the newer assignment's
2506
     * publisher must itself be a validated admin of the row's {@code npa:forSpaceRef}, so an
2507
     * unauthorized key's newer assignment can neither delete nor shadow an admin's
2508
     * materialized role. {@code dct:created} is written as a full IRI (not a {@code dct:}
2509
     * prefix) because {@link #wouldInvalidate}'s ASK wrapper only declares {@code npa:} /
2510
     * {@code gen:}.
2511
     */
2512
    static String presetDeactivationCheckWhere(IRI graph, long lastProcessed) {
2513
        return String.format("""
60✔
2514
                  GRAPH <%1$s> {
2515
                    ?ra a gen:RoleAssignment ;
2516
                        npa:derivedFromPreset ?assignNp ;
2517
                        npa:forSpaceRef ?targetRef .
2518
                  }
2519
                  GRAPH <%2$s> {
2520
                    ?pa a npa:PresetAssignment ;
2521
                        npa:viaNanopub  ?assignNp ;
2522
                        npa:ofPreset    ?preset ;
2523
                        npa:forResource ?resource ;
2524
                        <http://purl.org/dc/terms/created> ?created .
2525
                    ?paNewer a npa:PresetAssignment ;
2526
                             npa:ofPreset    ?preset ;
2527
                             npa:forResource ?resource ;
2528
                             npa:pubkeyHash  ?pkhNewer ;
2529
                             npa:viaNanopub  ?assignNpNewer ;
2530
                             <http://purl.org/dc/terms/created> ?createdNewer .
2531
                    FILTER (?createdNewer > ?created
2532
                            || (?createdNewer = ?created && STR(?paNewer) > STR(?pa)))
2533
                  }
2534
                  GRAPH <%3$s> {
2535
                    ?assignNpNewer npa:hasLoadNumber ?lnNewer .
2536
                    FILTER (?lnNewer > %4$d)
2537
                  }
2538
                  GRAPH <%1$s> {
2539
                    ?acctNewer a npa:AccountState ;
2540
                               npa:agent  ?publisherNewer ;
2541
                               npa:pubkey ?pkhNewer .
2542
                    ?adminRINewer a gen:RoleInstantiation ;
2543
                                  npa:forSpaceRef ?targetRef ;
2544
                                  npa:inverseProperty gen:hasAdmin ;
2545
                                  npa:forAgent ?publisherNewer .
2546
                  }
2547
                """, graph, SpacesVocab.SPACES_GRAPH, NPA.GRAPH, lastProcessed);
6✔
2548
    }
2549

2550
    /**
2551
     * DELETE template for preset-derived {@code gen:RoleAssignment} rows superseded by a
2552
     * newer admin-authored same-pair assignment (issue #302). Removes the whole row by
2553
     * subject; scoped via {@code npa:derivedFromPreset} so directly-published attachments
2554
     * are never touched. The {@link #presetAttachmentValidationUpdate} re-INSERT in the
2555
     * same cycle re-materializes the pair iff the newest assignment is still active.
2556
     */
2557
    static String presetDeactivationDelete(IRI graph, long lastProcessed) {
2558
        return String.format("""
63✔
2559
                PREFIX npa: <%1$s>
2560
                PREFIX gen: <%2$s>
2561
                DELETE { GRAPH <%3$s> {
2562
                  ?ra ?p ?o .
2563
                } }
2564
                WHERE {
2565
                  GRAPH <%3$s> { ?ra ?p ?o . }
2566
                %4$s
2567
                }
2568
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
2569
                presetDeactivationCheckWhere(graph, lastProcessed));
6✔
2570
    }
2571

2572
    /**
2573
     * DELETE template for ref-scoped preset-assignment stamps ({@link
2574
     * #presetAssignmentRefStampUpdate}) whose underlying assignment nanopub was
2575
     * hard-retracted (issue #122). Removes the whole row by subject; scoped to
2576
     * state-graph {@code npa:PresetAssignment} rows that carry {@code npa:forSpaceRef}
2577
     * (the IRI-keyed extraction rows never do), so it can never touch them.
2578
     *
2579
     * <p>Leaf delete — no structural flag: nothing downstream derives from a listing
2580
     * stamp, so a stale row only mis-displays a retracted assignment until this cycle's
2581
     * delete runs. Admin-grant revocation is bounded by the periodic full rebuild (same
2582
     * sticky-convenience policy as the alias / sub-space declaration edges). A
2583
     * <em>deactivation</em> needs no delete here: it is represented as a newer
2584
     * admin-authored stamp with {@code npa:isActivated false}, resolved by the consumer's
2585
     * latest-wins.
2586
     */
2587
    static String presetAssignmentRefInvalidationDelete(IRI graph, long lastProcessed) {
2588
        return String.format("""
84✔
2589
                PREFIX npa: <%1$s>
2590
                PREFIX gen: <%2$s>
2591
                DELETE { GRAPH <%3$s> {
2592
                  ?paRef ?p ?o .
2593
                } }
2594
                WHERE {
2595
                  GRAPH <%3$s> {
2596
                    ?paRef a npa:PresetAssignment ;
2597
                           npa:forSpaceRef ?targetRef ;
2598
                           npa:viaNanopub  ?assignNp .
2599
                    ?paRef ?p ?o .
2600
                  }
2601
                  GRAPH <%4$s> {
2602
                    ?invNp <%5$s> ?assignNp ;
2603
                           npa:hasLoadNumber ?ln .
2604
                    FILTER (?ln > %6$d)
2605
                    %7$s
2606
                  }
2607
                }
2608
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
2609
                NPA.GRAPH, NPX.INVALIDATES, lastProcessed,
18✔
2610
                samePublisherClause("invNp", "assignNp"));
6✔
2611
    }
2612

2613
    /** Wraps an ASK by joining the shared prefixes. */
2614
    private boolean wouldInvalidate(IRI graph, long lastProcessed,
2615
                                    boolean adminPinned, String whereClause) {
2616
        // adminPinned is informational only — kept to make call sites read clearly;
2617
        // the WHERE clause already encodes the kind via its own type predicates.
2618
        String ask = String.format("""
×
2619
                PREFIX npa: <%1$s>
2620
                PREFIX gen: <%2$s>
2621
                ASK { %3$s }
2622
                """, NPA.NAMESPACE, GEN.NAMESPACE, whereClause);
2623
        return runAsk(ask);
×
2624
    }
2625

2626
    private boolean runAsk(String sparql) {
2627
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
2628
            return conn.prepareBooleanQuery(QueryLanguage.SPARQL, sparql).evaluate();
×
2629
        }
2630
    }
2631

2632
    private void executeUpdate(String sparqlUpdate) {
2633
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
2634
            conn.prepareUpdate(QueryLanguage.SPARQL, sparqlUpdate).execute();
×
2635
        }
2636
    }
×
2637

2638
    // ---------------- Mirror step ----------------
2639

2640
    /**
2641
     * Copies trust-approved {@code npa:AccountState} rows from {@code npat:<T>}
2642
     * in the {@code trust} repo into {@code newGraph} in the {@code spaces} repo,
2643
     * inside one spaces-side serializable transaction.
2644
     *
2645
     * @return number of rows mirrored (useful for metrics / logging)
2646
     */
2647
    int mirrorTrustState(String trustStateHash, IRI newGraph) {
2648
        IRI trustStateIri = NPAT.forHash(trustStateHash);
×
2649
        int count = 0;
×
2650
        try (RepositoryConnection trustConn = TripleStore.get().getRepoConnection(TRUST_REPO);
×
2651
             RepositoryConnection spacesConn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
2652
            trustConn.begin(IsolationLevels.READ_COMMITTED);
×
2653
            spacesConn.begin(IsolationLevels.SERIALIZABLE);
×
2654
            // Walk rdf:type triples in the trust state's graph; for each AccountState,
2655
            // check status and copy the approved ones verbatim (minus status-specific
2656
            // detail triples, which we don't need for validation).
2657
            try (RepositoryResult<Statement> typeRows = trustConn.getStatements(
×
2658
                    null, RDF.TYPE, NPA_ACCOUNT_STATE, trustStateIri)) {
2659
                while (typeRows.hasNext()) {
×
2660
                    Statement st = typeRows.next();
×
2661
                    if (!(st.getSubject() instanceof IRI accountStateIri)) continue;
×
2662
                    Value status = trustConn.getStatements(accountStateIri, NPA_TRUST_STATUS, null, trustStateIri)
×
2663
                            .stream().findFirst().map(Statement::getObject).orElse(null);
×
2664
                    if (!(status instanceof IRI statusIri) || !APPROVED_SET.contains(statusIri)) continue;
×
2665
                    Value agent = trustConn.getStatements(accountStateIri, NPA_AGENT, null, trustStateIri)
×
2666
                            .stream().findFirst().map(Statement::getObject).orElse(null);
×
2667
                    Value pubkey = trustConn.getStatements(accountStateIri, NPA_PUBKEY, null, trustStateIri)
×
2668
                            .stream().findFirst().map(Statement::getObject).orElse(null);
×
2669
                    if (agent == null || pubkey == null) {
×
2670
                        logger.warn("AuthorityResolver.mirror: account {} missing agent or pubkey; skipping",
×
2671
                                accountStateIri);
2672
                        continue;
×
2673
                    }
2674
                    spacesConn.add(accountStateIri, RDF.TYPE, NPA_ACCOUNT_STATE, newGraph);
×
2675
                    spacesConn.add(accountStateIri, NPA_AGENT, agent, newGraph);
×
2676
                    spacesConn.add(accountStateIri, NPA_PUBKEY, pubkey, newGraph);
×
2677
                    spacesConn.add(accountStateIri, NPA_TRUST_STATUS, statusIri, newGraph);
×
2678
                    // Mirror the authorizing introduction provenance when present (issue #125
2679
                    // finding #4). Optional: absent for snapshots from registries that predate
2680
                    // nanopub-registry#117/#118, so consumers (e.g. get-space-members-ref) must
2681
                    // treat npa:viaNanopub on an AccountState as best-effort, not guaranteed.
2682
                    Value viaNanopub = trustConn.getStatements(accountStateIri, NPA_VIA_NANOPUB, null, trustStateIri)
×
2683
                            .stream().findFirst().map(Statement::getObject).orElse(null);
×
2684
                    if (viaNanopub != null) {
×
2685
                        spacesConn.add(accountStateIri, NPA_VIA_NANOPUB, viaNanopub, newGraph);
×
2686
                    }
2687
                    count++;
×
2688
                }
×
2689
            }
2690
            // Mirror canonical foaf:name triples for approved agents. The trust
2691
            // loader emits one per agent (across approved keys, MAX(ratio) wins).
2692
            // Copying them into the space-state graph means consumers reading
2693
            // ?agent foaf:name ?n inside the state graph hit local data, with no
2694
            // cross-repo SERVICE.
2695
            try (RepositoryResult<Statement> nameRows = trustConn.getStatements(
×
2696
                    null, FOAF.NAME, null, trustStateIri)) {
2697
                while (nameRows.hasNext()) {
×
2698
                    Statement st = nameRows.next();
×
2699
                    spacesConn.add(st.getSubject(), st.getPredicate(), st.getObject(), newGraph);
×
2700
                }
×
2701
            }
2702
            spacesConn.commit();
×
2703
            trustConn.commit();
×
2704
        }
2705
        return count;
×
2706
    }
2707

2708
    // ---------------- Pointer + counter helpers ----------------
2709

2710
    /**
2711
     * Reads the current {@code npa:hasCurrentSpaceState} pointer from the
2712
     * {@code npa:graph} admin graph of the {@code spaces} repo. Returns
2713
     * {@code null} if no pointer exists yet.
2714
     */
2715
    IRI getCurrentSpaceStateGraph() {
2716
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
2717
            Value v = Utils.getObjectForPattern(conn, NPA.GRAPH, NPA.THIS_REPO,
×
2718
                    SpacesVocab.HAS_CURRENT_SPACE_STATE);
2719
            return (v instanceof IRI iri) ? iri : null;
×
2720
        } catch (Exception ex) {
×
2721
            logger.warn("AuthorityResolver: failed to read hasCurrentSpaceState pointer: {}", ex.toString());
×
2722
            return null;
×
2723
        }
2724
    }
2725

2726
    long getCurrentLoadCounter() {
2727
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
2728
            Value v = Utils.getObjectForPattern(conn, NPA.GRAPH, NPA.THIS_REPO,
×
2729
                    SpacesVocab.CURRENT_LOAD_COUNTER);
2730
            if (v == null) return 0;
×
2731
            try {
2732
                return Long.parseLong(v.stringValue());
×
2733
            } catch (NumberFormatException ex) {
×
2734
                logger.warn("AuthorityResolver: non-numeric currentLoadCounter: {}", v);
×
2735
                return 0;
×
2736
            }
2737
        } catch (Exception ex) {
×
2738
            logger.warn("AuthorityResolver: failed to read currentLoadCounter: {}", ex.toString());
×
2739
            return 0;
×
2740
        }
2741
    }
2742

2743
    /**
2744
     * Atomic pointer flip: a single SPARQL {@code DELETE … INSERT … WHERE}
2745
     * replaces the old pointer with the new one in one statement, so readers
2746
     * never see a zero-pointer window.
2747
     */
2748
    void flipPointer(IRI newGraph) {
2749
        String update = String.format("""
×
2750
                DELETE { GRAPH <%s> { <%s> <%s> ?old } }
2751
                INSERT { GRAPH <%s> { <%s> <%s> <%s> } }
2752
                WHERE  { OPTIONAL { GRAPH <%s> { <%s> <%s> ?old } } }
2753
                """,
2754
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.HAS_CURRENT_SPACE_STATE,
2755
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.HAS_CURRENT_SPACE_STATE, newGraph,
2756
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.HAS_CURRENT_SPACE_STATE);
2757
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
2758
            conn.begin(IsolationLevels.SERIALIZABLE);
×
2759
            conn.prepareUpdate(QueryLanguage.SPARQL, update).execute();
×
2760
            conn.commit();
×
2761
        }
2762
    }
×
2763

2764
    void writeProcessedUpTo(IRI graph, long loadCounter) {
2765
        String update = String.format("""
×
2766
                DELETE { GRAPH <%s> { <%s> <%s> ?old } }
2767
                INSERT { GRAPH <%s> { <%s> <%s> "%d"^^<http://www.w3.org/2001/XMLSchema#long> } }
2768
                WHERE  { OPTIONAL { GRAPH <%s> { <%s> <%s> ?old } } }
2769
                """,
2770
                graph, graph, SpacesVocab.PROCESSED_UP_TO,
2771
                graph, graph, SpacesVocab.PROCESSED_UP_TO, loadCounter,
×
2772
                graph, graph, SpacesVocab.PROCESSED_UP_TO);
2773
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
2774
            conn.begin(IsolationLevels.SERIALIZABLE);
×
2775
            conn.prepareUpdate(QueryLanguage.SPARQL, update).execute();
×
2776
            conn.commit();
×
2777
        }
2778
    }
×
2779

2780
    /**
2781
     * Reads {@code processedUpTo} from the given space-state graph.
2782
     * Returns {@code -1} if absent (graph not fully built yet).
2783
     */
2784
    long readProcessedUpTo(IRI graph) {
2785
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
2786
            String query = String.format(
×
2787
                    "SELECT ?n WHERE { GRAPH <%s> { <%s> <%s> ?n } }",
2788
                    graph, graph, SpacesVocab.PROCESSED_UP_TO);
2789
            try (TupleQueryResult r = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) {
×
2790
                if (!r.hasNext()) return -1;
×
2791
                BindingSet b = r.next();
×
2792
                return Long.parseLong(b.getBinding("n").getValue().stringValue());
×
2793
            }
×
2794
        } catch (Exception ex) {
×
2795
            logger.warn("AuthorityResolver: failed to read processedUpTo for {}: {}", graph, ex.toString());
×
2796
            return -1;
×
2797
        }
2798
    }
2799

2800
    /**
2801
     * Reads the {@code npa:needsFullRebuild} flag (boolean literal) from
2802
     * {@code npa:graph} in the {@code spaces} repo. Defaults to {@code false}
2803
     * when the triple is absent.
2804
     */
2805
    boolean readNeedsFullRebuild() {
2806
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
2807
            Value v = Utils.getObjectForPattern(conn, NPA.GRAPH, NPA.THIS_REPO,
×
2808
                    SpacesVocab.NEEDS_FULL_REBUILD);
2809
            return v != null && Boolean.parseBoolean(v.stringValue());
×
2810
        } catch (Exception ex) {
×
2811
            logger.warn("AuthorityResolver: failed to read needsFullRebuild: {}", ex.toString());
×
2812
            return false;
×
2813
        }
2814
    }
2815

2816
    void setNeedsFullRebuild() {
2817
        writeNeedsFullRebuild(true);
×
2818
    }
×
2819

2820
    void clearNeedsFullRebuild() {
2821
        writeNeedsFullRebuild(false);
×
2822
    }
×
2823

2824
    private void writeNeedsFullRebuild(boolean value) {
2825
        String update = String.format("""
×
2826
                DELETE { GRAPH <%s> { <%s> <%s> ?old } }
2827
                INSERT { GRAPH <%s> { <%s> <%s> "%s"^^<http://www.w3.org/2001/XMLSchema#boolean> } }
2828
                WHERE  { OPTIONAL { GRAPH <%s> { <%s> <%s> ?old } } }
2829
                """,
2830
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.NEEDS_FULL_REBUILD,
2831
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.NEEDS_FULL_REBUILD, value,
×
2832
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.NEEDS_FULL_REBUILD);
2833
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
2834
            conn.begin(IsolationLevels.SERIALIZABLE);
×
2835
            conn.prepareUpdate(QueryLanguage.SPARQL, update).execute();
×
2836
            conn.commit();
×
2837
        }
2838
    }
×
2839

2840
    void dropGraph(IRI graph) {
2841
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
2842
            conn.begin(IsolationLevels.SERIALIZABLE);
×
2843
            conn.clear(graph);
×
2844
            conn.commit();
×
2845
            logger.info("AuthorityResolver: dropped old space-state graph {}", graph);
×
2846
        }
2847
    }
×
2848

2849
    // ---------------- Trust-repo pointer lookup (used by TrustStateRegistry's bootstrap) ----------------
2850

2851
    /**
2852
     * Queries the {@code trust} repo directly for the current trust-state hash.
2853
     * Prefer {@link TrustStateRegistry#getCurrentHash()} in normal operation —
2854
     * this helper exists for tests and diagnostics.
2855
     *
2856
     * @return the current trust-state hash, or empty if none is set
2857
     */
2858
    Optional<String> readTrustRepoCurrentHash() {
2859
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(TRUST_REPO)) {
×
2860
            Value v = Utils.getObjectForPattern(conn, NPA.GRAPH, NPA.THIS_REPO,
×
2861
                    NPA_HAS_CURRENT_TRUST_STATE);
2862
            if (!(v instanceof IRI iri)) return Optional.empty();
×
2863
            String s = iri.stringValue();
×
2864
            if (!s.startsWith(NPAT.NAMESPACE)) return Optional.empty();
×
2865
            return Optional.of(s.substring(NPAT.NAMESPACE.length()));
×
2866
        } catch (Exception ex) {
×
2867
            logger.warn("AuthorityResolver: failed to read trust-repo current pointer: {}", ex.toString());
×
2868
            return Optional.empty();
×
2869
        }
2870
    }
2871

2872
    private static String abbrev(String hash) {
2873
        return hash.length() > 12 ? hash.substring(0, 12) + "…" : hash;
×
2874
    }
2875

2876
}
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