@memberjunction/search-engine 6.2.0-edge.3 → 6.2.0-edge.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/README.md +1 -1
  2. package/dist/generic/EntitySearchProvider.d.ts +12 -4
  3. package/dist/generic/EntitySearchProvider.d.ts.map +1 -1
  4. package/dist/generic/EntitySearchProvider.js +13 -6
  5. package/dist/generic/EntitySearchProvider.js.map +1 -1
  6. package/dist/generic/FullTextSearchProvider.d.ts +8 -0
  7. package/dist/generic/FullTextSearchProvider.d.ts.map +1 -1
  8. package/dist/generic/FullTextSearchProvider.js +12 -4
  9. package/dist/generic/FullTextSearchProvider.js.map +1 -1
  10. package/dist/generic/ISearchProvider.d.ts +67 -2
  11. package/dist/generic/ISearchProvider.d.ts.map +1 -1
  12. package/dist/generic/ISearchProvider.js +63 -0
  13. package/dist/generic/ISearchProvider.js.map +1 -1
  14. package/dist/generic/ScopeDimensionResolver.d.ts +28 -0
  15. package/dist/generic/ScopeDimensionResolver.d.ts.map +1 -1
  16. package/dist/generic/ScopeDimensionResolver.js +55 -3
  17. package/dist/generic/ScopeDimensionResolver.js.map +1 -1
  18. package/dist/generic/ScopeExplanation.d.ts +24 -13
  19. package/dist/generic/ScopeExplanation.d.ts.map +1 -1
  20. package/dist/generic/ScopeExplanation.js +39 -26
  21. package/dist/generic/ScopeExplanation.js.map +1 -1
  22. package/dist/generic/ScopeFilterGuard.d.ts +18 -0
  23. package/dist/generic/ScopeFilterGuard.d.ts.map +1 -1
  24. package/dist/generic/ScopeFilterGuard.js +49 -0
  25. package/dist/generic/ScopeFilterGuard.js.map +1 -1
  26. package/dist/generic/ScopeTemplateRenderer.d.ts +3 -0
  27. package/dist/generic/ScopeTemplateRenderer.d.ts.map +1 -1
  28. package/dist/generic/ScopeTemplateRenderer.js +11 -2
  29. package/dist/generic/ScopeTemplateRenderer.js.map +1 -1
  30. package/dist/generic/ScopeValueEscaper.d.ts +10 -3
  31. package/dist/generic/ScopeValueEscaper.d.ts.map +1 -1
  32. package/dist/generic/ScopeValueEscaper.js +51 -5
  33. package/dist/generic/ScopeValueEscaper.js.map +1 -1
  34. package/dist/generic/SearchEngine.d.ts +507 -50
  35. package/dist/generic/SearchEngine.d.ts.map +1 -1
  36. package/dist/generic/SearchEngine.js +1356 -253
  37. package/dist/generic/SearchEngine.js.map +1 -1
  38. package/dist/generic/SearchEnricher.d.ts +3 -1
  39. package/dist/generic/SearchEnricher.d.ts.map +1 -1
  40. package/dist/generic/SearchEnricher.js +10 -5
  41. package/dist/generic/SearchEnricher.js.map +1 -1
  42. package/dist/generic/SearchFusion.d.ts +42 -7
  43. package/dist/generic/SearchFusion.d.ts.map +1 -1
  44. package/dist/generic/SearchFusion.js +116 -47
  45. package/dist/generic/SearchFusion.js.map +1 -1
  46. package/dist/generic/StorageSearchProvider.d.ts +37 -20
  47. package/dist/generic/StorageSearchProvider.d.ts.map +1 -1
  48. package/dist/generic/StorageSearchProvider.js +79 -105
  49. package/dist/generic/StorageSearchProvider.js.map +1 -1
  50. package/dist/generic/TagSearchProvider.d.ts +5 -1
  51. package/dist/generic/TagSearchProvider.d.ts.map +1 -1
  52. package/dist/generic/TagSearchProvider.js +5 -2
  53. package/dist/generic/TagSearchProvider.js.map +1 -1
  54. package/dist/generic/VectorSearchProvider.d.ts +3 -0
  55. package/dist/generic/VectorSearchProvider.d.ts.map +1 -1
  56. package/dist/generic/VectorSearchProvider.js +29 -9
  57. package/dist/generic/VectorSearchProvider.js.map +1 -1
  58. package/dist/generic/search.types.d.ts +125 -7
  59. package/dist/generic/search.types.d.ts.map +1 -1
  60. package/dist/generic/search.types.js +0 -9
  61. package/dist/generic/search.types.js.map +1 -1
  62. package/dist/permissions/SearchScopePermissionResolver.d.ts +6 -5
  63. package/dist/permissions/SearchScopePermissionResolver.d.ts.map +1 -1
  64. package/dist/permissions/SearchScopePermissionResolver.js +15 -13
  65. package/dist/permissions/SearchScopePermissionResolver.js.map +1 -1
  66. package/dist/providers/AzureAISearchProvider.d.ts +4 -1
  67. package/dist/providers/AzureAISearchProvider.d.ts.map +1 -1
  68. package/dist/providers/AzureAISearchProvider.js +8 -6
  69. package/dist/providers/AzureAISearchProvider.js.map +1 -1
  70. package/dist/providers/ElasticsearchSearchProvider.d.ts +3 -0
  71. package/dist/providers/ElasticsearchSearchProvider.d.ts.map +1 -1
  72. package/dist/providers/ElasticsearchSearchProvider.js +8 -7
  73. package/dist/providers/ElasticsearchSearchProvider.js.map +1 -1
  74. package/dist/providers/OpenSearchSearchProvider.d.ts +5 -1
  75. package/dist/providers/OpenSearchSearchProvider.d.ts.map +1 -1
  76. package/dist/providers/OpenSearchSearchProvider.js +9 -5
  77. package/dist/providers/OpenSearchSearchProvider.js.map +1 -1
  78. package/dist/providers/TypesenseSearchProvider.d.ts +4 -1
  79. package/dist/providers/TypesenseSearchProvider.d.ts.map +1 -1
  80. package/dist/providers/TypesenseSearchProvider.js +8 -7
  81. package/dist/providers/TypesenseSearchProvider.js.map +1 -1
  82. package/package.json +10 -10
@@ -19,10 +19,11 @@
19
19
  *
20
20
  * @module @memberjunction/search-engine
21
21
  */
22
- import { IMetadataProvider, UserInfo } from '@memberjunction/core';
23
- import { SearchEngineBase, MJAIAgentEntity, MJAISkillEntity } from '@memberjunction/core-entities';
22
+ import { EntityInfo, IMetadataProvider, UserInfo } from '@memberjunction/core';
23
+ import { SearchEngineBase, MJAIAgentEntity, MJAISkillEntity, ScopeBundle } from '@memberjunction/core-entities';
24
24
  import { BaseSingleton } from '@memberjunction/global';
25
25
  import { SearchParams, SearchResult, SearchResultItem, SearchStreamEvent, ScopePrincipals } from './search.types.js';
26
+ import { BaseSearchProvider } from './ISearchProvider.js';
26
27
  import { ScopeDimensionResolver } from './ScopeDimensionResolver.js';
27
28
  import { ScopeExplanation, ExplainScopeInput, EntitlementExplanation } from './ScopeExplanation.js';
28
29
  /**
@@ -45,8 +46,9 @@ export interface SearchEngineConfig {
45
46
  DefaultMaxResults?: number;
46
47
  /**
47
48
  * Default multiplier applied to per-provider `topK` to compensate for residual
48
- * late permission filtering. Individual calls can override via
49
- * `SearchParams.PermissionOverfetchFactor`. Default: 2.
49
+ * late permission filtering. A scope's `ScopeConfig.permissionOverfetchFactor` or a call's
50
+ * `SearchParams.PermissionOverfetchFactor` takes precedence. Clamped to 1–20 (logged once, at
51
+ * configuration); a non-finite value falls back to 2. Default: 2.
50
52
  */
51
53
  DefaultPermissionOverfetchFactor?: number;
52
54
  }
@@ -61,7 +63,10 @@ export interface SearchEngineConfig {
61
63
  export type OnProviderResolved = (event: {
62
64
  /** Source type as reported by the provider (e.g. 'vector', 'fulltext'). */
63
65
  sourceType: string;
64
- /** Result rows from this provider, with metadata already stamped. */
66
+ /**
67
+ * Result rows from this provider, with metadata already stamped — before any permission pass, so
68
+ * {@link SearchEngine.streamSearch} forwards only their count, never the rows.
69
+ */
65
70
  results: SearchResultItem[];
66
71
  /** Wall-clock time spent inside `Provider.Search()` for this invocation. */
67
72
  durationMs: number;
@@ -123,6 +128,12 @@ export declare class SearchEngine extends BaseSingleton<SearchEngine> {
123
128
  private static readonly CACHE_TTL_MS;
124
129
  /** Maximum cached entries across all users. LRU-evicted on overflow. */
125
130
  private static readonly CACHE_MAX_ENTRIES;
131
+ /**
132
+ * Ceiling on the per-provider over-fetch multiplier, whatever its source (caller, scope metadata or
133
+ * the engine default). Above it a single metadata edit would multiply every provider call for every
134
+ * caller of the scope, and vector providers bill per candidate.
135
+ */
136
+ private static readonly MAX_OVERFETCH_FACTOR;
126
137
  private _cache;
127
138
  private _dimensionResolver;
128
139
  /**
@@ -165,36 +176,31 @@ export declare class SearchEngine extends BaseSingleton<SearchEngine> {
165
176
  */
166
177
  private searchInternal;
167
178
  /**
168
- * Streaming variant of {@link Search}. Yields events as each pipeline
169
- * stage produces output so the caller can emit partials to the UI / agent
170
- * before fusion + reranking complete.
171
- *
172
- * **Phase 2C v1 semantics:** runs the same internal pipeline as
173
- * {@link Search} and emits synthetic events at each transition. This
174
- * preserves all existing fusion / permission / dedup / enrich behavior
175
- * — important because those steps have subtle correctness rules that
176
- * we don't want to re-implement in a parallel code path. Per-provider
177
- * partials are reconstructed from the final SourceCounts; a future
178
- * refactor (Phase 2C v2) can split provider emission to true real-time
179
- * concurrent emission once we measure that the synthetic phase is the
180
- * actual bottleneck.
181
- *
182
- * Cancellation: the consumer can stop iterating at any point — the
183
- * underlying Search() will run to completion but its result is
184
- * discarded. AbortSignal-based mid-pipeline cancellation is a Phase 2C
185
- * v2 concern.
179
+ * Streaming variant of {@link Search}: the same pipeline, with a progress event as each provider
180
+ * returns, so a UI or agent can show progress before fusion, the permission pass and enrichment finish.
181
+ *
182
+ * **Progress, not partial results.** A `provider` event carries the provider's name, its duration and
183
+ * `resultCount` — how many hits it returned, capped at `MaxResults` — and never the hits themselves
184
+ * (`results` is always empty). They arrive before the permission pass, so they include rows the caller's
185
+ * row filters would drop, external-index hits not yet verified against the entity they name, and content
186
+ * whose origin record the caller may not read. Results arrive only in `fused` and `final`, which carry
187
+ * exactly what {@link Search} returns. `resultCount` is counted before the permission and audience passes,
188
+ * like `SearchResult.SourceCounts`, so don't show it to a room.
189
+ *
190
+ * Cancellation: the consumer can stop iterating at any point — the underlying search runs to
191
+ * completion and its result is discarded. Mid-pipeline AbortSignal cancellation is not supported.
186
192
  *
187
193
  * Event ordering:
188
- * 1. Zero or more `provider` events (one per non-empty source)
194
+ * 1. One `provider` event per provider that ran, in the order they return (a provider that failed
195
+ * reports `resultCount: 0`)
189
196
  * 2. Exactly one `fused` event
190
- * 3. Optional one `reranked` event (when a reranker is configured)
191
- * 4. Exactly one `final` event
192
- * 5. On error: a single `error` event in place of `final`.
197
+ * 3. Exactly one `final` event (`reranked` is part of the type but not emitted today)
198
+ * 4. On error: a single `error` event in place of `fused` and `final`.
193
199
  *
194
200
  * @example
195
201
  * for await (const ev of SearchEngine.Instance.streamSearch(params, user)) {
196
202
  * switch (ev.phase) {
197
- * case 'provider': scratchpad.append(`${ev.providerName}: ${ev.results.length} hits`); break;
203
+ * case 'provider': scratchpad.append(`${ev.providerName}: ${ev.resultCount} hits`); break;
198
204
  * case 'final': scratchpad.commit(ev.results); break;
199
205
  * case 'error': scratchpad.fail(ev.error); break;
200
206
  * }
@@ -247,6 +253,58 @@ export declare class SearchEngine extends BaseSingleton<SearchEngine> {
247
253
  * never caches across an allow/deny boundary.
248
254
  */
249
255
  protected buildCacheKey(trimmed: string, params: SearchParams, contextUser: UserInfo): string;
256
+ /**
257
+ * Throw when `audience` is present but cannot be honoured. Called first in `searchInternal`, whose catch
258
+ * turns the throw into a `Success: false` result. A malformed reader is refused rather than skipped:
259
+ * skipping it would restrict nothing, and the room would see the caller's full reach.
260
+ */
261
+ private validateAudience;
262
+ /** What is wrong with an audience, or `null` when it is well formed. Takes `unknown`: hosts assemble it at runtime. */
263
+ private audienceProblem;
264
+ /**
265
+ * What is wrong with one reader, or `null`. A reader needs a non-empty `ID` and a `UserRoles` array:
266
+ * `[]` is a reader with no roles (legitimate, reads nothing); a missing array means it was never hydrated.
267
+ */
268
+ private audienceReaderProblem;
269
+ /** `null`, `an array`, or the `typeof` name: validation messages name a bad value's kind rather than echo it. */
270
+ private describeValue;
271
+ /**
272
+ * The readers an audience actually adds: one per distinct ID (case-insensitive), the caller's own ID left
273
+ * out. Empty when the audience changes nothing. Expects an audience that passed `validateAudience`.
274
+ */
275
+ private distinctReaders;
276
+ /** The distinct reader IDs, lower-cased and sorted, for the cache key. `undefined` when the audience adds no reader, so it keys like no audience. */
277
+ private audienceReaderIDs;
278
+ /**
279
+ * Keep only the results every reader in `params.Audience` may read, on top of the caller's own filter.
280
+ * Each reader gets the same safety net the caller did (`filterByPermissions`: entity read, row filters,
281
+ * ownership), so a shared conversation's results are the intersection of what every participant may see —
282
+ * the asker's reach is the ceiling, each other reader's reach lowers it. Readers are checked concurrently;
283
+ * a reader with the caller's own ID, or listed twice, is checked once. Expects a validated audience
284
+ * (`searchInternal` validates it before doing any work).
285
+ *
286
+ * Two things the pass cannot do, both failing closed:
287
+ * - **Storage hits are refused under an audience.** Their permission model is the storage account's;
288
+ * `filterByPermissions` re-checks a `storage-file` hit's account for the user it is given, but this pass
289
+ * does not yet combine those per-reader answers for storage, so a storage hit is not shown to the room.
290
+ * - **A reader with no roles (`UserRoles: []`) reads nothing.** Permissions and row filters are
291
+ * evaluated from `UserInfo.UserRoles`, so such a reader empties the result. A reader with no
292
+ * `UserRoles` array at all never gets here: validation refuses it.
293
+ *
294
+ * **Identity contract.** A result survives when every reader's `filterByPermissions` returns it. Survivors
295
+ * are matched to the input by `EntityName|RecordID` (the record the result names), falling back to object
296
+ * identity for a result that names no record. An override of `filterByPermissions` may therefore return
297
+ * copies, but must not rewrite `EntityName` or `RecordID`.
298
+ *
299
+ * Protected so a host can change how an audience combines (a host that materializes a shared reach in one
300
+ * query can replace the per-reader pass). It receives the whole `params`, so an override can see the anchor
301
+ * (`SearchContext`) and the scopes. The default is the intersection.
302
+ */
303
+ protected FilterForAudience(results: SearchResultItem[], params: SearchParams, contextUser: UserInfo): Promise<SearchResultItem[]>;
304
+ /** `EntityName|RecordID` for a result that names a record, else the object itself — see `FilterForAudience`'s identity contract. */
305
+ private audienceIdentity;
306
+ /** Log, per reader, why the shared result set shrank: a reader with no roles, or results a reader cannot read. */
307
+ private logAudienceNarrowing;
250
308
  /** Insert into the LRU cache, evicting oldest entries when over capacity. */
251
309
  private cachePut;
252
310
  /** Test / admin hook: clear the result cache. */
@@ -288,13 +346,22 @@ export declare class SearchEngine extends BaseSingleton<SearchEngine> {
288
346
  *
289
347
  * Unlike a real search this never throws for a scope-level problem; a scope that would fail
290
348
  * closed comes back with `Reachable: false` and the reason, since "it would have failed"
291
- * is precisely the finding the caller asked for.
349
+ * is precisely the finding the caller asked for. A scope that cannot be resolved (inactive,
350
+ * expired, or missing) refuses the whole search, so when one is named every scope comes back
351
+ * unreachable, each saying why.
292
352
  *
293
353
  * @param input scopes to explain plus the hypothetical caller context and principals
294
354
  * @param contextUser the user to evaluate entitlement for
295
355
  * @returns one explanation per requested scope, in the order requested
296
356
  */
297
357
  ExplainScope(input: ExplainScopeInput, contextUser: UserInfo): Promise<ScopeExplanation[]>;
358
+ /**
359
+ * A search naming a scope it cannot resolve is refused outright (see `refuseUnresolvableScopes`), so a dry
360
+ * run over the same IDs reaches nothing through ANY of them — including a scope that is reachable on its
361
+ * own. Each such scope is marked unreachable with the reason; the unresolvable ones already explain
362
+ * themselves.
363
+ */
364
+ private markRefusedTogether;
298
365
  /**
299
366
  * Build the principal set a dimension's expansion query may bind.
300
367
  *
@@ -313,6 +380,34 @@ export declare class SearchEngine extends BaseSingleton<SearchEngine> {
313
380
  }): ScopePrincipals;
314
381
  /** Explain a single scope. Never throws — a failure to resolve IS the explanation. */
315
382
  private explainOneScope;
383
+ /**
384
+ * What a scope's configuration lets it reach. One judgement, used by the dry run and the search path — and
385
+ * the search path calls exactly the `Providers` it returns, so the two cannot disagree about who runs.
386
+ *
387
+ * A GLOBAL scope runs unconstrained (the search path never builds constraints for it), so with no
388
+ * lanes it is unbounded. A NON-global scope is bounded by its rows: it runs only the providers its enabled
389
+ * rows name that are configured and available (and support preview, for a preview search), and of those
390
+ * only the ones that read a lane kind the scope has an active lane of (`BaseSearchProvider.ConsumesLaneKinds`).
391
+ * With none of those, it reaches nothing — an empty configuration never means "everything". A skipped lane
392
+ * (only a dry run has one) is a problem the real search refuses on, so it makes the scope unreachable too.
393
+ */
394
+ private judgeScopeBound;
395
+ /** {@link judgeScopeBound} for a global scope, which runs every available provider unconstrained. */
396
+ private judgeGlobalScopeBound;
397
+ /** The configured entries a search may call: available now, and preview-capable for a preview search. */
398
+ private availableProviders;
399
+ /**
400
+ * The available entries a NON-global scope's enabled provider rows name. A non-global scope runs ONLY the
401
+ * providers it lists: no enabled row means no provider, never every provider (disabling a scope's last row
402
+ * used to widen it to all of them).
403
+ */
404
+ private runnableScopeProviders;
405
+ /**
406
+ * Of `entries`, the ones with at least one ACTIVE lane of a kind they read (`ConsumesLaneKinds`). A provider
407
+ * whose lane kinds are all empty in the scope is never called: it could only search nothing, or — written with
408
+ * the old `?.length` pattern — fall back to its unscoped default.
409
+ */
410
+ private providersWithAnActiveLane;
316
411
  /** Resolve entitlement for the dry run, including the skill and tenant principals.
317
412
  * `protected`, like {@link principalsFrom}, so a test can drive it without weak-typed casts.
318
413
  */
@@ -353,14 +448,79 @@ export declare class SearchEngine extends BaseSingleton<SearchEngine> {
353
448
  /** Render a filter of unknown shape as a display string. */
354
449
  private stringifyFilter;
355
450
  /**
356
- * Load `ScopeBundle`s for each requested scope ID, filtering out inactive / expired.
357
- * Returns an empty array when no scope IDs are supplied (caller treats as Global).
451
+ * Load the `ScopeBundle` of each requested scope ID that names a scope active right now, and collect the IDs
452
+ * that do not (inactive, expired, or missing). A search refuses when any ID is unresolved
453
+ * ({@link refuseUnresolvableScopes}); `ExplainScope` reports the same. No IDs → no bundles, which the
454
+ * search treats as Global.
358
455
  */
359
456
  private resolveScopes;
457
+ /**
458
+ * Refuse a search that named a scope the engine cannot resolve (inactive, expired, or missing): an error
459
+ * result and a `Failure` row in `MJ: Search Execution Logs`, never a wider search.
460
+ *
461
+ * Before, an unresolvable scope was skipped, and a search whose scopes were all skipped ran UNSCOPED —
462
+ * every provider, every entity, no scope filter — because no resolved scope reads as Global. Refused when
463
+ * ANY named scope fails, not only when all do: dropping one of several scopes silently changes what the
464
+ * caller asked for, and nothing in the results would tell them. An error result is how the engine already
465
+ * reports a scope it refuses (a `ScopeDimensionError`, a restricting filter that did not render).
466
+ */
467
+ private refuseUnresolvableScopes;
360
468
  /**
361
469
  * Execute all scoped providers for a single scope bundle and return per-scope fused results.
362
470
  */
363
471
  private executeScopeBundle;
472
+ /**
473
+ * Hold one scope's hits to its lane bounds, before fusion, in three steps:
474
+ * 1. every hit, against the lane `ExtraFilter` of the entity it names ({@link enforceLaneExtraFilters});
475
+ * 2. content-item promotion: a `MJ: Content Items` hit derived from an entity record becomes that record,
476
+ * marked `PromotedFromContentItemID` (`SearchEnricher.ExcludeEntitySourcedContentItems`);
477
+ * 3. every PROMOTED hit, against the lane `ExtraFilter` of the origin entity it now names.
478
+ *
479
+ * Step 1 holds a content-item hit to a Content Items lane; step 3 holds the record it became to that
480
+ * record's lane. Promotion used to run once, after cross-scope fusion, so a promoted hit met no lane bound:
481
+ * a vector hit on a content item became a row of a bounded entity from outside the bound. `searchInternal`
482
+ * promotes only unconstrained results (which have no lane bounds), so nothing is promoted twice.
483
+ */
484
+ private boundScopeHits;
485
+ /** Content-item promotion, per provider list. A list with no `MJ: Content Items` hit comes back unchanged, unread. */
486
+ private promoteContentItems;
487
+ /**
488
+ * Enforce each entity lane's rendered `ExtraFilter` on the hits of every OTHER provider.
489
+ *
490
+ * The entity lane applies its ExtraFilter in SQL. The full-text and tag lanes take only the lanes'
491
+ * entity NAMES, and the vector and 3rd-party lanes key off their own index rows — so a scope that bounds
492
+ * an entity with an ExtraFilter still returned rows outside it through every lane but one. Here a hit for
493
+ * an entity with a lane ExtraFilter in this scope is kept only when its record satisfies that filter,
494
+ * read as the user: `PK IN (...) AND (<ExtraFilter>)`, one RunView per filtered entity per scope (the
495
+ * permission pass's readability check, with the lane's filter as the clause). The filter is the exact
496
+ * string the entity lane runs: same template, same context, same escaping.
497
+ *
498
+ * Exemption follows the provider the ENGINE stamped on the hit (`ProviderId`, through
499
+ * {@link ProviderForResult}): only a provider declaring `BaseSearchProvider.AppliesLaneExtraFilter` (the entity
500
+ * provider) applied the filter already. `SourceType` is provider-declared and proves nothing, and a promoted
501
+ * content-item hit is never exempt (the filter it met, if any, was the Content Items lane's). Storage files are
502
+ * not entity records and pass. `pass` is `'promoted'` to check only promoted hits ({@link boundScopeHits}).
503
+ * Fails closed: a failed read drops that entity's hits from the other providers.
504
+ */
505
+ private enforceLaneExtraFilters;
506
+ /**
507
+ * Each entity's lane bound, keyed by {@link laneEntityKey}. Several lanes on one entity are a union (the
508
+ * entity lane searches each), so their filters are ORed; an entity with any UNFILTERED lane is unbounded
509
+ * for this scope and gets no entry. A lane whose entity could not be named is skipped.
510
+ */
511
+ private laneEntityBounds;
512
+ /** An entity name normalised for matching a hit's `EntityName` to a lane's. */
513
+ private laneEntityKey;
514
+ /**
515
+ * The lane bound `item` must satisfy in this `pass`, or `undefined` when it has none: a storage file, a hit
516
+ * from a provider that applied the lane filter itself, a hit for an entity with no filtered lane — or, in the
517
+ * `'promoted'` pass, a hit that was not promoted (step 1 of {@link boundScopeHits} already checked it).
518
+ */
519
+ private laneBoundFor;
520
+ /** The candidate hits whose record satisfies its entity's lane bound — one read per entity, in parallel. */
521
+ private hitsInsideLaneFilters;
522
+ /** `hits` (all of `bound`'s entity) whose record satisfies the lane filter, read as the user; none when the read fails. */
523
+ private hitsInsideLaneFilter;
364
524
  /**
365
525
  * Assemble a `ScopeConstraints` for a single scope: Nunjucks-render each template
366
526
  * field against the `SearchContext`, then hand the rendered values to providers.
@@ -369,12 +529,12 @@ export declare class SearchEngine extends BaseSingleton<SearchEngine> {
369
529
  * Fail a search CLOSED when a scope field that RESTRICTS was authored but did not render
370
530
  * usably (see `CheckRenderedTemplate`).
371
531
  *
372
- * Throwing rather than dropping the offending row is deliberate. Dropping it would empty
373
- * the row collection, and `buildScopeConstraints` collapses an empty collection to
374
- * `undefined` — which every provider reads as "unscoped", i.e. all entities / all indexes
375
- * with no filter. So the surgical-looking fix is the one that widens; failing the search
376
- * is the one that doesn't. A broken restricting template is a misconfiguration and should
377
- * be loud and actionable, never silently degraded into a wider search.
532
+ * Throwing rather than dropping the offending row is deliberate. Dropping one lane of
533
+ * several would quietly change what the scope covers, and a scope's ONLY lane dropped used to
534
+ * collapse to `undefined` — "unscoped" to every provider. (A non-global scope now hands providers
535
+ * an empty list, which means "nothing", but a silently narrowed scope is still a wrong answer.)
536
+ * A broken restricting template is a misconfiguration and should be loud and actionable, never
537
+ * silently degraded.
378
538
  */
379
539
  protected assertRestrictingTemplateRendered(source: string | null | undefined, rendered: unknown, fieldName: string, scopeLabel: string, rowLabel: string, laneID: string, collector?: LaneProblemCollector): void;
380
540
  /**
@@ -396,6 +556,26 @@ export declare class SearchEngine extends BaseSingleton<SearchEngine> {
396
556
  */
397
557
  private reportLaneProblem;
398
558
  private buildScopeConstraints;
559
+ /** One external-index lane's constraint, with its restricting fields guarded. */
560
+ private buildExternalIndexConstraint;
561
+ /** One entity lane's constraint: its `ExtraFilter` rendered for T-SQL and guarded. */
562
+ private buildEntityConstraint;
563
+ /**
564
+ * One storage lane's constraint. `FolderPath` RESTRICTS — it is what confines the lane to one folder
565
+ * of the account — so a FolderPath that was authored but renders empty, with an empty segment, with
566
+ * a `..` segment, or with an interpolated value the `path` escaper refuses makes the lane unusable:
567
+ * the search is refused (or, in a dry run, the lane is reported skipped). An absent FolderPath still
568
+ * means the whole account.
569
+ */
570
+ private buildStorageConstraint;
571
+ /**
572
+ * Render a storage lane's FolderPath on the `path` lane. The renderer throws when an interpolated value
573
+ * is `..` or `.`, or contains a separator; that is reported as the lane's problem (undefined is returned
574
+ * only in a dry run, where the problem is collected instead of thrown).
575
+ */
576
+ private renderFolderPath;
577
+ /** A FolderPath problem, in the wording `assertRestrictingTemplateRendered` uses for every restricting field. */
578
+ private reportFolderPathProblem;
399
579
  /** Resolve the EntityID → EntityName via MJ Metadata (for passing to providers that key by name). */
400
580
  private lookupEntityName;
401
581
  /**
@@ -411,6 +591,31 @@ export declare class SearchEngine extends BaseSingleton<SearchEngine> {
411
591
  * (uncapped) is the default when no scope sets a budget.
412
592
  */
413
593
  private pickRerankerBudgetCents;
594
+ /**
595
+ * The per-provider over-fetch multiplier for this search, in priority order: the caller's
596
+ * `SearchParams.PermissionOverfetchFactor`; else the **largest** of each resolved scope's declared
597
+ * `ScopeConfig.permissionOverfetchFactor` (a scope that declares none counts as the engine default);
598
+ * else the engine default. Clamped to `[1, MAX_OVERFETCH_FACTOR]`.
599
+ *
600
+ * The largest wins across scopes, not the first: over-fetch exists to compensate for late
601
+ * permission filtering, and a lane trimmed heavily by it needs the extra candidates whichever
602
+ * scope it belongs to. A larger factor never changes which results the caller gets (the final
603
+ * list is still trimmed to `MaxResults`), but it does cost more: every provider returns more
604
+ * candidates, dedup, the content exclusion and the permission passes do more work, a re-ranker is
605
+ * fed up to its `inputTopN` from a bigger pool, and `streamSearch`'s per-provider partial events
606
+ * (capped to the caller's `MaxResults`) draw from it. This is why a scope may declare it at all:
607
+ * the scope's author knows how sparse its lanes are after permissions, and every caller shouldn't
608
+ * have to.
609
+ */
610
+ protected ResolvePermissionOverfetchFactor(params: SearchParams, resolvedScopes: ScopeBundle[]): number;
611
+ /** A scope's declared `ScopeConfig.permissionOverfetchFactor`, when it is a finite number. Anything else is "not declared". */
612
+ private scopeOverfetchFactor;
613
+ /**
614
+ * Hold the factor to `[1, MAX_OVERFETCH_FACTOR]`. Below 1 would under-fetch the caller's own `topK`;
615
+ * above the ceiling, a single metadata edit would multiply every provider call for every caller of
616
+ * the scope (vector providers bill per candidate). A clamped value is logged so the author sees it.
617
+ */
618
+ private clampOverfetchFactor;
414
619
  private runReRanker;
415
620
  /**
416
621
  * Instantiate a single provider from its SearchProvider metadata record,
@@ -427,35 +632,139 @@ export declare class SearchEngine extends BaseSingleton<SearchEngine> {
427
632
  */
428
633
  private countSources;
429
634
  /**
430
- * Filter search results by entity-level and row-level security permissions.
635
+ * Filter search results by entity-level and row-level security permissions, then by whether the user
636
+ * may read the record each content result was derived from.
431
637
  *
432
- * **This is a safety net.** Providers are expected to do per-provider permission
433
- * push-down (Section 3.6 of plans/search-scopes-rag-plus.md). If this filter is
434
- * removing more than a handful of results in practice, the responsible provider's
435
- * push-down is incomplete and should be fixed.
638
+ * **Steps 1–4 are a safety net.** Providers are expected to do per-provider permission
639
+ * push-down (Section 3.6 of plans/search-scopes-rag-plus.md). If those steps remove more
640
+ * than a handful of results in practice, the responsible provider's push-down is incomplete
641
+ * and should be fixed. **Step 5 is not**: it drops by design, because no provider can push
642
+ * an origin record's own row filters down into a content index. Its removals are counted
643
+ * into `stats.OriginGateRemoved`, so the late-filter count keeps its meaning.
436
644
  *
437
645
  * Groups results by entity for efficient permission checking:
438
646
  * 1. Unknown entities are excluded (fail closed).
439
647
  * 2. If the user lacks entity-level CanRead, all results for that entity are dropped.
440
648
  * 3. If the user is exempt from RLS, all results pass through.
441
649
  * 4. If RLS applies, a RunView validates which record IDs the user can read.
650
+ * 5. Content items and chunks are kept only when the user may read the record they were
651
+ * derived from ({@link VerifyOriginRecords}).
652
+ *
653
+ * `storage-file` results take their own path ({@link filterStorageResults}): they are re-checked against
654
+ * the storage-account permission model for this user, never passed through on the strength of their type.
655
+ *
656
+ * @param stats optional per-call counters; `OriginGateRemoved` is incremented by step 5's removals
442
657
  */
443
- protected filterByPermissions(results: SearchResultItem[], contextUser: UserInfo): Promise<SearchResultItem[]>;
658
+ protected filterByPermissions(results: SearchResultItem[], contextUser: UserInfo, stats?: {
659
+ OriginGateRemoved: number;
660
+ }): Promise<SearchResultItem[]>;
661
+ /**
662
+ * The storage half of {@link filterByPermissions}: re-check `storage-file` results for `contextUser` and push the
663
+ * ones that pass into `permitted`.
664
+ *
665
+ * `ResultType` is set by whichever provider produced a result, so being typed `storage-file` proves nothing. A
666
+ * storage hit is kept only when ALL hold:
667
+ * - its `ProviderId` — stamped by this engine on every result, overwriting whatever the provider set — names a
668
+ * configured entry whose provider is a {@link StorageSearchProvider};
669
+ * - the account it names (`RawMetadata.accountId`, as that provider writes it) is one `contextUser` may read now,
670
+ * per `StorageAccessEvaluator` (per call; the account-without-rows rule lives there); and
671
+ * - the object it names (`RawMetadata.path` / `objectId`) does not back an `MJ: Files` row `contextUser` may not
672
+ * read — the tracked-file rule `CreatePreAuthDownloadUrl` applies, so a hit never names (or excerpts) a file the
673
+ * caller would be refused ({@link dropUnreadableTrackedStorageHits}).
674
+ *
675
+ * Anything else — no or a foreign `ProviderId`, missing or unparseable metadata, an evaluator failure or throw —
676
+ * drops the result (fail closed). Order is restored by the caller.
677
+ */
678
+ private filterStorageResults;
679
+ /**
680
+ * The tracked-file rule on storage hits: grouped by account, each account's hits are checked in one batched lookup
681
+ * against the `MJ: Files` rows on that account's provider (`StorageAccessEvaluator.UnreadableTrackedObjectKeys`,
682
+ * compared the way the account's driver addresses keys), and a hit whose path or object ID backs a row the caller
683
+ * may not read is dropped. An account whose provider or driver cannot be resolved loses all its hits (fail closed).
684
+ */
685
+ private dropUnreadableTrackedStorageHits;
686
+ /** {@link dropUnreadableTrackedStorageHits} for one account's hits; any failure drops them all. */
687
+ private readableTrackedStorageHits;
688
+ /**
689
+ * The storage results that came from a configured {@link StorageSearchProvider} entry and name a well-formed account
690
+ * and at least one object key, paired with them. Everything else is left out, which drops it.
691
+ */
692
+ private storageCandidates;
693
+ /**
694
+ * The account (`RawMetadata.accountId`) and object keys (`RawMetadata.path`, `RawMetadata.objectId`) a
695
+ * `storage-file` result names, or null when the account is absent or malformed or no object key is present.
696
+ */
697
+ private storageLocationOf;
444
698
  /**
445
699
  * Group search result items by EntityName for batch permission checking.
446
700
  */
447
701
  private groupResultsByEntity;
448
702
  /**
449
703
  * Check permissions for a single entity's batch of results.
450
- * Permitted results are pushed into the shared `permitted` array.
704
+ * Permitted results are pushed into the shared `permitted` array; rows the origin-record gate removes are
705
+ * counted into `stats` when it is supplied.
451
706
  * On any error, results are excluded (fail closed).
452
707
  */
453
708
  private filterEntityResults;
454
709
  /**
455
- * Lanes whose results are self-evidently records of the entity they are labelled with, because the
456
- * provider obtained them by querying that entity through `RunView`. Everything else — the vector
457
- * lane, and any 3rd-party provider keyed by its own `SourceType` — carries a label supplied by
458
- * whatever populated the index, and must be verified before its permissions are trusted.
710
+ * Gate 1: the results that are rows of `entity` the user may read.
711
+ *
712
+ * With no row filter (or a user exempt from row filtering) that settles WHICH ROWS of this entity they may
713
+ * see — it does not establish that these results ARE this entity's rows. `EntityName` is provider output,
714
+ * and for the vector and 3rd-party lanes it comes from the index: vector metadata's `Entity` key, or the
715
+ * index name. Admitting on that label alone lets whoever writes the index choose which entity's
716
+ * permissions get evaluated, so a label naming an entity the user CAN read admits documents that are not
717
+ * that entity's records at all.
718
+ *
719
+ * Results that came out of a RunView against the entity need no such check, so those pass untouched (this
720
+ * is the hot path and its cost is unchanged) and only the rest are verified — see {@link isSelfEvidentRow}
721
+ * for which results qualify. When a row filter applies, every result is verified: ownership is checked as
722
+ * a side effect of filtering.
723
+ */
724
+ private admitOwnRows;
725
+ /**
726
+ * Whether `item` is self-evidently a row of the entity it is labelled with: the engine stamped it with a
727
+ * configured provider that reads that entity through `RunView`
728
+ * ({@link BaseSearchProvider.ResultsAreRowsOfLabelledEntity}), AND it carries one of the lanes in
729
+ * {@link lanesWithSelfEvidentOwnership}.
730
+ *
731
+ * Trust follows the engine's stamp, never the label. `SourceType` is provider output and `SearchSource` is a
732
+ * closed union, so every shipped external-index provider (Azure AI Search, Typesense, Elasticsearch,
733
+ * OpenSearch) stamps `'fulltext'` with the index name as `EntityName`, and a third-party provider may stamp
734
+ * `'entity'`. A result with no `ProviderId` (a fusion fallback, a hand-built hit) or one naming no configured
735
+ * provider is verified, and so is a hit promoted from a content item to its origin record
736
+ * (`PromotedFromContentItemID`): its provider read the content item, never the origin row.
737
+ *
738
+ * Fusion and dedup never move a `ProviderId` onto another item's `EntityName`/`RecordID`/`SourceType`: each
739
+ * merged result is one provider's item, whole, and only scores, `ScoreBreakdown`, tags and (dedup) a snippet
740
+ * replacing a generic one are taken from the items it absorbed. Those may be from rows nothing verified:
741
+ * `Deduplicate` merges items sharing `EntityName` + `RecordID`, but per-scope RRF (`SearchFusion.applyRRF`)
742
+ * merges `ScoreBreakdown` across items sharing only a `RecordID` — of any entity — keeping the first. So a
743
+ * merge can lend a trusted item another item's scores, never its trust: trust is the surviving item's own.
744
+ */
745
+ private isSelfEvidentRow;
746
+ /**
747
+ * The configured provider that read the row `item` names — {@link ProviderForResult}, except for a hit the
748
+ * engine promoted from a content item to its origin record (`PromotedFromContentItemID`), whose row no
749
+ * provider read. Both per-provider trust decisions resolve through here: ownership
750
+ * (`ResultsAreRowsOfLabelledEntity`, {@link isSelfEvidentRow}) and the lane `ExtraFilter` exemption
751
+ * (`AppliesLaneExtraFilter`, {@link laneBoundFor}).
752
+ */
753
+ private providerThatReadRow;
754
+ /**
755
+ * The configured provider whose engine-stamped `ProviderId` `item` carries, or `undefined` when it carries
756
+ * none or names no configured provider. The engine overwrites `ProviderId` on every result a provider
757
+ * returns, before fusion.
758
+ *
759
+ * Protected so a probe can map a hand-built hit to a provider instance without configuring the engine. It
760
+ * decides which results skip ownership verification and which skip the lane `ExtraFilter` re-check, so an
761
+ * override must only ever return the provider that actually produced the result.
762
+ */
763
+ protected ProviderForResult(item: SearchResultItem): BaseSearchProvider | undefined;
764
+ /**
765
+ * Lanes whose results can be self-evident rows of the entity they are labelled with — a necessary
766
+ * condition only: the provider that produced the result must also say it reads that entity through
767
+ * `RunView` (see {@link isSelfEvidentRow}). The vector lane, and anything else, is always verified.
459
768
  *
460
769
  * An allowlist rather than a denylist on purpose: a `SourceType` nobody anticipated is verified by
461
770
  * default instead of trusted by default.
@@ -468,10 +777,158 @@ export declare class SearchEngine extends BaseSingleton<SearchEngine> {
468
777
  * record of this entity is dropped whether or not a row filter exists.
469
778
  */
470
779
  private verifyOwnershipAndRowFilters;
471
- /** `PK IN ('a','b',...)` — the fast path for the overwhelmingly common single-column key. */
780
+ /**
781
+ * Ask the database, as `contextUser`, which of `recordIDs` are rows of `entity` the user may read:
782
+ * `PK IN (...)`, ANDed with `rlsClause` when one applies, run through RunView so the user's own row
783
+ * filters apply as well. Returns the matching keys in {@link canonicalKeyValues} form, or `null`
784
+ * when the question could not be asked (no primary key, no usable record id, RunView failed) — the
785
+ * caller fails closed.
786
+ */
787
+ private readableRecordKeys;
788
+ /**
789
+ * The RunView behind {@link readableRecordKeys}, projecting only the key. `null` when it cannot be asked:
790
+ * the entity has no primary key, or no record id names a key of it (both logged).
791
+ *
792
+ * `MaxRows` is the number of ids, since each matches at most one row: left unset, the entity's
793
+ * `UserViewMaxRows` could truncate the answer and silently drop readable results.
794
+ */
795
+ private readableKeysParams;
796
+ /** The keys a {@link readableKeysParams} RunView returned, in {@link canonicalKeyValues} form; `null` (logged) when it failed. */
797
+ private readableKeySet;
798
+ /**
799
+ * `PK IN ('a','b',...)` — the fast path for the overwhelmingly common single-column key. Each id is
800
+ * read as a key segment first, so a bare value and a prefixed `ID|value` segment (the encoding
801
+ * `CompositeKey.ToRecordID()` writes) both compare on the value alone.
802
+ */
472
803
  private buildSingleKeyMembership;
473
- /** `(F1='v1' AND F2='v2') OR (...)` — one term per composite-key result. */
804
+ /**
805
+ * `(F1='v1' AND F2='v2') OR (...)` — one term per composite-key record. The field names come from the
806
+ * record id, so only a segment {@link parseCompositeKey} accepts reaches the SQL, under the metadata's own
807
+ * names; any other is dropped (logged). Empty when no segment is usable.
808
+ */
474
809
  private buildCompositeKeyMembership;
810
+ /**
811
+ * A composite-key segment rebuilt on `entity`'s own primary-key names, or `null` when it names a field that
812
+ * is not a primary key of `entity` or leaves one out. Names match case-insensitively and are replaced by
813
+ * the metadata's, so nothing parsed from a record id is interpolated into SQL as an identifier.
814
+ */
815
+ private parseCompositeKey;
816
+ /**
817
+ * The {@link canonicalKeyValues} form of the key `recordID` names in `entity`, to match against the rows a
818
+ * readability check returned. `null` for a composite-key segment {@link parseCompositeKey} rejects.
819
+ */
820
+ private recordMatchKey;
821
+ /**
822
+ * Second gate, after a result is known to be a readable row of its own entity: may the user also
823
+ * read the record the row was DERIVED from?
824
+ *
825
+ * Row-level security on a content entity settles who may read the content table. It cannot say
826
+ * whether the person may read the file, task or conversation that content was extracted from —
827
+ * that permission lives on the origin entity, under its own row filters. Without this gate, a
828
+ * chunk of a document the user may not open passes the first gate and is quoted anyway.
829
+ *
830
+ * For `MJ: Content Items` and `MJ: Content Item Chunks` (and any IS-A subtype of either) the
831
+ * default follows chunk → item (→ root item, for a split child) → `MJ: Entity Record Documents`
832
+ * → the origin record, and keeps a result only when the origin is a row the user may read,
833
+ * verified the way {@link verifyOwnershipAndRowFilters} verifies the result's own entity. A
834
+ * content row with no Entity Record Document (crawled, uploaded, external) has no origin and
835
+ * passes unchanged, as does every result of a non-content entity.
836
+ *
837
+ * Every lookup runs as the user, and that is a NEW requirement on who may see content hits: read on
838
+ * the base `MJ: Content Items` for anyone who sees chunk hits (the chunk → item hop reads it), and read
839
+ * on `MJ: Entity Record Documents` for anyone who sees hits derived from a record (the item → document
840
+ * hop reads it). An app that indexes documents behind its own permissions grants those, under its
841
+ * own row filters. Without them the affected rows are dropped: every row of the group for the chunk
842
+ * and item hops, only the document-bearing rows for the document hop.
843
+ *
844
+ * The origin's own permissions are checked once; an origin that is itself a content row is not walked
845
+ * again. Protected so a host can extend the rule to another derived-content family. Fails closed: a
846
+ * lookup that reports failure, or returns a row without a column it asked for (field-level security),
847
+ * drops the rows that depended on it; a lookup that throws drops the whole group. It never widens.
848
+ */
849
+ protected VerifyOriginRecords(entity: EntityInfo, results: SearchResultItem[], contextUser: UserInfo): Promise<SearchResultItem[]>;
850
+ /**
851
+ * Where `entity` sits in the content family: `'chunk'` for `MJ: Content Item Chunks` or a subtype,
852
+ * `'item'` for `MJ: Content Items` or a subtype, `null` for anything else. Walks `ParentID` on the
853
+ * request's provider; a cycle in the metadata ends the walk rather than looping.
854
+ */
855
+ private contentFamilyLevel;
856
+ /**
857
+ * A content result's `RecordID` as the key value the origin lookups query and the origin map is keyed by.
858
+ * Read as a key segment, exactly as gate 1 reads it, so a prefixed `ID|value` id resolves to its value.
859
+ * Empty when the segment does not name the entity's key.
860
+ */
861
+ private contentRecordKey;
862
+ /**
863
+ * Resolve each result to its origin record. The returned map is keyed by {@link contentRecordKey}; a
864
+ * value of `null` means "a content row with no origin" (it passes); a missing key means a link in the
865
+ * chain could not be read as this user (it is dropped).
866
+ *
867
+ * Failures are scoped to the rows that depended on the failed hop. Every row depends on the chunk
868
+ * and item hops, so a failed lookup there throws and the caller drops the group. Only split children
869
+ * depend on the root hop, and only document-bearing items on the Entity Record Document hop, so a
870
+ * failure there leaves just those rows unresolved and lets the rest through on their own merits.
871
+ */
872
+ private resolveContentOrigins;
873
+ /**
874
+ * chunk id → owning Content Item id, read through the chunk entity's own view as the user. Every
875
+ * chunk result depends on this hop, so a failed lookup throws and the group is dropped.
876
+ */
877
+ private lookupChunkItems;
878
+ /**
879
+ * Content Item id → its Entity Record Document id, `null` when it has none.
880
+ *
881
+ * Always read through the base `MJ: Content Items`, whatever entity the result was labelled with:
882
+ * `RootParentID` is a view-computed column, and an IS-A subtype's view projects only its parent's
883
+ * base columns, so reading a subtype would silently lose the root link and let a split child
884
+ * through as "no origin". The key is shared across the family, so the base view holds every row.
885
+ *
886
+ * A split child is judged by its own document first and by its root's only when it has none — one more
887
+ * hop, taken once. A failed root lookup leaves only those children unresolved (dropped); a failed item
888
+ * lookup throws, since every row depends on it.
889
+ */
890
+ private lookupItemOrigins;
891
+ /**
892
+ * Sort item rows: an item with its own document, or a root (no `ParentID`) with none, goes straight into
893
+ * `map`; a split child with no document of its own is returned as child → root, to be judged by its root.
894
+ * The view gives a root its own id as `RootParentID`, so a root is never re-read. A child whose
895
+ * `RootParentID` is missing or names itself (the view could not walk its `ParentID` chain) goes nowhere:
896
+ * unresolved, so dropped, rather than passed as "no origin".
897
+ */
898
+ private classifyItemRows;
899
+ /**
900
+ * Entity Record Document id → the (entity, record) it documents, read as the user. Only document-bearing
901
+ * items depend on this hop, so a failed lookup resolves nothing here and drops those rows alone. A
902
+ * document that names no entity or record resolves nothing either.
903
+ */
904
+ private lookupEntityRecordDocuments;
905
+ /**
906
+ * One `Fields` projection of `entityName` where `keyField IN (ids)`, as the user. `null` (logged) when the
907
+ * RunView fails, or when a row comes back without one of `fields`: field-level security drops a denied
908
+ * column from the projection silently, and reading the absent column as null would turn "may not see the
909
+ * link" into "has no origin" and let the hit through. The caller decides how far the failure reaches.
910
+ * `MaxRows` is the number of ids (each matches at most one row), so `UserViewMaxRows` cannot truncate it.
911
+ */
912
+ private runLookup;
913
+ /**
914
+ * Keep the results whose origin record the user may read. Origins are verified through
915
+ * {@link ReadableOriginRecordIDs}: one batch, one view per origin entity.
916
+ */
917
+ private keepReadableOrigins;
918
+ /**
919
+ * For each origin entity, those of its record ids the user may read under that entity's own permissions and
920
+ * row filters — the check {@link verifyOwnershipAndRowFilters} gives a result's own entity. All entities are
921
+ * asked in one `RunViews` batch. An entity the provider does not know, the user may not read at all, or
922
+ * whose view fails gets no entry, so only the rows derived from it are dropped.
923
+ *
924
+ * Protected so a host extending {@link VerifyOriginRecords} to another derived-content family can reuse it.
925
+ *
926
+ * @param idsByEntity origin entity name → record ids, each a bare key value or a key segment
927
+ * @returns origin entity name → the ids (as given) of the rows the user may read
928
+ */
929
+ protected ReadableOriginRecordIDs(idsByEntity: Map<string, string[]>, contextUser: UserInfo): Promise<Map<string, Set<string>>>;
930
+ /** The readability view for each origin entity the user may read at all. The rest get none: not readable. */
931
+ private originReadChecks;
475
932
  /**
476
933
  * Key values in primary-key metadata order, UUID-normalized and joined — the comparison form for
477
934
  * matching a result's RecordID against the rows the database returned. Field-name lookup is