@coasys/ad4m 0.13.1-staging.2 → 0.13.1-staging.3

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 (43) hide show
  1. package/lib/index.cjs +584 -203
  2. package/lib/index.js +581 -204
  3. package/lib/src/Ad4mClient.d.ts +7 -0
  4. package/lib/src/Ad4mClient.js +9 -0
  5. package/lib/src/apiClient.d.ts +13 -0
  6. package/lib/src/apiClient.js +67 -12
  7. package/lib/src/generated/api/AuthInfo.d.ts +4 -0
  8. package/lib/src/generated/api/RuntimeInfo.d.ts +5 -0
  9. package/lib/src/index.d.ts +1 -0
  10. package/lib/src/index.js +1 -0
  11. package/lib/src/model/Ad4mModel.js +45 -18
  12. package/lib/src/model/ModelQueryBuilder.d.ts +7 -3
  13. package/lib/src/model/ModelQueryBuilder.js +9 -4
  14. package/lib/src/model/query-common.js +7 -1
  15. package/lib/src/model/types.d.ts +45 -2
  16. package/lib/src/model/types.js +8 -0
  17. package/lib/src/perspectives/Container.d.ts +41 -0
  18. package/lib/src/perspectives/Container.js +62 -0
  19. package/lib/src/perspectives/PerspectiveProxy.d.ts +6 -3
  20. package/lib/src/perspectives/PerspectiveProxy.js +10 -4
  21. package/lib/src/perspectives/WakerSubscriptionManager.d.ts +94 -12
  22. package/lib/src/perspectives/WakerSubscriptionManager.js +273 -72
  23. package/lib/src/runtime/RuntimeTypes.d.ts +2 -0
  24. package/package.json +2 -2
  25. package/src/Ad4mClient.test.ts +1 -1
  26. package/src/Ad4mClient.ts +10 -0
  27. package/src/apiClient.test.ts +128 -2
  28. package/src/apiClient.ts +64 -11
  29. package/src/generated/api/AuthInfo.ts +6 -1
  30. package/src/generated/api/RuntimeInfo.ts +6 -1
  31. package/src/index.ts +1 -0
  32. package/src/model/Ad4mModel.ts +51 -19
  33. package/src/model/ModelQueryBuilder.ts +9 -6
  34. package/src/model/containment-scope.test.ts +104 -0
  35. package/src/model/query-common.ts +10 -1
  36. package/src/model/types.ts +56 -2
  37. package/src/perspectives/Container.test.ts +65 -0
  38. package/src/perspectives/Container.ts +46 -0
  39. package/src/perspectives/PerspectiveProxy.test.ts +11 -0
  40. package/src/perspectives/PerspectiveProxy.ts +10 -4
  41. package/src/perspectives/WakerSubscriptionManager.test.ts +398 -80
  42. package/src/perspectives/WakerSubscriptionManager.ts +318 -82
  43. package/src/runtime/RuntimeTypes.ts +2 -0
package/lib/index.js CHANGED
@@ -137,7 +137,12 @@ function nextId() {
137
137
  * for the next socket is safe for writes too. This covers an executor that
138
138
  * is still binding its port (about 1.5 s with the reconnect backoff). */
139
139
  const MAX_CONNECT_ATTEMPTS = 3;
140
- const closedError = () => new RpcError(503, 'WebSocket connection closed');
140
+ const closedError = (reason) => new RpcError(503, reason || 'WebSocket connection closed');
141
+ /** Close code for "try again later": the executor's wallet is locked, so it cannot check the
142
+ * token yet. The token may be good: reconnect as for any close, and pass the reason on. */
143
+ const CLOSE_TRY_AGAIN_LATER = 1013;
144
+ /** Close code the executor uses when the socket's token opens no session, expired or was revoked. */
145
+ const CLOSE_AUTH_FAILED = 1008;
141
146
  class ApiClient {
142
147
  constructor(baseUrl, token, webSocketImpl, fetchImpl) {
143
148
  // ── WebSocket ───────────────────────────────────────────────────────────
@@ -148,6 +153,10 @@ class ApiClient {
148
153
  /** `on()` handlers by event type; a type with none has no entry. */
149
154
  this._handlers = new Map();
150
155
  this._reconnectCallbacks = new Set();
156
+ this._authFailedCallbacks = new Set();
157
+ /** Set once the executor refused the token: the reason. The client then
158
+ * never connects again; a new token needs a new client. */
159
+ this._authFailed = null;
151
160
  this._hasConnectedOnce = false;
152
161
  this._pendingCalls = new Map();
153
162
  this._wsReconnectTimer = null;
@@ -183,6 +192,8 @@ class ApiClient {
183
192
  _ensureWs() {
184
193
  if (this._ws)
185
194
  return;
195
+ if (this._authFailed !== null)
196
+ throw new RpcError(401, this._authFailed);
186
197
  const WsImpl = this._webSocketImpl ?? globalThis.WebSocket;
187
198
  const ws = new WsImpl(this._getWsUrl());
188
199
  this._ws = ws;
@@ -191,9 +202,17 @@ class ApiClient {
191
202
  resolve();
192
203
  this._onOpen(ws);
193
204
  };
194
- ws.onclose = () => {
195
- reject(closedError());
196
- this._onClose(ws);
205
+ ws.onclose = (event) => {
206
+ // Classify the close for watchApplied() as for every other waiting call.
207
+ reject(event?.code === CLOSE_AUTH_FAILED
208
+ ? new RpcError(401, event.reason || 'token expired or revoked')
209
+ : closedError(event?.code === CLOSE_TRY_AGAIN_LATER ? event.reason : undefined));
210
+ if (event?.code === CLOSE_AUTH_FAILED && this._ws === ws) {
211
+ this._failAuth(event.reason || 'token expired or revoked');
212
+ }
213
+ else {
214
+ this._onClose(ws, event?.code === CLOSE_TRY_AGAIN_LATER ? event.reason : undefined);
215
+ }
197
216
  };
198
217
  });
199
218
  // Only watchApplied() awaits this; a close before open is not an error otherwise.
@@ -213,10 +232,15 @@ class ApiClient {
213
232
  if (!pending)
214
233
  return; // late reply to a timed-out or aborted call, or a cancel ack
215
234
  const error = parsed.error;
216
- if (error)
217
- pending.reject(new RpcError(error.code ?? 500, error.message ?? 'Unknown error'));
218
- else
235
+ if (!error) {
219
236
  pending.resolve(parsed.result);
237
+ return;
238
+ }
239
+ const rpcError = new RpcError(error.code ?? 500, error.message ?? 'Unknown error');
240
+ pending.reject(rpcError);
241
+ // The executor answers 401 only when the token stopped working, then closes the socket.
242
+ if (rpcError.status === 401)
243
+ this._failAuth(rpcError.body);
220
244
  return;
221
245
  }
222
246
  if (parsed.type === 'pong')
@@ -265,7 +289,8 @@ class ApiClient {
265
289
  }
266
290
  this._hasConnectedOnce = true;
267
291
  }
268
- _onClose(ws) {
292
+ /** `reason` is set when the executor asked to try again later; calls that fail carry it. */
293
+ _onClose(ws, reason) {
269
294
  // A socket closed by _closeWs() can report after a new one exists.
270
295
  if (this._ws !== ws)
271
296
  return;
@@ -280,12 +305,25 @@ class ApiClient {
280
305
  pending.retry = false;
281
306
  }
282
307
  else {
283
- pending.reject(closedError());
308
+ pending.reject(closedError(reason));
284
309
  }
285
310
  }
286
311
  if (this._handlers.size > 0 || this._pendingCalls.size > 0)
287
312
  this._scheduleReconnect();
288
313
  }
314
+ /** The executor refused the token: fail every call with 401, stop
315
+ * reconnecting and tell the `onAuthFailed` callbacks, once. */
316
+ _failAuth(reason) {
317
+ if (this._authFailed !== null)
318
+ return;
319
+ this._authFailed = reason;
320
+ const error = new RpcError(401, reason);
321
+ for (const pending of this._pendingCalls.values())
322
+ pending.reject(error);
323
+ this._closeWs();
324
+ for (const cb of [...this._authFailedCallbacks])
325
+ callSafely(cb, 'Error in auth-failed callback:', reason);
326
+ }
289
327
  _startPing() {
290
328
  this._stopPing();
291
329
  this._wsPingTimer = setInterval(() => {
@@ -301,7 +339,7 @@ class ApiClient {
301
339
  }
302
340
  }
303
341
  _scheduleReconnect() {
304
- if (this._wsReconnectTimer)
342
+ if (this._wsReconnectTimer || this._authFailed !== null)
305
343
  return;
306
344
  const delay = this._wsReconnectDelay;
307
345
  this._wsReconnectDelay = Math.min(this._wsReconnectDelay * 2, MAX_RECONNECT_DELAY_MS);
@@ -401,7 +439,9 @@ class ApiClient {
401
439
  regs.add(reg);
402
440
  this._scheduleWatch();
403
441
  }
404
- this._ensureWs();
442
+ // A client whose token was refused keeps the handler but opens no socket.
443
+ if (this._authFailed === null)
444
+ this._ensureWs();
405
445
  return () => {
406
446
  const regs = this._handlers.get(type);
407
447
  if (!regs?.delete(reg))
@@ -468,10 +508,13 @@ class ApiClient {
468
508
  if (key === this._watching)
469
509
  return;
470
510
  this._watching = key;
471
- this._watchSent = this._request('events.watch', events).then(() => { this._watchRetries = 0; }, (e) => {
511
+ const sent = this._request('events.watch', events).then(() => { this._watchRetries = 0; }, (e) => {
472
512
  if (this._watching !== key)
473
513
  return;
474
514
  this._watching = null;
515
+ // A refused token (401) gets no next socket: watchApplied() must not resolve.
516
+ if (e instanceof RpcError && e.status === 401)
517
+ throw e;
475
518
  // A closed socket (503) gets the watch again when the next one opens.
476
519
  if (e instanceof RpcError && e.status === 503)
477
520
  return;
@@ -483,6 +526,9 @@ class ApiClient {
483
526
  }, WATCH_RETRY_DELAY_MS);
484
527
  }
485
528
  });
529
+ // Only watchApplied() awaits this; a refused watch is not an unhandled rejection otherwise.
530
+ sent.catch(() => { });
531
+ this._watchSent = sent;
486
532
  }
487
533
  _closeWs() {
488
534
  this._stopPing();
@@ -506,6 +552,14 @@ class ApiClient {
506
552
  this._reconnectCallbacks.add(callback);
507
553
  return () => { this._reconnectCallbacks.delete(callback); };
508
554
  }
555
+ /** Register a callback that fires once when the executor refuses this
556
+ * client's token: a 401 reply, or a socket closed with code 1008. Every
557
+ * call then fails with a 401 `RpcError` and the client does not reconnect;
558
+ * build a new client to use another token. Returns an unsubscribe function. */
559
+ onAuthFailed(callback) {
560
+ this._authFailedCallbacks.add(callback);
561
+ return () => { this._authFailedCallbacks.delete(callback); };
562
+ }
509
563
  /** Close the WebSocket and reject pending calls. */
510
564
  closeAll() {
511
565
  for (const pending of this._pendingCalls.values()) {
@@ -514,6 +568,7 @@ class ApiClient {
514
568
  this._closeWs();
515
569
  this._handlers.clear();
516
570
  this._reconnectCallbacks.clear();
571
+ this._authFailedCallbacks.clear();
517
572
  // A reused client must not fire onReconnect on its next first open.
518
573
  this._hasConnectedOnce = false;
519
574
  }
@@ -7487,7 +7542,7 @@ function extractNamespaceFromUri(uri) {
7487
7542
  return uri.substring(0, colonIdx + 1);
7488
7543
  return uri;
7489
7544
  }
7490
- /** A live SPARQL query with its latest result.
7545
+ /** A live SPARQL or model query with its latest result.
7491
7546
  *
7492
7547
  * `subscribe()` opens the query and resolves once the first result is in;
7493
7548
  * `onResult()` callbacks then get every later result. The executor sends
@@ -7501,14 +7556,20 @@ function extractNamespaceFromUri(uri) {
7501
7556
  * ```
7502
7557
  */
7503
7558
  class QuerySubscriptionProxy {
7504
- constructor(uuid, query, client) {
7559
+ /** With `className`, `query` is a model query (JSON) over that class or
7560
+ * union of classes, opened with `modelSubscribe`; results are
7561
+ * `{ instances, totalCount }`. Without it, `query` is SPARQL. */
7562
+ constructor(uuid, query, client, className) {
7505
7563
  _QuerySubscriptionProxy_instances.add(this);
7506
7564
  _QuerySubscriptionProxy_live.set(this, void 0);
7507
7565
  _QuerySubscriptionProxy_callbacks.set(this, new Set());
7508
7566
  _QuerySubscriptionProxy_initialized.set(this, void 0);
7509
7567
  _QuerySubscriptionProxy_initResolve.set(this, void 0);
7510
7568
  _QuerySubscriptionProxy_initReject.set(this, void 0);
7511
- __classPrivateFieldSet$6(this, _QuerySubscriptionProxy_live, new LiveQuery(client, uuid, () => client.subscribeQuery(uuid, query), result => __classPrivateFieldGet$6(this, _QuerySubscriptionProxy_instances, "m", _QuerySubscriptionProxy_deliver).call(this, result)), "f");
7569
+ const open = className === undefined
7570
+ ? () => client.subscribeQuery(uuid, query)
7571
+ : () => client.modelSubscribe(uuid, className, query);
7572
+ __classPrivateFieldSet$6(this, _QuerySubscriptionProxy_live, new LiveQuery(client, uuid, open, result => __classPrivateFieldGet$6(this, _QuerySubscriptionProxy_instances, "m", _QuerySubscriptionProxy_deliver).call(this, result)), "f");
7512
7573
  __classPrivateFieldSet$6(this, _QuerySubscriptionProxy_initialized, new Promise((resolve, reject) => {
7513
7574
  __classPrivateFieldSet$6(this, _QuerySubscriptionProxy_initResolve, resolve, "f");
7514
7575
  __classPrivateFieldSet$6(this, _QuerySubscriptionProxy_initReject, reject, "f");
@@ -7930,7 +7991,7 @@ class PerspectiveProxy {
7930
7991
  *
7931
7992
  * The state is not stored on the graph: the engine derives it from the
7932
7993
  * signed proposals and keeps what it derived per agent, outside the
7933
- * perspective. So no other agent — a co-owner on the same node included —
7994
+ * perspective. So no other agent — a co-owner on the same executor included —
7934
7995
  * can read or write your entries, and a link query never sees them.
7935
7996
  * `FlowInstance.findAll` / `start` call this for you.
7936
7997
  */
@@ -17450,6 +17511,14 @@ _AIClient_apiClient = new WeakMap(), _AIClient_transcriptionUnsubscribers = new
17450
17511
  * (`query-utils.ts`, `decorators.ts`, etc.) can import types without
17451
17512
  * creating circular runtime dependencies on `Ad4mModel.ts`.
17452
17513
  */
17514
+ /** Whether this traversal follows containment rather than a named predicate. */
17515
+ function isContainmentTraversal(scope) {
17516
+ return isTraverseScope(scope) && !('predicate' in scope && scope.predicate) && !('model' in scope && scope.model);
17517
+ }
17518
+ /** Whether this scope is the containment form, `{ id }` alone. */
17519
+ function isContainedScope(scope) {
17520
+ return !isTraverseScope(scope) && !('predicate' in scope) && !('model' in scope);
17521
+ }
17453
17522
  /**
17454
17523
  * Whether this scope is a traversal rather than a single named parent.
17455
17524
  *
@@ -17495,6 +17564,12 @@ function resolveParentPredicate(parent, childCtor) {
17495
17564
  // Raw form — explicit predicate
17496
17565
  if ('predicate' in parent)
17497
17566
  return parent.predicate;
17567
+ // Containment form — one predicate per containment edge, resolved by the
17568
+ // executor from the installed classes. There is no single one to return.
17569
+ if (isContainedScope(parent) || isContainmentTraversal(parent)) {
17570
+ throw new Error('parent(): a containment scope { id } names no single predicate; the executor resolves ' +
17571
+ 'it. Use the model query path (findAll / query / subscribe) to read it.');
17572
+ }
17498
17573
  // Model form — resolve from relation metadata
17499
17574
  const { model } = parent;
17500
17575
  const relMeta = getRelationsMetadata(model);
@@ -18620,9 +18695,10 @@ class ModelQueryBuilder {
18620
18695
  * 3. **String id + model class** — same metadata scan (or field lookup if
18621
18696
  * options include `field`).
18622
18697
  * 4. **String id + string predicate** — raw escape hatch, no metadata lookup.
18623
- *
18624
- * Passing a plain string id with no second argument throws because the
18625
- * predicate cannot be resolved without a model class.
18698
+ * 5. **String id alone** — containment through the built-in `Container`:
18699
+ * the id's `ad4m://has_child` targets, and the targets of the `children`
18700
+ * relation of every class the id is an instance of. The executor
18701
+ * resolves the predicates; nothing is looked up here.
18626
18702
  *
18627
18703
  * @param idOrInstance - The parent's expression URI **or** an Ad4mModel instance
18628
18704
  * @param modelOrPredicate - A model class (predicate auto-resolved) **or** a raw predicate string
@@ -18645,6 +18721,9 @@ class ModelQueryBuilder {
18645
18721
  *
18646
18722
  * // String id + raw predicate (escape hatch)
18647
18723
  * Recipe.query(perspective).parent(cookbookId, "cookbook://recipe").get();
18724
+ *
18725
+ * // String id alone: whatever cookbookId contains
18726
+ * Recipe.query(perspective).parent(cookbookId).get();
18648
18727
  * ```
18649
18728
  */
18650
18729
  parent(idOrInstance, modelOrPredicate, options) {
@@ -18672,7 +18751,8 @@ class ModelQueryBuilder {
18672
18751
  this.queryParams.parent = { id, model: idOrInstance.constructor, ...(field && { field }) };
18673
18752
  }
18674
18753
  else {
18675
- throw new Error('parent() called with a string id requires a second argument: either a model class or a predicate string');
18754
+ // String id alone → containment form of Scope
18755
+ this.queryParams.parent = { id };
18676
18756
  }
18677
18757
  return this;
18678
18758
  }
@@ -19471,6 +19551,24 @@ function jsonToModelInstance(ModelClass, perspective, json, include, properties)
19471
19551
  }
19472
19552
  return instance;
19473
19553
  }
19554
+ /**
19555
+ * Put `childId` under `parent`. A containment scope `{ id }` writes through the
19556
+ * built-in `Container` (#1446): the executor runs the adder of the parent's own
19557
+ * `children` relation when its class has one (a block's `we://child`), else
19558
+ * writes `ad4m://has_child`. The other forms write their one predicate.
19559
+ */
19560
+ async function linkToParent(perspective, parent, childCtor, childId, batchId) {
19561
+ if (isContainedScope(parent)) {
19562
+ await perspective.updateSubject("ad4m://Container", parent.id, { children: { action: "adder", value: [childId] } }, batchId);
19563
+ return;
19564
+ }
19565
+ const link = new Link({
19566
+ source: parent.id,
19567
+ predicate: resolveParentPredicate(parent, childCtor),
19568
+ target: childId,
19569
+ });
19570
+ await perspective.add(link, 'shared', batchId);
19571
+ }
19474
19572
  /**
19475
19573
  * Base class for defining data models in AD4M.
19476
19574
  *
@@ -20128,7 +20226,28 @@ class Ad4mModel {
20128
20226
  query = { ...query, include: { ...expanded, ...query.include } };
20129
20227
  }
20130
20228
  const queryInput = {};
20131
- if (query.parent) {
20229
+ if (query.parent && isContainedScope(query.parent)) {
20230
+ // Containment: the executor resolves the predicates from the installed
20231
+ // classes, so only the id travels.
20232
+ queryInput.parent = { id: query.parent.id };
20233
+ }
20234
+ else if (query.parent && isContainmentTraversal(query.parent)) {
20235
+ // A traversal over containment: no predicate travels either.
20236
+ const t = query.parent;
20237
+ const traverse = { ids: t.ids };
20238
+ if (t.transitive !== undefined)
20239
+ traverse.transitive = t.transitive;
20240
+ if (t.direction !== undefined)
20241
+ traverse.direction = t.direction;
20242
+ if (t.limitPerAnchor !== undefined)
20243
+ traverse.limitPerAnchor = t.limitPerAnchor;
20244
+ if (t.levels !== undefined)
20245
+ traverse.levels = t.levels;
20246
+ if (t.maxDepth !== undefined)
20247
+ traverse.maxDepth = t.maxDepth;
20248
+ queryInput.parent = traverse;
20249
+ }
20250
+ else if (query.parent) {
20132
20251
  const parentPredicate = resolveParentPredicate(query.parent, this);
20133
20252
  // A traversal keeps its own shape on the wire: the executor reads `ids`,
20134
20253
  // and flattening it to one `id` here is how a request for a whole level
@@ -20152,6 +20271,8 @@ class Ad4mModel {
20152
20271
  traverse.limitPerAnchor = t.limitPerAnchor;
20153
20272
  if (t.levels !== undefined)
20154
20273
  traverse.levels = t.levels;
20274
+ if (t.maxDepth !== undefined)
20275
+ traverse.maxDepth = t.maxDepth;
20155
20276
  queryInput.parent = traverse;
20156
20277
  }
20157
20278
  else {
@@ -21116,14 +21237,7 @@ class Ad4mModel {
21116
21237
  if (options?.parent && !options?.batchId) {
21117
21238
  const batchId = await perspective.createBatch();
21118
21239
  await instance.save(batchId);
21119
- const parent = requireSingleParent(options.parent);
21120
- const predicate = resolveParentPredicate(parent, this);
21121
- const link = new Link({
21122
- source: parent.id,
21123
- predicate,
21124
- target: instance.id,
21125
- });
21126
- await perspective.add(link, 'shared', batchId);
21240
+ await linkToParent(perspective, requireSingleParent(options.parent), this, instance.id, batchId);
21127
21241
  await perspective.commitBatch(batchId);
21128
21242
  // Hydrate the instance now that the batch has been committed (mirrors the
21129
21243
  // behaviour of save() when it manages its own batch).
@@ -21133,14 +21247,7 @@ class Ad4mModel {
21133
21247
  await instance.save(options?.batchId);
21134
21248
  // Create parent → child link if a parent scope was provided
21135
21249
  if (options?.parent) {
21136
- const parent = requireSingleParent(options.parent);
21137
- const predicate = resolveParentPredicate(parent, this);
21138
- const link = new Link({
21139
- source: parent.id,
21140
- predicate,
21141
- target: instance.id,
21142
- });
21143
- await perspective.add(link, 'shared', options?.batchId);
21250
+ await linkToParent(perspective, requireSingleParent(options.parent), this, instance.id, options?.batchId);
21144
21251
  }
21145
21252
  return instance;
21146
21253
  }
@@ -21547,6 +21654,15 @@ class Ad4mClient {
21547
21654
  on(type, handler, filter) {
21548
21655
  return __classPrivateFieldGet$1(this, _Ad4mClient_apiClient, "f").on(type, handler, filter);
21549
21656
  }
21657
+ /**
21658
+ * Call `callback` once when the executor refuses this client's token
21659
+ * (expired, revoked, or no session). Every call then fails with a 401
21660
+ * `RpcError` and the client stops reconnecting: log in again and build a
21661
+ * new client. Returns a function that removes the callback.
21662
+ */
21663
+ onAuthFailed(callback) {
21664
+ return __classPrivateFieldGet$1(this, _Ad4mClient_apiClient, "f").onAuthFailed(callback);
21665
+ }
21550
21666
  /** Close all event connections and clear in-memory caches */
21551
21667
  close() {
21552
21668
  __classPrivateFieldGet$1(this, _Ad4mClient_agentClient, "f").clearByDidCache();
@@ -21698,13 +21814,13 @@ class LanguageLanguageInput {
21698
21814
  * const runs = await InterpretationRun.findAll(perspective);
21699
21815
  * const configs = await AutoProcessorConfig.findAll(perspective);
21700
21816
  */
21701
- var __decorate$2 = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
21817
+ var __decorate$3 = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
21702
21818
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
21703
21819
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
21704
21820
  else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
21705
21821
  return c > 3 && r && Object.defineProperty(target, key, r), r;
21706
21822
  };
21707
- var __metadata$2 = (undefined && undefined.__metadata) || function (k, v) {
21823
+ var __metadata$3 = (undefined && undefined.__metadata) || function (k, v) {
21708
21824
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
21709
21825
  };
21710
21826
  // ── AutoProcessorConfig ─────────────────────────────────────────────────────
@@ -21745,71 +21861,71 @@ let AutoProcessorConfig = class AutoProcessorConfig extends Ad4mModel {
21745
21861
  // `batchMax` + `claimTtlMs` — the Rust SDNA takes the same shape.
21746
21862
  }
21747
21863
  };
21748
- __decorate$2([
21864
+ __decorate$3([
21749
21865
  Property({ through: "ad4m://processor_id", required: true, identity: true }),
21750
- __metadata$2("design:type", String)
21866
+ __metadata$3("design:type", String)
21751
21867
  ], AutoProcessorConfig.prototype, "processorId", void 0);
21752
- __decorate$2([
21868
+ __decorate$3([
21753
21869
  Property({ through: "ad4m://source_scope_query", required: true }),
21754
- __metadata$2("design:type", String)
21870
+ __metadata$3("design:type", String)
21755
21871
  ], AutoProcessorConfig.prototype, "sourceScopeQuery", void 0);
21756
- __decorate$2([
21872
+ __decorate$3([
21757
21873
  Optional({ through: "ad4m://base_prefix" }),
21758
- __metadata$2("design:type", String)
21874
+ __metadata$3("design:type", String)
21759
21875
  ], AutoProcessorConfig.prototype, "basePrefix", void 0);
21760
- __decorate$2([
21876
+ __decorate$3([
21761
21877
  HasMany({ through: "ad4m://interpretation_class", datatype: "xsd:string" }),
21762
- __metadata$2("design:type", Array)
21878
+ __metadata$3("design:type", Array)
21763
21879
  ], AutoProcessorConfig.prototype, "interpretationClasses", void 0);
21764
- __decorate$2([
21880
+ __decorate$3([
21765
21881
  HasMany({ through: "ad4m://flow", datatype: "xsd:string" }),
21766
- __metadata$2("design:type", Array)
21882
+ __metadata$3("design:type", Array)
21767
21883
  ], AutoProcessorConfig.prototype, "flows", void 0);
21768
- __decorate$2([
21884
+ __decorate$3([
21769
21885
  Property({ through: "ad4m://debounce_ms", required: true }),
21770
- __metadata$2("design:type", String)
21886
+ __metadata$3("design:type", String)
21771
21887
  ], AutoProcessorConfig.prototype, "debounceMs", void 0);
21772
- __decorate$2([
21888
+ __decorate$3([
21773
21889
  Optional({ through: "ad4m://batch_min" }),
21774
- __metadata$2("design:type", String)
21890
+ __metadata$3("design:type", String)
21775
21891
  ], AutoProcessorConfig.prototype, "batchMin", void 0);
21776
- __decorate$2([
21892
+ __decorate$3([
21777
21893
  Property({ through: "ad4m://batch_max", required: true }),
21778
- __metadata$2("design:type", String)
21894
+ __metadata$3("design:type", String)
21779
21895
  ], AutoProcessorConfig.prototype, "batchMax", void 0);
21780
- __decorate$2([
21896
+ __decorate$3([
21781
21897
  Optional({ through: "ad4m://max_wait_ms" }),
21782
- __metadata$2("design:type", String)
21898
+ __metadata$3("design:type", String)
21783
21899
  ], AutoProcessorConfig.prototype, "maxWaitMs", void 0);
21784
- __decorate$2([
21900
+ __decorate$3([
21785
21901
  Property({ through: "ad4m://claim_ttl_ms", required: true }),
21786
- __metadata$2("design:type", String)
21902
+ __metadata$3("design:type", String)
21787
21903
  ], AutoProcessorConfig.prototype, "claimTtlMs", void 0);
21788
- __decorate$2([
21904
+ __decorate$3([
21789
21905
  Optional({ through: "ad4m://source_window_ms" }),
21790
- __metadata$2("design:type", String)
21906
+ __metadata$3("design:type", String)
21791
21907
  ], AutoProcessorConfig.prototype, "sourceWindowMs", void 0);
21792
- __decorate$2([
21908
+ __decorate$3([
21793
21909
  Optional({ through: "ad4m://dedup_strategy" }),
21794
- __metadata$2("design:type", String)
21910
+ __metadata$3("design:type", String)
21795
21911
  ], AutoProcessorConfig.prototype, "dedupStrategy", void 0);
21796
- __decorate$2([
21912
+ __decorate$3([
21797
21913
  Optional({ through: "ad4m://existing_scope" }),
21798
- __metadata$2("design:type", String)
21914
+ __metadata$3("design:type", String)
21799
21915
  ], AutoProcessorConfig.prototype, "existingScope", void 0);
21800
- __decorate$2([
21916
+ __decorate$3([
21801
21917
  Optional({ through: "ad4m://mint_scope" }),
21802
- __metadata$2("design:type", String)
21918
+ __metadata$3("design:type", String)
21803
21919
  ], AutoProcessorConfig.prototype, "mintScope", void 0);
21804
- __decorate$2([
21920
+ __decorate$3([
21805
21921
  Optional({ through: "ad4m://max_tool_calls" }),
21806
- __metadata$2("design:type", String)
21922
+ __metadata$3("design:type", String)
21807
21923
  ], AutoProcessorConfig.prototype, "maxToolCalls", void 0);
21808
- __decorate$2([
21924
+ __decorate$3([
21809
21925
  Optional({ through: "ad4m://emit_debug_events", resolveLanguage: "literal" }),
21810
- __metadata$2("design:type", String)
21926
+ __metadata$3("design:type", String)
21811
21927
  ], AutoProcessorConfig.prototype, "emitDebugEvents", void 0);
21812
- AutoProcessorConfig = __decorate$2([
21928
+ AutoProcessorConfig = __decorate$3([
21813
21929
  Model$1({ name: "AutoProcessor" })
21814
21930
  ], AutoProcessorConfig);
21815
21931
  // ── InterpretationRun ───────────────────────────────────────────────────────
@@ -21833,39 +21949,39 @@ let InterpretationRun = class InterpretationRun extends Ad4mModel {
21833
21949
  this.sources = [];
21834
21950
  }
21835
21951
  };
21836
- __decorate$2([
21952
+ __decorate$3([
21837
21953
  Property({ through: "ad4m://interp/run_id", required: true, identity: true }),
21838
- __metadata$2("design:type", String)
21954
+ __metadata$3("design:type", String)
21839
21955
  ], InterpretationRun.prototype, "runId", void 0);
21840
- __decorate$2([
21956
+ __decorate$3([
21841
21957
  Optional({ through: "ad4m://interp/model" }),
21842
- __metadata$2("design:type", String)
21958
+ __metadata$3("design:type", String)
21843
21959
  ], InterpretationRun.prototype, "model", void 0);
21844
- __decorate$2([
21960
+ __decorate$3([
21845
21961
  Optional({ through: "ad4m://interp/prompt_version" }),
21846
- __metadata$2("design:type", String)
21962
+ __metadata$3("design:type", String)
21847
21963
  ], InterpretationRun.prototype, "promptVersion", void 0);
21848
- __decorate$2([
21964
+ __decorate$3([
21849
21965
  Optional({ through: "ad4m://interp/ran_at" }),
21850
- __metadata$2("design:type", String)
21966
+ __metadata$3("design:type", String)
21851
21967
  ], InterpretationRun.prototype, "ranAt", void 0);
21852
- __decorate$2([
21968
+ __decorate$3([
21853
21969
  Optional({ through: "ad4m://interp/processor" }),
21854
- __metadata$2("design:type", String)
21970
+ __metadata$3("design:type", String)
21855
21971
  ], InterpretationRun.prototype, "processor", void 0);
21856
- __decorate$2([
21972
+ __decorate$3([
21857
21973
  HasMany({ through: "ad4m://interp/sources", datatype: "xsd:string" }),
21858
- __metadata$2("design:type", Array)
21974
+ __metadata$3("design:type", Array)
21859
21975
  ], InterpretationRun.prototype, "sources", void 0);
21860
- __decorate$2([
21976
+ __decorate$3([
21861
21977
  Optional({ through: "ad4m://interp/debug_prompt", resolveLanguage: "literal" }),
21862
- __metadata$2("design:type", String)
21978
+ __metadata$3("design:type", String)
21863
21979
  ], InterpretationRun.prototype, "debugPrompt", void 0);
21864
- __decorate$2([
21980
+ __decorate$3([
21865
21981
  Optional({ through: "ad4m://interp/debug_response", resolveLanguage: "literal" }),
21866
- __metadata$2("design:type", String)
21982
+ __metadata$3("design:type", String)
21867
21983
  ], InterpretationRun.prototype, "debugResponse", void 0);
21868
- InterpretationRun = __decorate$2([
21984
+ InterpretationRun = __decorate$3([
21869
21985
  Model$1({ name: "InterpretationRun" })
21870
21986
  ], InterpretationRun);
21871
21987
  // ── InterpretationOverlay ───────────────────────────────────────────────────
@@ -21895,15 +22011,15 @@ let InterpretationOverlay = class InterpretationOverlay extends Ad4mModel {
21895
22011
  this.kind = "";
21896
22012
  }
21897
22013
  };
21898
- __decorate$2([
22014
+ __decorate$3([
21899
22015
  Property({ through: "ad4m://interp/kind", required: true }),
21900
- __metadata$2("design:type", String)
22016
+ __metadata$3("design:type", String)
21901
22017
  ], InterpretationOverlay.prototype, "kind", void 0);
21902
- __decorate$2([
22018
+ __decorate$3([
21903
22019
  Optional({ through: "ad4m://interp/run" }),
21904
- __metadata$2("design:type", String)
22020
+ __metadata$3("design:type", String)
21905
22021
  ], InterpretationOverlay.prototype, "run", void 0);
21906
- InterpretationOverlay = __decorate$2([
22022
+ InterpretationOverlay = __decorate$3([
21907
22023
  Model$1({ name: "InterpretationOverlay" })
21908
22024
  ], InterpretationOverlay);
21909
22025
 
@@ -21927,13 +22043,13 @@ InterpretationOverlay = __decorate$2([
21927
22043
  * - the SDNA-parity test locks TS/Rust drift against
21928
22044
  * `rust-executor/src/perspectives/hardwired_sdna/flow_transition_proposal.json`.
21929
22045
  */
21930
- var __decorate$1 = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
22046
+ var __decorate$2 = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
21931
22047
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
21932
22048
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
21933
22049
  else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
21934
22050
  return c > 3 && r && Object.defineProperty(target, key, r), r;
21935
22051
  };
21936
- var __metadata$1 = (undefined && undefined.__metadata) || function (k, v) {
22052
+ var __metadata$2 = (undefined && undefined.__metadata) || function (k, v) {
21937
22053
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
21938
22054
  };
21939
22055
  /**
@@ -22040,55 +22156,55 @@ let FlowTransitionProposal = class FlowTransitionProposal extends Ad4mModel {
22040
22156
  // of the proposal's own links (all written together during create_subject).
22041
22157
  }
22042
22158
  };
22043
- __decorate$1([
22159
+ __decorate$2([
22044
22160
  Property({ through: "ad4m://flow/instance", required: true, identity: true }),
22045
- __metadata$1("design:type", String)
22161
+ __metadata$2("design:type", String)
22046
22162
  ], FlowTransitionProposal.prototype, "flowInstance", void 0);
22047
- __decorate$1([
22163
+ __decorate$2([
22048
22164
  Property({ through: "ad4m://flow/from_state", required: true }),
22049
- __metadata$1("design:type", String)
22165
+ __metadata$2("design:type", String)
22050
22166
  ], FlowTransitionProposal.prototype, "fromState", void 0);
22051
- __decorate$1([
22167
+ __decorate$2([
22052
22168
  Property({ through: "ad4m://flow/to_state", required: true }),
22053
- __metadata$1("design:type", String)
22169
+ __metadata$2("design:type", String)
22054
22170
  ], FlowTransitionProposal.prototype, "toState", void 0);
22055
- __decorate$1([
22171
+ __decorate$2([
22056
22172
  Property({ through: "ad4m://flow/proposer", required: true, getter: PROPOSER_GETTER, datatype: "xsd:string" }),
22057
- __metadata$1("design:type", String)
22173
+ __metadata$2("design:type", String)
22058
22174
  ], FlowTransitionProposal.prototype, "proposer", void 0);
22059
- __decorate$1([
22175
+ __decorate$2([
22060
22176
  HasMany({ through: "ad4m://flow/evidence", datatype: "xsd:string" }),
22061
- __metadata$1("design:type", Array)
22177
+ __metadata$2("design:type", Array)
22062
22178
  ], FlowTransitionProposal.prototype, "evidence", void 0);
22063
- __decorate$1([
22179
+ __decorate$2([
22064
22180
  Property({ through: "ad4m://flow/evidence_hashes", required: true }),
22065
- __metadata$1("design:type", String)
22181
+ __metadata$2("design:type", String)
22066
22182
  ], FlowTransitionProposal.prototype, "evidenceHashes", void 0);
22067
- __decorate$1([
22183
+ __decorate$2([
22068
22184
  HasMany({ through: "ad4m://flow/output", datatype: "xsd:string" }),
22069
- __metadata$1("design:type", Array)
22185
+ __metadata$2("design:type", Array)
22070
22186
  ], FlowTransitionProposal.prototype, "outputs", void 0);
22071
- __decorate$1([
22187
+ __decorate$2([
22072
22188
  Property({ through: "ad4m://flow/outputs_hash" }),
22073
- __metadata$1("design:type", String)
22189
+ __metadata$2("design:type", String)
22074
22190
  ], FlowTransitionProposal.prototype, "outputsHash", void 0);
22075
- __decorate$1([
22191
+ __decorate$2([
22076
22192
  Property({ through: "ad4m://flow/nonce" }),
22077
- __metadata$1("design:type", String)
22193
+ __metadata$2("design:type", String)
22078
22194
  ], FlowTransitionProposal.prototype, "nonce", void 0);
22079
- __decorate$1([
22195
+ __decorate$2([
22080
22196
  Optional({ through: "ad4m://flow/run_uri" }),
22081
- __metadata$1("design:type", String)
22197
+ __metadata$2("design:type", String)
22082
22198
  ], FlowTransitionProposal.prototype, "runUri", void 0);
22083
- __decorate$1([
22199
+ __decorate$2([
22084
22200
  Optional({ through: "ad4m://flow/rationale" }),
22085
- __metadata$1("design:type", String)
22201
+ __metadata$2("design:type", String)
22086
22202
  ], FlowTransitionProposal.prototype, "rationale", void 0);
22087
- __decorate$1([
22203
+ __decorate$2([
22088
22204
  HasMany({ through: "ad4m://acceptedBy", getter: ACCEPTED_BY_GETTER, readOnly: true }),
22089
- __metadata$1("design:type", Array)
22205
+ __metadata$2("design:type", Array)
22090
22206
  ], FlowTransitionProposal.prototype, "acceptedBy", void 0);
22091
- FlowTransitionProposal = __decorate$1([
22207
+ FlowTransitionProposal = __decorate$2([
22092
22208
  Model$1({ name: "FlowTransitionProposal" })
22093
22209
  ], FlowTransitionProposal);
22094
22210
  // ── FlowInstanceRecord ──────────────────────────────────────────────────────
@@ -22148,25 +22264,25 @@ let FlowInstanceRecord = class FlowInstanceRecord extends Ad4mModel {
22148
22264
  // of the instance's own links (all written together during `mint_flow_instance`).
22149
22265
  }
22150
22266
  };
22151
- __decorate$1([
22267
+ __decorate$2([
22152
22268
  Property({ through: "ad4m://flow/flow_uri", required: true, identity: true }),
22153
- __metadata$1("design:type", String)
22269
+ __metadata$2("design:type", String)
22154
22270
  ], FlowInstanceRecord.prototype, "flowUri", void 0);
22155
- __decorate$1([
22271
+ __decorate$2([
22156
22272
  Property({ through: "ad4m://flow/base", required: true }),
22157
- __metadata$1("design:type", String)
22273
+ __metadata$2("design:type", String)
22158
22274
  ], FlowInstanceRecord.prototype, "subject", void 0);
22159
- FlowInstanceRecord = __decorate$1([
22275
+ FlowInstanceRecord = __decorate$2([
22160
22276
  Model$1({ name: "FlowInstance" })
22161
22277
  ], FlowInstanceRecord);
22162
22278
 
22163
- var __decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
22279
+ var __decorate$1 = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
22164
22280
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
22165
22281
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
22166
22282
  else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
22167
22283
  return c > 3 && r && Object.defineProperty(target, key, r), r;
22168
22284
  };
22169
- var __metadata = (undefined && undefined.__metadata) || function (k, v) {
22285
+ var __metadata$1 = (undefined && undefined.__metadata) || function (k, v) {
22170
22286
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
22171
22287
  };
22172
22288
  /**
@@ -22202,14 +22318,74 @@ let TextContent = class TextContent extends Ad4mModel {
22202
22318
  };
22203
22319
  /** The URI the executor reads it by. */
22204
22320
  TextContent.builtinUri = "ad4m://TextContent";
22205
- __decorate([
22321
+ __decorate$1([
22206
22322
  Property({ through: "ad4m://text" }),
22207
- __metadata("design:type", String)
22323
+ __metadata$1("design:type", String)
22208
22324
  ], TextContent.prototype, "text", void 0);
22209
- TextContent = __decorate([
22325
+ TextContent = __decorate$1([
22210
22326
  Model$1({ name: "TextContent", abstract: true })
22211
22327
  ], TextContent);
22212
22328
 
22329
+ var __decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
22330
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
22331
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
22332
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
22333
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
22334
+ };
22335
+ var __metadata = (undefined && undefined.__metadata) || function (k, v) {
22336
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
22337
+ };
22338
+ /**
22339
+ * The built-in abstract class `Container { children }` (#1446): what holds
22340
+ * other records — a channel, a thread, a post, a call, a document, a board.
22341
+ *
22342
+ * X is contained in P when `P ad4m://has_child X` exists, whatever P is (an
22343
+ * instance of any class, or a node no class describes, such as
22344
+ * `ad4m://self`), or when P is an instance of a class whose `children`
22345
+ * relation (by name, or aliased to `children`) links X:
22346
+ *
22347
+ * ```typescript
22348
+ * @Model({ name: "Block", implements: [Container] })
22349
+ * class Block extends Ad4mModel {
22350
+ * @HasMany({ through: "we://child", alias: { Container: "children" } })
22351
+ * blocks: string[] = [];
22352
+ * }
22353
+ *
22354
+ * // Messages held by P, through has_child or a Block's we://child:
22355
+ * await Message.findAll(perspective, { parent: { id: P } });
22356
+ * // Everything that holds X:
22357
+ * await Container.findAll(perspective, { parent: { ids: [X], direction: "in" } });
22358
+ * ```
22359
+ *
22360
+ * A row's `children` is everything it holds, merged across its classes. A
22361
+ * node no class describes is a row of its own when it holds something by
22362
+ * `has_child`. Always scope a `Container` query (`where: { id }`, a
22363
+ * `children` filter or `parent`): unscoped, it reads every holder in the
22364
+ * perspective.
22365
+ *
22366
+ * Built in: the executor declares it (mirrors
22367
+ * `rust-executor/src/perspectives/hardwired_sdna/container.json`) and reads
22368
+ * it by its URI, `ad4m://Container`, so a perspective never stores it and an
22369
+ * app class named `Container` does not replace it. `register()` on it writes
22370
+ * nothing.
22371
+ */
22372
+ let Container = class Container extends Ad4mModel {
22373
+ constructor() {
22374
+ super(...arguments);
22375
+ /** What it holds, whatever their class. */
22376
+ this.children = [];
22377
+ }
22378
+ };
22379
+ /** The URI the executor reads it by. */
22380
+ Container.builtinUri = "ad4m://Container";
22381
+ __decorate([
22382
+ HasMany({ through: "ad4m://has_child" }),
22383
+ __metadata("design:type", Array)
22384
+ ], Container.prototype, "children", void 0);
22385
+ Container = __decorate([
22386
+ Model$1({ name: "Container", abstract: true })
22387
+ ], Container);
22388
+
22213
22389
  /**
22214
22390
  * `FlowInstance` — object-oriented wrapper for a running flow.
22215
22391
  *
@@ -22798,6 +22974,107 @@ function parseLitBoolean(val) {
22798
22974
  * module (`plugins/ad4m/wakerSubscriptionManager.ts`) rather than carrying its
22799
22975
  * own copy. Any behaviour change belongs here.
22800
22976
  */
22977
+ /** A letter, combining mark, digit or underscore: what a term must not touch. */
22978
+ const WORD_CHAR = "[\\p{L}\\p{M}\\p{N}_]";
22979
+ /**
22980
+ * The elements a message's HTML is made of. A `<` before any other name is text:
22981
+ * We stores plain text, where "<hey Data> can you look" is words.
22982
+ */
22983
+ const ELEMENT = "a|abbr|b|bdi|bdo|blockquote|br|caption|center|cite|code|col|colgroup|dd|del|details|dfn|div|dl|dt|em|" +
22984
+ "figcaption|figure|font|h[1-6]|hr|i|img|ins|kbd|label|li|mark|ol|p|pre|q|s|samp|section|article|small|" +
22985
+ "span|strike|strong|sub|summary|sup|table|tbody|td|tfoot|th|thead|time|tr|u|ul|var|wbr|script|style";
22986
+ /** An attribute: a name, then optionally `=` and a quoted value (which may hold `>`) or an unquoted one. */
22987
+ const ATTRIBUTE = `\\s+[A-Za-z_:][-\\w:.]*(?:\\s*=\\s*(?:"[^"]*"|'[^']*'|[^\\s"'=<>\`]+))?`;
22988
+ /**
22989
+ * Markup: a comment, a `<script>`/`<style>` element with its contents, or a tag of
22990
+ * a known element whose rest is a valid attribute list. "a < b" and
22991
+ * "if a <b then ask Data, else c -> d" are text: the comma is no attribute.
22992
+ */
22993
+ const TAG = new RegExp(`<!--[\\s\\S]*?-->` +
22994
+ `|<(script|style)(?=[\\s/>])(?:${ATTRIBUTE})*\\s*>[\\s\\S]*?<\\/\\1\\s*>` +
22995
+ `|<(?:${ELEMENT})(?=[\\s/>])(?:${ATTRIBUTE})*\\s*\\/?>` +
22996
+ `|<\\/(?:${ELEMENT})\\s*>`, "gi");
22997
+ /** Tags that break a line: replaced by a space, so `<p>hi</p><p>Data</p>` keeps "Data" a word. */
22998
+ const BREAKING_TAG = /^<\/?(?:p|div|br|hr|li|ul|ol|h[1-6]|blockquote|pre|tr|td|th|table|section|article)\b/i;
22999
+ /**
23000
+ * The attributes a mention puts its target's DID in: Flux's `<a data-type="mention"
23001
+ * href="did:…">`, older Flux messages' `<span data-id="did:…">`, and We's editor chip
23002
+ * `<span class="we-mention" data-did="did:…">`.
23003
+ */
23004
+ const ATTRIBUTES = new RegExp(ATTRIBUTE, "g");
23005
+ const MENTION_TARGET = /^\s+(?:href|data-id|data-did)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+))$/i;
23006
+ /**
23007
+ * How much of a record's text the word check reads. Dropping markup costs time
23008
+ * quadratic in a run of unclosed `<script>`, `<style>` or `<!--` openers, so a
23009
+ * very long text could hold the event loop for seconds, and a row that holds
23010
+ * no term is checked again on every result while it is in the window. A term
23011
+ * past this many characters does not wake.
23012
+ */
23013
+ const MENTION_TEXT_LIMIT = 16384;
23014
+ const ENTITIES = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " " };
23015
+ function decodeEntities(s) {
23016
+ return s.replace(/&(#x[0-9a-f]+|#[0-9]+|[a-z]+);/gi, (whole, ref) => {
23017
+ if (ref[0] !== "#")
23018
+ return ENTITIES[ref.toLowerCase()] ?? whole;
23019
+ const code = ref[1] === "x" || ref[1] === "X" ? parseInt(ref.slice(2), 16) : parseInt(ref.slice(1), 10);
23020
+ return code > 0 && code <= 0x10ffff ? String.fromCodePoint(code) : whole;
23021
+ });
23022
+ }
23023
+ /**
23024
+ * What a reader sees of `text`, and the DIDs its mentions point at. `text` may be
23025
+ * HTML (TextContent allows it): tag names and attributes are markup, not words, so
23026
+ * a bot named "Data" must not wake on `data-type="mention"` in a mention of
23027
+ * someone else. Plain text passes through unchanged, apart from entities.
23028
+ */
23029
+ function readableParts(text) {
23030
+ const targets = [];
23031
+ const visible = text.replace(TAG, (tag, scriptOrStyle) => {
23032
+ if (scriptOrStyle)
23033
+ return " ";
23034
+ if (tag.startsWith("<!--"))
23035
+ return "";
23036
+ // Parse complete attributes first: a DID-shaped string inside `title`
23037
+ // is not a target attribute and must not wake an agent.
23038
+ for (const attribute of tag.matchAll(ATTRIBUTES)) {
23039
+ const target = MENTION_TARGET.exec(attribute[0]);
23040
+ if (target)
23041
+ targets.push(decodeEntities(target[1] ?? target[2] ?? target[3]));
23042
+ }
23043
+ return BREAKING_TAG.test(tag) ? " " : "";
23044
+ });
23045
+ return { visible: decodeEntities(visible), targets };
23046
+ }
23047
+ /**
23048
+ * Whether `text` holds one of `terms` as a whole word, case-insensitively:
23049
+ * "Data" is in "hi Data!", "@data" and "Data's turn", not in "metadata" or
23050
+ * "database". A term is matched literally (regex characters, quotes) and must
23051
+ * not touch a letter, mark, digit or underscore on either side, so a name
23052
+ * that starts or ends with punctuation still matches. Same rule as #1459's
23053
+ * SPARQL `(?:^|\W)term(?:\W|$)`.
23054
+ *
23055
+ * The rule runs on the visible text only: in HTML, tags and attributes are
23056
+ * dropped and entities decoded first. A mention's target attribute
23057
+ * (`href`, `data-id`, `data-did`) matches an exact, case-sensitive DID term, which
23058
+ * is how a mention by DID is found when the DID is not in the visible text.
23059
+ *
23060
+ * The mention query's `contains` matches substrings (model query has no word
23061
+ * match); this is the check that keeps "data" from waking on "metadata".
23062
+ * It reads the first {@link MENTION_TEXT_LIMIT} characters only.
23063
+ */
23064
+ function holdsAWholeWordTerm(text, terms) {
23065
+ const { visible, targets } = readableParts(text.slice(0, MENTION_TEXT_LIMIT));
23066
+ return terms.some((term) => {
23067
+ if (!term)
23068
+ return false;
23069
+ if (term.startsWith("did:") && targets.includes(term))
23070
+ return true;
23071
+ const escaped = term.replace(/[\\^$.*+?()[\]{}|\/]/g, "\\$&");
23072
+ return new RegExp(`(?<!${WORD_CHAR})${escaped}(?!${WORD_CHAR})`, "iu").test(visible);
23073
+ });
23074
+ }
23075
+ /** The built-in `Container` (`Container.builtinUri`; not imported, so the
23076
+ * plugin bundle does not pull in the model layer). */
23077
+ const CONTAINER = "ad4m://Container";
22801
23078
  /**
22802
23079
  * Add a short cause hint to known subscription failures.
22803
23080
  * The executor needs its main key to register a live query; on a restarted
@@ -22864,6 +23141,20 @@ class WakerSubscriptionManager {
22864
23141
  /** Per-subscription set of already-processed message addresses (for mention subs)
22865
23142
  * or serialized result hash (for channel-messages subs). */
22866
23143
  this.seenMessages = new Map();
23144
+ /**
23145
+ * Per mention subscription: the addresses whose wake was delivered, or that were history when
23146
+ * the subscription opened. This, not `seenMessages`, is what gets persisted: an address joins
23147
+ * `seenMessages` as soon as it is read, while its parents are still resolving and before any
23148
+ * wake, so a restart in between must not take it as done.
23149
+ */
23150
+ this.delivered = new Map();
23151
+ /**
23152
+ * Per mention subscription: mentions read but whose wake has not been delivered yet, keyed by
23153
+ * address. They accumulate across a debounce window, so one wake names all of them.
23154
+ */
23155
+ this.undelivered = new Map();
23156
+ /** Failed wake attempts in a row per subscription, for the retry backoff. */
23157
+ this.wakeFailures = new Map();
22867
23158
  this.perspectiveClient = options.perspectiveClient;
22868
23159
  this.logger = options.logger;
22869
23160
  this.debounceMs = options.debounceMs ?? 2000;
@@ -22874,6 +23165,7 @@ class WakerSubscriptionManager {
22874
23165
  this.previousSeenMessages = options.previousSeenMessages ?? {};
22875
23166
  this.retryPendingMs = options.retryPendingMs ?? 30000;
22876
23167
  this.subscribeTimeoutMs = options.subscribeTimeoutMs ?? 15000;
23168
+ this.retryWakeMs = options.retryWakeMs ?? 5000;
22877
23169
  }
22878
23170
  /** A token identifying this attempt at subscribing `id`. */
22879
23171
  beginAttempt(id) {
@@ -22886,7 +23178,7 @@ class WakerSubscriptionManager {
22886
23178
  return token.epoch !== this.epoch || this.generations.get(id) !== token.gen;
22887
23179
  }
22888
23180
  /**
22889
- * Create a live SPARQL subscription.
23181
+ * Create a live subscription: SPARQL, or a model query when `sub.className` is set.
22890
23182
  * If a subscription with the same id already exists, it is disposed first.
22891
23183
  */
22892
23184
  async subscribe(sub) {
@@ -22897,9 +23189,16 @@ class WakerSubscriptionManager {
22897
23189
  throw new Error("WakerSubscriptionManager: QuerySubscriptionProxy must be provided via constructor options");
22898
23190
  }
22899
23191
  const QuerySubscriptionProxy = this.QuerySubscriptionProxyCtor;
23192
+ if (sub.type === "mention" && sub.className && !sub.terms?.length) {
23193
+ // Without terms the whole-word check cannot run, and every substring
23194
+ // ("metadata" for "data") would wake the agent.
23195
+ throw new Error(`Waker subscription ${sub.id}: a mention subscription needs its terms (get_mention_waker_config returns them)`);
23196
+ }
22900
23197
  this.logger.info(`[waker] ${sub.id}: creating subscription (perspective=${sub.perspective}, type=${sub.type})`);
22901
- this.logger.info(`[waker] ${sub.id}: SPARQL query:\n${sub.query}`);
22902
- const proxy = new QuerySubscriptionProxy(sub.perspective, sub.query, this.perspectiveClient);
23198
+ this.logger.info(`[waker] ${sub.id}: ${sub.className ? `model query over ${sub.className}` : "SPARQL query"}:\n${sub.query}`);
23199
+ const proxy = sub.className
23200
+ ? new QuerySubscriptionProxy(sub.perspective, sub.query, this.perspectiveClient, sub.className)
23201
+ : new QuerySubscriptionProxy(sub.perspective, sub.query, this.perspectiveClient);
22903
23202
  // Suppress unhandled rejection from proxy.initialized — QuerySubscriptionProxy
22904
23203
  // rejects this promise internally when subscribe() fails, and if nobody catches
22905
23204
  // it before the next microtask it crashes the process.
@@ -22940,6 +23239,7 @@ class WakerSubscriptionManager {
22940
23239
  // reported as active or persisted as if it were.
22941
23240
  this.activeSubscriptions.delete(sub.id);
22942
23241
  this.seenMessages.delete(sub.id);
23242
+ this.delivered.delete(sub.id);
22943
23243
  this.persist();
22944
23244
  // Keep it pending and re-attempt: the usual cause (locked wallet, executor
22945
23245
  // mid-restart, a handshake the executor never answered) clears on its
@@ -22964,33 +23264,62 @@ class WakerSubscriptionManager {
22964
23264
  this.pendingSubscriptions.delete(sub.id);
22965
23265
  this.logger.info(`[waker] ${sub.id}: subscription initialized successfully`);
22966
23266
  // Seed from persisted seen messages so we don't re-wake after restart
23267
+ const restored = Object.prototype.hasOwnProperty.call(this.previousSeenMessages, sub.id);
22967
23268
  const seen = new Set(this.previousSeenMessages[sub.id] ?? []);
22968
23269
  this.seenMessages.set(sub.id, seen);
23270
+ this.delivered.set(sub.id, new Set(seen));
22969
23271
  if (seen.size > 0) {
22970
23272
  this.logger.info(`[waker] ${sub.id}: seeded ${seen.size} seen message(s) from persisted state`);
22971
23273
  }
22972
- proxy.onResult(async (result) => {
22973
- this.logger.info(`[waker] ${sub.id}: onResult fired — type=${typeof result}, isArray=${Array.isArray(result)}, value=${String(JSON.stringify(result)).substring(0, 500)}`);
22974
- // Query engine can deliver non-array values (e.g. false) on disconnect/reconnect — ignore them
22975
- if (!Array.isArray(result)) {
22976
- this.logger.warn(`[waker] ${sub.id}: ignoring non-array result: ${JSON.stringify(result)}`);
23274
+ // `opening` is the result the subscription holds when it opens (`proxy.result`): `onResult`
23275
+ // only reports later changes, so this is the one chance to see what was written meanwhile.
23276
+ const handleResult = async (result, opening = false) => {
23277
+ this.logger.info(`[waker] ${sub.id}: ${opening ? "opening result" : "onResult fired"} — type=${typeof result}, isArray=${Array.isArray(result)}, value=${String(JSON.stringify(result)).substring(0, 500)}`);
23278
+ // A model subscription delivers `{ instances }`, SPARQL an array of
23279
+ // rows. Anything else (e.g. `false` on a disconnect/reconnect) is
23280
+ // ignored.
23281
+ const rows = sub.className ? result?.instances : result;
23282
+ if (!Array.isArray(rows)) {
23283
+ this.logger.warn(`[waker] ${sub.id}: ignoring result without ${sub.className ? "instances" : "rows"}: ${JSON.stringify(result)}`);
22977
23284
  return;
22978
23285
  }
22979
23286
  if (sub.type === "mention") {
22980
- // For mention subscriptions: track seen message addresses.
22981
- // Only wake for messages we haven't seen before.
23287
+ // For mention subscriptions: track seen record ids.
23288
+ // Only wake for records we haven't seen before.
22982
23289
  const currentSeen = this.seenMessages.get(sub.id) ?? new Set();
22983
23290
  const newMessages = [];
22984
- for (const item of result) {
22985
- if (item && item.source && !currentSeen.has(item.source)) {
22986
- newMessages.push(item.source);
23291
+ const terms = sub.terms ?? [];
23292
+ for (const item of rows) {
23293
+ // A SPARQL row names the record as `source`, a model row as `id`.
23294
+ const address = sub.className ? item?.id : item?.source;
23295
+ if (typeof address !== "string" || !address || currentSeen.has(address))
23296
+ continue;
23297
+ if (terms.length) {
23298
+ // The mention query matched a substring; wake only on a whole word.
23299
+ const text = Array.isArray(item.text) ? item.text.join(" ") : item.text;
23300
+ if (typeof text !== "string" || !holdsAWholeWordTerm(text, terms)) {
23301
+ this.logger.debug(`[waker] ${sub.id}: ${address} holds no term as a whole word, skipping`);
23302
+ continue;
23303
+ }
22987
23304
  }
23305
+ currentSeen.add(address);
23306
+ newMessages.push(address);
22988
23307
  }
22989
23308
  if (newMessages.length === 0) {
22990
- this.logger.info(`[waker] ${sub.id}: all ${result.length} items already seen, skipping`);
23309
+ this.logger.info(`[waker] ${sub.id}: no new mention among ${rows.length} items, skipping`);
23310
+ return;
23311
+ }
23312
+ if (opening && !restored) {
23313
+ // A new subscription: what it opens on is history, readable on demand, not news.
23314
+ this.seenMessages.set(sub.id, currentSeen);
23315
+ const done = this.delivered.get(sub.id) ?? new Set();
23316
+ for (const address of newMessages)
23317
+ done.add(address);
23318
+ this.delivered.set(sub.id, done);
23319
+ this.logger.info(`[waker] ${sub.id}: ${newMessages.length} existing mention(s) taken as history, not woken`);
22991
23320
  return;
22992
23321
  }
22993
- this.logger.info(`[waker] ${sub.id}: ${newMessages.length} new message(s) out of ${result.length} total`);
23322
+ this.logger.info(`[waker] ${sub.id}: ${newMessages.length} new message(s) out of ${rows.length} total`);
22994
23323
  // Resolve parents, and the chain above them, per new message
22995
23324
  const mentions = [];
22996
23325
  for (const msgAddr of newMessages) {
@@ -23001,25 +23330,20 @@ class WakerSubscriptionManager {
23001
23330
  (ancestors.length ? `; ancestors: ${ancestors.join(", ")}` : ""));
23002
23331
  mentions.push({ address: msgAddr, parents, ancestors });
23003
23332
  }
23004
- // Mark all new messages as seen
23005
- for (const addr of newMessages) {
23006
- currentSeen.add(addr);
23007
- }
23008
23333
  this.seenMessages.set(sub.id, currentSeen);
23009
- // Debounce the wake callback
23010
- const existing = this.debounceTimers.get(sub.id);
23011
- if (existing)
23012
- clearTimeout(existing);
23013
- this.debounceTimers.set(sub.id, setTimeout(() => {
23014
- this.onWake(sub, result, mentions);
23015
- this.debounceTimers.delete(sub.id);
23016
- this.persist();
23017
- }, this.debounceMs));
23334
+ const pending = this.undelivered.get(sub.id) ?? new Map();
23335
+ for (const mention of mentions)
23336
+ pending.set(mention.address, mention);
23337
+ this.undelivered.set(sub.id, pending);
23338
+ this.scheduleMentionWake(sub, result, this.debounceMs);
23018
23339
  }
23019
23340
  else {
23341
+ // A container's contents when the subscription opens are not an update.
23342
+ if (opening)
23343
+ return;
23020
23344
  // For channel-messages: always notify the agent on every subscription push.
23021
23345
  // No deduplication — the agent reads recent messages itself.
23022
- this.logger.info(`[waker] ${sub.id}: channel update (${result.length} items)`);
23346
+ this.logger.info(`[waker] ${sub.id}: channel update (${rows.length} items)`);
23023
23347
  const existing = this.debounceTimers.get(sub.id);
23024
23348
  if (existing)
23025
23349
  clearTimeout(existing);
@@ -23028,7 +23352,8 @@ class WakerSubscriptionManager {
23028
23352
  this.debounceTimers.delete(sub.id);
23029
23353
  }, this.debounceMs));
23030
23354
  }
23031
- });
23355
+ };
23356
+ proxy.onResult((result) => handleResult(result));
23032
23357
  if (this.isStale(sub.id, token)) {
23033
23358
  try {
23034
23359
  proxy.dispose();
@@ -23038,6 +23363,16 @@ class WakerSubscriptionManager {
23038
23363
  }
23039
23364
  this.proxies.set(sub.id, proxy);
23040
23365
  this.activeSubscriptions.set(sub.id, sub);
23366
+ // After a restart this wakes on mentions written while the waker was down; on a new
23367
+ // subscription it records the existing ones as history.
23368
+ if (proxy.result !== undefined) {
23369
+ try {
23370
+ await handleResult(proxy.result, true);
23371
+ }
23372
+ catch (e) {
23373
+ this.logger.warn(`[waker] ${sub.id}: reading the opening result failed: ${e?.message ?? e}`);
23374
+ }
23375
+ }
23041
23376
  this.persist();
23042
23377
  this.logger.info(`[waker] Subscription ${sub.id} active (type=${sub.type}, perspective=${sub.perspective})`);
23043
23378
  }
@@ -23113,9 +23448,61 @@ class WakerSubscriptionManager {
23113
23448
  this.activeSubscriptions.delete(id);
23114
23449
  this.pendingSubscriptions.delete(id);
23115
23450
  this.seenMessages.delete(id);
23451
+ this.delivered.delete(id);
23452
+ this.undelivered.delete(id);
23453
+ this.wakeFailures.delete(id);
23116
23454
  if (persist)
23117
23455
  this.persist();
23118
23456
  }
23457
+ /** (Re)start the timer that offers `sub`'s undelivered mentions to `onWake` after `delayMs`. */
23458
+ scheduleMentionWake(sub, result, delayMs) {
23459
+ const existing = this.debounceTimers.get(sub.id);
23460
+ if (existing)
23461
+ clearTimeout(existing);
23462
+ this.debounceTimers.set(sub.id, setTimeout(() => {
23463
+ this.debounceTimers.delete(sub.id);
23464
+ void this.deliverMentions(sub, result);
23465
+ }, delayMs));
23466
+ }
23467
+ /**
23468
+ * Offer every undelivered mention of `sub` in one wake. On delivery they join the persisted
23469
+ * seen set; on failure they stay undelivered and are offered again with backoff.
23470
+ */
23471
+ async deliverMentions(sub, result) {
23472
+ const pending = this.undelivered.get(sub.id);
23473
+ if (!pending?.size || !this.activeSubscriptions.has(sub.id))
23474
+ return;
23475
+ const mentions = Array.from(pending.values());
23476
+ let delivered;
23477
+ try {
23478
+ delivered = (await this.onWake(sub, result, mentions)) !== false;
23479
+ }
23480
+ catch (e) {
23481
+ this.logger.warn(`[waker] ${sub.id}: wake callback threw: ${e?.message ?? e}`);
23482
+ delivered = false;
23483
+ }
23484
+ // Disposed while the wake was in flight: nothing left to retry or persist.
23485
+ if (this.undelivered.get(sub.id) !== pending)
23486
+ return;
23487
+ if (!delivered) {
23488
+ const failures = (this.wakeFailures.get(sub.id) ?? 0) + 1;
23489
+ this.wakeFailures.set(sub.id, failures);
23490
+ const delay = Math.min(this.retryWakeMs * 2 ** (failures - 1), 60000);
23491
+ this.logger.warn(`[waker] ${sub.id}: wake for ${mentions.length} mention(s) not delivered, offering again in ${delay}ms`);
23492
+ // A newer result arriving meanwhile restarts the timer and joins this wake.
23493
+ if (!this.debounceTimers.has(sub.id))
23494
+ this.scheduleMentionWake(sub, result, delay);
23495
+ return;
23496
+ }
23497
+ this.wakeFailures.delete(sub.id);
23498
+ const done = this.delivered.get(sub.id) ?? new Set();
23499
+ for (const mention of mentions) {
23500
+ pending.delete(mention.address);
23501
+ done.add(mention.address);
23502
+ }
23503
+ this.delivered.set(sub.id, done);
23504
+ this.persist();
23505
+ }
23119
23506
  /** Dispose all active subscriptions and drop anything still pending. */
23120
23507
  disposeAll() {
23121
23508
  // Bump the epoch first: in-flight subscribe() calls have no proxy in the
@@ -23138,60 +23525,50 @@ class WakerSubscriptionManager {
23138
23525
  has(id) {
23139
23526
  return this.activeSubscriptions.has(id);
23140
23527
  }
23141
- /** Resolve one containment level in one query; skip unsafe IRI tokens and treat failures as none. */
23528
+ /**
23529
+ * Everything holding any of `addresses`, in one model query: a `Container`
23530
+ * step in (#1446). The executor follows `ad4m://has_child` on any node and
23531
+ * each class's own `children` relation on its instances, so the waker
23532
+ * looks up no predicate. Failures count as none.
23533
+ */
23142
23534
  async parentsOf(sub, addresses) {
23143
- const safe = [...new Set(addresses)].filter((address) => {
23144
- if (/[<>"{}|^`\\\s\x00-\x20]/.test(address)) {
23145
- this.logger.warn(`[waker] ${sub.id}: skipping parent lookup for unsafe address ${JSON.stringify(address)}`);
23146
- return false;
23147
- }
23148
- return true;
23149
- });
23150
- if (!safe.length)
23535
+ if (!addresses.length)
23151
23536
  return [];
23152
- try {
23153
- const query = safe.length === 1
23154
- ? `SELECT ?source WHERE { ?source <ad4m://has_child> <${safe[0]}> . }`
23155
- : `SELECT ?source WHERE { VALUES ?child { ${safe.map((address) => `<${address}>`).join(" ")} } ?source <ad4m://has_child> ?child . }`;
23156
- const rows = await this.perspectiveClient.querySparql(sub.perspective, query);
23157
- if (!Array.isArray(rows))
23158
- return [];
23159
- // A row omits a variable left unbound in its solution.
23160
- return rows.map((row) => row?.source).filter((source) => typeof source === "string");
23161
- }
23162
- catch (err) {
23163
- this.logger.warn(`[waker] ${sub.id}: parent resolution failed for ${JSON.stringify(safe)} — ${err?.message ?? err}`);
23164
- return [];
23165
- }
23537
+ return this.containers(sub, { ids: [...new Set(addresses)], direction: "in" }, addresses);
23166
23538
  }
23167
23539
  /**
23168
- * The chain above an item's parents, a level at a time, nearest first, up to `ancestorDepth`.
23169
- *
23170
- * Breadth-first with a visited set: containment is a graph, not a tree — an item can sit in two
23171
- * places, and nothing stops a cycle — so each address is reported once and the walk always ends.
23172
- * Each level uses one batched parent lookup, bounded by the depth.
23540
+ * The chain above an item's parents, nearest first, up to `ancestorDepth` levels: one
23541
+ * transitive `Container` walk in from the parents, bounded by `maxDepth`. The executor walks
23542
+ * containment as a graph, so each address comes once however many paths reach it, and a
23543
+ * cycle ends. The item and its parents are never reported as ancestors.
23173
23544
  */
23174
23545
  async ancestorsOf(sub, address, parents) {
23546
+ if (!parents.length || this.ancestorDepth <= 0)
23547
+ return [];
23548
+ const scope = { ids: parents, direction: "in", transitive: true, maxDepth: this.ancestorDepth };
23175
23549
  const seen = new Set([address, ...parents]);
23176
- const ancestors = [];
23177
- let level = parents;
23178
- for (let depth = 0; depth < this.ancestorDepth && level.length; depth++) {
23179
- const next = [];
23180
- for (const parent of await this.parentsOf(sub, level)) {
23181
- if (seen.has(parent))
23182
- continue;
23183
- seen.add(parent);
23184
- next.push(parent);
23185
- }
23186
- ancestors.push(...next);
23187
- level = next;
23550
+ return (await this.containers(sub, scope, parents)).filter((id) => !seen.has(id));
23551
+ }
23552
+ /** The ids of the `Container` rows `parent` scopes to, in the executor's order. */
23553
+ async containers(sub, parent, from) {
23554
+ try {
23555
+ const query = JSON.stringify({ parent, properties: [] });
23556
+ const result = await this.perspectiveClient.modelQuery(sub.perspective, CONTAINER, query);
23557
+ const instances = result?.instances;
23558
+ if (!Array.isArray(instances))
23559
+ return [];
23560
+ return instances.map((row) => row?.id).filter((id) => typeof id === "string");
23561
+ }
23562
+ catch (err) {
23563
+ this.logger.warn(`[waker] ${sub.id}: containment lookup failed for ${JSON.stringify(from)} — ${err?.message ?? err}`);
23564
+ return [];
23188
23565
  }
23189
- return ancestors;
23190
23566
  }
23191
23567
  persist() {
23192
23568
  if (this.onPersist) {
23193
23569
  const seen = {};
23194
- for (const [id, set] of this.seenMessages) {
23570
+ // Only what was delivered: anything else must wake again after a restart.
23571
+ for (const [id, set] of this.delivered) {
23195
23572
  seen[id] = Array.from(set);
23196
23573
  }
23197
23574
  this.onPersist(this.getActive(), seen);
@@ -23639,4 +24016,4 @@ const SCOPED_EVENTS = new Set([
23639
24016
  "flow-state-changed",
23640
24017
  ]);
23641
24018
 
23642
- export { ACCEPTED_BY_GETTER, AIClient, Model as AIModel, AIModelLoadingStatus, AIPromptExamples, AIPromptExamplesInput, AITask, AITaskInput, Ad4mClient, Ad4mModel, Agent, AgentClient, AgentExpression, AgentSignature, AgentStatus, Apps, AuthInfo, AuthInfoInput, AutoProcessorConfig, BelongsToMany, BelongsToOne, CALL_PROTOCOL_VERSION, Capability, CapabilityInput, ComputeLogEntry, DEFAULT_ICE_SERVERS, EntanglementProof, EntanglementProofInput, ExceptionInfo, ExceptionType, Expression, ExpressionGeneric, ExpressionGenericInput, ExpressionProof, ExpressionProofInput, ExpressionRef, ExpressionRendered, Flag, FlowInstance, FlowInstanceRecord, FlowTransitionProposal, HasMany, HasOne, HostingUserInfo, IDBCache, Icon, ImportResult, ImportStats, InteractionCall, InteractionMeta, InteractionParameter, InterpretationOverlay, InterpretationRun, LONG_METHODS, LONG_TIMEOUT_MS, LanguageExpression, LanguageHandle, LanguageLanguageInput, LanguageMeta, LanguageMetaInput, LanguageMetaInternal, LanguageRef, Link, LinkExpression, LinkExpressionInput, LinkExpressionMutations, LinkExpressionUpdated, LinkInput, LinkMutations, LinkQuery, Literal, LiveQuery, LocalModel, LocalModelInput, MeshManager, Model$1 as Model, ModelApi, ModelApiInput, ModelInput, ModelQueryBuilder, Neighbourhood, NeighbourhoodExpression, NeighbourhoodProxy, Notification, NotificationInput, NullCache, OnlineAgent, Optional, PROPOSER_GETTER, PaymentRequestResult, Perspective, PerspectiveDiff, PerspectiveDiffExpression, PerspectiveExpression, PerspectiveHandle, PerspectiveInput, PerspectiveProxy, PerspectiveState, PerspectiveUnsignedInput, Property, QuerySubscriptionProxy, READ_METHODS, ReadOnly, Resource, ResourceInput, RpcError, RuntimeInfo, SCOPED_EVENTS, SHACLFlow, SHACLShape, SMART_LITERAL_CONTENT_PREDICATE, SentMessage, SmartLiteral, TextContent, TokenizerSource, TokenizerSourceInput, TriggeredNotification, UserCreationResult, UserStatistics, VerificationRequestResult, VoiceActivityParamsInput, WakerSubscriptionManager, applyUpdate, buildConformanceFilter, buildModelFromJSONSchema, buildPaginationSubquery, buildSDNA, buildSHACL, buildSPARQLQuery, buildWhereCondition, capSentence, clearQueryCache, coalesce, compileWhereClause, concat, createPersistentCache, createTelepresenceChannel, determineNamespace, determinePredicate, effectiveLiteralStorage, escapeQueryString, exists, exprRef2String, fileToDataUri, fn, focus, formatList, formatQueryValue, formatSPARQLValue, getCachedResult, getDefaultValueForType, getMemoizedSHACL, getPropertiesMetadata, getPropertyOption, getRelationsMetadata, hasJsOnlyWhereFilters, hintFor, ifExpr, invalidatePerspectiveCache, isArrayType, isExpression, isIncludeProjection, isLink, isNodeExpression, isNumericType, isObjectType, isSchemaType, isTraverseScope, linkEqual, linkExpressionInputToWire, linkExpressionToWire, linkMutationsToWire, literal, looksLikeUri, neighbourhoodExpressionFromWire, normalizeNamespaceString, normalizeSchemaType, normalizeValue, normalizeWhereForSparql, parseCallMessage, parseExprUrl, parseLit, parseLitBoolean, parseLitNumber, parseSparqlCount, path, queryCacheSize, requireSingleParent, resolveParentPredicate, setCachedResult, setPropertyRegistryEntry, setRelationRegistryEntry, typeDefsString, valueToLiteralIri };
24019
+ export { ACCEPTED_BY_GETTER, AIClient, Model as AIModel, AIModelLoadingStatus, AIPromptExamples, AIPromptExamplesInput, AITask, AITaskInput, Ad4mClient, Ad4mModel, Agent, AgentClient, AgentExpression, AgentSignature, AgentStatus, Apps, AuthInfo, AuthInfoInput, AutoProcessorConfig, BelongsToMany, BelongsToOne, CALL_PROTOCOL_VERSION, Capability, CapabilityInput, ComputeLogEntry, Container, DEFAULT_ICE_SERVERS, EntanglementProof, EntanglementProofInput, ExceptionInfo, ExceptionType, Expression, ExpressionGeneric, ExpressionGenericInput, ExpressionProof, ExpressionProofInput, ExpressionRef, ExpressionRendered, Flag, FlowInstance, FlowInstanceRecord, FlowTransitionProposal, HasMany, HasOne, HostingUserInfo, IDBCache, Icon, ImportResult, ImportStats, InteractionCall, InteractionMeta, InteractionParameter, InterpretationOverlay, InterpretationRun, LONG_METHODS, LONG_TIMEOUT_MS, LanguageExpression, LanguageHandle, LanguageLanguageInput, LanguageMeta, LanguageMetaInput, LanguageMetaInternal, LanguageRef, Link, LinkExpression, LinkExpressionInput, LinkExpressionMutations, LinkExpressionUpdated, LinkInput, LinkMutations, LinkQuery, Literal, LiveQuery, LocalModel, LocalModelInput, MENTION_TEXT_LIMIT, MeshManager, Model$1 as Model, ModelApi, ModelApiInput, ModelInput, ModelQueryBuilder, Neighbourhood, NeighbourhoodExpression, NeighbourhoodProxy, Notification, NotificationInput, NullCache, OnlineAgent, Optional, PROPOSER_GETTER, PaymentRequestResult, Perspective, PerspectiveDiff, PerspectiveDiffExpression, PerspectiveExpression, PerspectiveHandle, PerspectiveInput, PerspectiveProxy, PerspectiveState, PerspectiveUnsignedInput, Property, QuerySubscriptionProxy, READ_METHODS, ReadOnly, Resource, ResourceInput, RpcError, RuntimeInfo, SCOPED_EVENTS, SHACLFlow, SHACLShape, SMART_LITERAL_CONTENT_PREDICATE, SentMessage, SmartLiteral, TextContent, TokenizerSource, TokenizerSourceInput, TriggeredNotification, UserCreationResult, UserStatistics, VerificationRequestResult, VoiceActivityParamsInput, WakerSubscriptionManager, applyUpdate, buildConformanceFilter, buildModelFromJSONSchema, buildPaginationSubquery, buildSDNA, buildSHACL, buildSPARQLQuery, buildWhereCondition, capSentence, clearQueryCache, coalesce, compileWhereClause, concat, createPersistentCache, createTelepresenceChannel, determineNamespace, determinePredicate, effectiveLiteralStorage, escapeQueryString, exists, exprRef2String, fileToDataUri, fn, focus, formatList, formatQueryValue, formatSPARQLValue, getCachedResult, getDefaultValueForType, getMemoizedSHACL, getPropertiesMetadata, getPropertyOption, getRelationsMetadata, hasJsOnlyWhereFilters, hintFor, holdsAWholeWordTerm, ifExpr, invalidatePerspectiveCache, isArrayType, isContainedScope, isContainmentTraversal, isExpression, isIncludeProjection, isLink, isNodeExpression, isNumericType, isObjectType, isSchemaType, isTraverseScope, linkEqual, linkExpressionInputToWire, linkExpressionToWire, linkMutationsToWire, literal, looksLikeUri, neighbourhoodExpressionFromWire, normalizeNamespaceString, normalizeSchemaType, normalizeValue, normalizeWhereForSparql, parseCallMessage, parseExprUrl, parseLit, parseLitBoolean, parseLitNumber, parseSparqlCount, path, queryCacheSize, requireSingleParent, resolveParentPredicate, setCachedResult, setPropertyRegistryEntry, setRelationRegistryEntry, typeDefsString, valueToLiteralIri };