@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
@@ -38,6 +38,13 @@ export declare class Ad4mClient {
38
38
  * handler.
39
39
  */
40
40
  on<K extends EventName>(type: K, handler: (event: EventMap[K]) => void, filter?: EventFilter): () => void;
41
+ /**
42
+ * Call `callback` once when the executor refuses this client's token
43
+ * (expired, revoked, or no session). Every call then fails with a 401
44
+ * `RpcError` and the client stops reconnecting: log in again and build a
45
+ * new client. Returns a function that removes the callback.
46
+ */
47
+ onAuthFailed(callback: (reason: string) => void): () => void;
41
48
  /** Close all event connections and clear in-memory caches */
42
49
  close(): void;
43
50
  }
@@ -95,6 +95,15 @@ export class Ad4mClient {
95
95
  on(type, handler, filter) {
96
96
  return __classPrivateFieldGet(this, _Ad4mClient_apiClient, "f").on(type, handler, filter);
97
97
  }
98
+ /**
99
+ * Call `callback` once when the executor refuses this client's token
100
+ * (expired, revoked, or no session). Every call then fails with a 401
101
+ * `RpcError` and the client stops reconnecting: log in again and build a
102
+ * new client. Returns a function that removes the callback.
103
+ */
104
+ onAuthFailed(callback) {
105
+ return __classPrivateFieldGet(this, _Ad4mClient_apiClient, "f").onAuthFailed(callback);
106
+ }
98
107
  /** Close all event connections and clear in-memory caches */
99
108
  close() {
100
109
  __classPrivateFieldGet(this, _Ad4mClient_agentClient, "f").clearByDidCache();
@@ -47,6 +47,10 @@ export declare class ApiClient {
47
47
  /** `on()` handlers by event type; a type with none has no entry. */
48
48
  private _handlers;
49
49
  private _reconnectCallbacks;
50
+ private _authFailedCallbacks;
51
+ /** Set once the executor refused the token: the reason. The client then
52
+ * never connects again; a new token needs a new client. */
53
+ private _authFailed;
50
54
  private _hasConnectedOnce;
51
55
  private _pendingCalls;
52
56
  private _wsReconnectTimer;
@@ -61,7 +65,11 @@ export declare class ApiClient {
61
65
  private _getWsUrl;
62
66
  private _ensureWs;
63
67
  private _onOpen;
68
+ /** `reason` is set when the executor asked to try again later; calls that fail carry it. */
64
69
  private _onClose;
70
+ /** The executor refused the token: fail every call with 401, stop
71
+ * reconnecting and tell the `onAuthFailed` callbacks, once. */
72
+ private _failAuth;
65
73
  private _startPing;
66
74
  private _stopPing;
67
75
  private _scheduleReconnect;
@@ -102,6 +110,11 @@ export declare class ApiClient {
102
110
  * Does NOT fire on the initial connection — only on reconnects.
103
111
  * Returns an unsubscribe function. */
104
112
  onReconnect(callback: () => void): () => void;
113
+ /** Register a callback that fires once when the executor refuses this
114
+ * client's token: a 401 reply, or a socket closed with code 1008. Every
115
+ * call then fails with a 401 `RpcError` and the client does not reconnect;
116
+ * build a new client to use another token. Returns an unsubscribe function. */
117
+ onAuthFailed(callback: (reason: string) => void): () => void;
105
118
  /** Close the WebSocket and reject pending calls. */
106
119
  closeAll(): void;
107
120
  }
@@ -27,7 +27,12 @@ function nextId() {
27
27
  * for the next socket is safe for writes too. This covers an executor that
28
28
  * is still binding its port (about 1.5 s with the reconnect backoff). */
29
29
  const MAX_CONNECT_ATTEMPTS = 3;
30
- const closedError = () => new RpcError(503, 'WebSocket connection closed');
30
+ const closedError = (reason) => new RpcError(503, reason || 'WebSocket connection closed');
31
+ /** Close code for "try again later": the executor's wallet is locked, so it cannot check the
32
+ * token yet. The token may be good: reconnect as for any close, and pass the reason on. */
33
+ const CLOSE_TRY_AGAIN_LATER = 1013;
34
+ /** Close code the executor uses when the socket's token opens no session, expired or was revoked. */
35
+ const CLOSE_AUTH_FAILED = 1008;
31
36
  export class ApiClient {
32
37
  constructor(baseUrl, token, webSocketImpl, fetchImpl) {
33
38
  // ── WebSocket ───────────────────────────────────────────────────────────
@@ -38,6 +43,10 @@ export class ApiClient {
38
43
  /** `on()` handlers by event type; a type with none has no entry. */
39
44
  this._handlers = new Map();
40
45
  this._reconnectCallbacks = new Set();
46
+ this._authFailedCallbacks = new Set();
47
+ /** Set once the executor refused the token: the reason. The client then
48
+ * never connects again; a new token needs a new client. */
49
+ this._authFailed = null;
41
50
  this._hasConnectedOnce = false;
42
51
  this._pendingCalls = new Map();
43
52
  this._wsReconnectTimer = null;
@@ -73,6 +82,8 @@ export class ApiClient {
73
82
  _ensureWs() {
74
83
  if (this._ws)
75
84
  return;
85
+ if (this._authFailed !== null)
86
+ throw new RpcError(401, this._authFailed);
76
87
  const WsImpl = this._webSocketImpl ?? globalThis.WebSocket;
77
88
  const ws = new WsImpl(this._getWsUrl());
78
89
  this._ws = ws;
@@ -81,9 +92,17 @@ export class ApiClient {
81
92
  resolve();
82
93
  this._onOpen(ws);
83
94
  };
84
- ws.onclose = () => {
85
- reject(closedError());
86
- this._onClose(ws);
95
+ ws.onclose = (event) => {
96
+ // Classify the close for watchApplied() as for every other waiting call.
97
+ reject(event?.code === CLOSE_AUTH_FAILED
98
+ ? new RpcError(401, event.reason || 'token expired or revoked')
99
+ : closedError(event?.code === CLOSE_TRY_AGAIN_LATER ? event.reason : undefined));
100
+ if (event?.code === CLOSE_AUTH_FAILED && this._ws === ws) {
101
+ this._failAuth(event.reason || 'token expired or revoked');
102
+ }
103
+ else {
104
+ this._onClose(ws, event?.code === CLOSE_TRY_AGAIN_LATER ? event.reason : undefined);
105
+ }
87
106
  };
88
107
  });
89
108
  // Only watchApplied() awaits this; a close before open is not an error otherwise.
@@ -103,10 +122,15 @@ export class ApiClient {
103
122
  if (!pending)
104
123
  return; // late reply to a timed-out or aborted call, or a cancel ack
105
124
  const error = parsed.error;
106
- if (error)
107
- pending.reject(new RpcError(error.code ?? 500, error.message ?? 'Unknown error'));
108
- else
125
+ if (!error) {
109
126
  pending.resolve(parsed.result);
127
+ return;
128
+ }
129
+ const rpcError = new RpcError(error.code ?? 500, error.message ?? 'Unknown error');
130
+ pending.reject(rpcError);
131
+ // The executor answers 401 only when the token stopped working, then closes the socket.
132
+ if (rpcError.status === 401)
133
+ this._failAuth(rpcError.body);
110
134
  return;
111
135
  }
112
136
  if (parsed.type === 'pong')
@@ -155,7 +179,8 @@ export class ApiClient {
155
179
  }
156
180
  this._hasConnectedOnce = true;
157
181
  }
158
- _onClose(ws) {
182
+ /** `reason` is set when the executor asked to try again later; calls that fail carry it. */
183
+ _onClose(ws, reason) {
159
184
  // A socket closed by _closeWs() can report after a new one exists.
160
185
  if (this._ws !== ws)
161
186
  return;
@@ -170,12 +195,25 @@ export class ApiClient {
170
195
  pending.retry = false;
171
196
  }
172
197
  else {
173
- pending.reject(closedError());
198
+ pending.reject(closedError(reason));
174
199
  }
175
200
  }
176
201
  if (this._handlers.size > 0 || this._pendingCalls.size > 0)
177
202
  this._scheduleReconnect();
178
203
  }
204
+ /** The executor refused the token: fail every call with 401, stop
205
+ * reconnecting and tell the `onAuthFailed` callbacks, once. */
206
+ _failAuth(reason) {
207
+ if (this._authFailed !== null)
208
+ return;
209
+ this._authFailed = reason;
210
+ const error = new RpcError(401, reason);
211
+ for (const pending of this._pendingCalls.values())
212
+ pending.reject(error);
213
+ this._closeWs();
214
+ for (const cb of [...this._authFailedCallbacks])
215
+ callSafely(cb, 'Error in auth-failed callback:', reason);
216
+ }
179
217
  _startPing() {
180
218
  this._stopPing();
181
219
  this._wsPingTimer = setInterval(() => {
@@ -191,7 +229,7 @@ export class ApiClient {
191
229
  }
192
230
  }
193
231
  _scheduleReconnect() {
194
- if (this._wsReconnectTimer)
232
+ if (this._wsReconnectTimer || this._authFailed !== null)
195
233
  return;
196
234
  const delay = this._wsReconnectDelay;
197
235
  this._wsReconnectDelay = Math.min(this._wsReconnectDelay * 2, MAX_RECONNECT_DELAY_MS);
@@ -291,7 +329,9 @@ export class ApiClient {
291
329
  regs.add(reg);
292
330
  this._scheduleWatch();
293
331
  }
294
- this._ensureWs();
332
+ // A client whose token was refused keeps the handler but opens no socket.
333
+ if (this._authFailed === null)
334
+ this._ensureWs();
295
335
  return () => {
296
336
  const regs = this._handlers.get(type);
297
337
  if (!regs?.delete(reg))
@@ -358,10 +398,13 @@ export class ApiClient {
358
398
  if (key === this._watching)
359
399
  return;
360
400
  this._watching = key;
361
- this._watchSent = this._request('events.watch', events).then(() => { this._watchRetries = 0; }, (e) => {
401
+ const sent = this._request('events.watch', events).then(() => { this._watchRetries = 0; }, (e) => {
362
402
  if (this._watching !== key)
363
403
  return;
364
404
  this._watching = null;
405
+ // A refused token (401) gets no next socket: watchApplied() must not resolve.
406
+ if (e instanceof RpcError && e.status === 401)
407
+ throw e;
365
408
  // A closed socket (503) gets the watch again when the next one opens.
366
409
  if (e instanceof RpcError && e.status === 503)
367
410
  return;
@@ -373,6 +416,9 @@ export class ApiClient {
373
416
  }, WATCH_RETRY_DELAY_MS);
374
417
  }
375
418
  });
419
+ // Only watchApplied() awaits this; a refused watch is not an unhandled rejection otherwise.
420
+ sent.catch(() => { });
421
+ this._watchSent = sent;
376
422
  }
377
423
  _closeWs() {
378
424
  this._stopPing();
@@ -396,6 +442,14 @@ export class ApiClient {
396
442
  this._reconnectCallbacks.add(callback);
397
443
  return () => { this._reconnectCallbacks.delete(callback); };
398
444
  }
445
+ /** Register a callback that fires once when the executor refuses this
446
+ * client's token: a 401 reply, or a socket closed with code 1008. Every
447
+ * call then fails with a 401 `RpcError` and the client does not reconnect;
448
+ * build a new client to use another token. Returns an unsubscribe function. */
449
+ onAuthFailed(callback) {
450
+ this._authFailedCallbacks.add(callback);
451
+ return () => { this._authFailedCallbacks.delete(callback); };
452
+ }
399
453
  /** Close the WebSocket and reject pending calls. */
400
454
  closeAll() {
401
455
  for (const pending of this._pendingCalls.values()) {
@@ -404,6 +458,7 @@ export class ApiClient {
404
458
  this._closeWs();
405
459
  this._handlers.clear();
406
460
  this._reconnectCallbacks.clear();
461
+ this._authFailedCallbacks.clear();
407
462
  // A reused client must not fire onReconnect on its next first open.
408
463
  this._hasConnectedOnce = false;
409
464
  }
@@ -6,5 +6,9 @@ export type AuthInfo = {
6
6
  appUrl: string | null;
7
7
  appIconPath: string | null;
8
8
  capabilities: Array<Capability> | null;
9
+ /**
10
+ * The user a multi-user token is minted for: the login name of a managed agent's
11
+ * account. The token's `sub` carries the agent's DID; this stays as the account's name.
12
+ */
9
13
  userEmail: string | null;
10
14
  };
@@ -1,5 +1,10 @@
1
1
  export type RuntimeInfo = {
2
2
  ad4mExecutorVersion: string;
3
+ /**
4
+ * The commit the executor was built from, or nothing when the build could not tell (no git
5
+ * checkout). Every build between two releases reports one version; this names the build.
6
+ */
7
+ ad4mExecutorCommit: string | null;
3
8
  isInitialized: boolean;
4
9
  isUnlocked: boolean;
5
10
  };
@@ -21,6 +21,7 @@ export * from "./perspectives/AutoProcessor";
21
21
  export * from "./perspectives/InterpretationModels";
22
22
  export * from "./perspectives/FlowModels";
23
23
  export * from "./perspectives/TextContent";
24
+ export * from "./perspectives/Container";
24
25
  export * from "./perspectives/FlowInstance";
25
26
  export * from "./perspectives/SparqlBindings";
26
27
  export * from "./perspectives/WakerSubscriptionManager";
package/lib/src/index.js CHANGED
@@ -21,6 +21,7 @@ export * from "./perspectives/AutoProcessor";
21
21
  export * from "./perspectives/InterpretationModels";
22
22
  export * from "./perspectives/FlowModels";
23
23
  export * from "./perspectives/TextContent";
24
+ export * from "./perspectives/Container";
24
25
  // Also exports FlowFireOutcome / FlowProposeResult, the result shapes of the
25
26
  // flow write API — they live beside the `proposeTransition()` surface.
26
27
  export * from "./perspectives/FlowInstance";
@@ -7,7 +7,7 @@ import { isArrayType, determinePredicate, determineNamespace, buildModelFromJSON
7
7
  import { buildSPARQLQuery, valueToLiteralIri, effectiveLiteralStorage } from "./query-sparql";
8
8
  import { ModelQueryBuilder } from "./ModelQueryBuilder";
9
9
  import { normalizeValue, } from "./hydration";
10
- import { isTraverseScope } from "./types";
10
+ import { isContainedScope, isContainmentTraversal, isTraverseScope } from "./types";
11
11
  // ---------------------------------------------------------------------------
12
12
  // Helpers for Rust-side include resolution
13
13
  // ---------------------------------------------------------------------------
@@ -348,6 +348,24 @@ function jsonToModelInstance(ModelClass, perspective, json, include, properties)
348
348
  }
349
349
  return instance;
350
350
  }
351
+ /**
352
+ * Put `childId` under `parent`. A containment scope `{ id }` writes through the
353
+ * built-in `Container` (#1446): the executor runs the adder of the parent's own
354
+ * `children` relation when its class has one (a block's `we://child`), else
355
+ * writes `ad4m://has_child`. The other forms write their one predicate.
356
+ */
357
+ async function linkToParent(perspective, parent, childCtor, childId, batchId) {
358
+ if (isContainedScope(parent)) {
359
+ await perspective.updateSubject("ad4m://Container", parent.id, { children: { action: "adder", value: [childId] } }, batchId);
360
+ return;
361
+ }
362
+ const link = new Link({
363
+ source: parent.id,
364
+ predicate: resolveParentPredicate(parent, childCtor),
365
+ target: childId,
366
+ });
367
+ await perspective.add(link, 'shared', batchId);
368
+ }
351
369
  /**
352
370
  * Base class for defining data models in AD4M.
353
371
  *
@@ -1005,7 +1023,28 @@ export class Ad4mModel {
1005
1023
  query = { ...query, include: { ...expanded, ...query.include } };
1006
1024
  }
1007
1025
  const queryInput = {};
1008
- if (query.parent) {
1026
+ if (query.parent && isContainedScope(query.parent)) {
1027
+ // Containment: the executor resolves the predicates from the installed
1028
+ // classes, so only the id travels.
1029
+ queryInput.parent = { id: query.parent.id };
1030
+ }
1031
+ else if (query.parent && isContainmentTraversal(query.parent)) {
1032
+ // A traversal over containment: no predicate travels either.
1033
+ const t = query.parent;
1034
+ const traverse = { ids: t.ids };
1035
+ if (t.transitive !== undefined)
1036
+ traverse.transitive = t.transitive;
1037
+ if (t.direction !== undefined)
1038
+ traverse.direction = t.direction;
1039
+ if (t.limitPerAnchor !== undefined)
1040
+ traverse.limitPerAnchor = t.limitPerAnchor;
1041
+ if (t.levels !== undefined)
1042
+ traverse.levels = t.levels;
1043
+ if (t.maxDepth !== undefined)
1044
+ traverse.maxDepth = t.maxDepth;
1045
+ queryInput.parent = traverse;
1046
+ }
1047
+ else if (query.parent) {
1009
1048
  const parentPredicate = resolveParentPredicate(query.parent, this);
1010
1049
  // A traversal keeps its own shape on the wire: the executor reads `ids`,
1011
1050
  // and flattening it to one `id` here is how a request for a whole level
@@ -1029,6 +1068,8 @@ export class Ad4mModel {
1029
1068
  traverse.limitPerAnchor = t.limitPerAnchor;
1030
1069
  if (t.levels !== undefined)
1031
1070
  traverse.levels = t.levels;
1071
+ if (t.maxDepth !== undefined)
1072
+ traverse.maxDepth = t.maxDepth;
1032
1073
  queryInput.parent = traverse;
1033
1074
  }
1034
1075
  else {
@@ -1993,14 +2034,7 @@ export class Ad4mModel {
1993
2034
  if (options?.parent && !options?.batchId) {
1994
2035
  const batchId = await perspective.createBatch();
1995
2036
  await instance.save(batchId);
1996
- const parent = requireSingleParent(options.parent);
1997
- const predicate = resolveParentPredicate(parent, this);
1998
- const link = new Link({
1999
- source: parent.id,
2000
- predicate,
2001
- target: instance.id,
2002
- });
2003
- await perspective.add(link, 'shared', batchId);
2037
+ await linkToParent(perspective, requireSingleParent(options.parent), this, instance.id, batchId);
2004
2038
  await perspective.commitBatch(batchId);
2005
2039
  // Hydrate the instance now that the batch has been committed (mirrors the
2006
2040
  // behaviour of save() when it manages its own batch).
@@ -2010,14 +2044,7 @@ export class Ad4mModel {
2010
2044
  await instance.save(options?.batchId);
2011
2045
  // Create parent → child link if a parent scope was provided
2012
2046
  if (options?.parent) {
2013
- const parent = requireSingleParent(options.parent);
2014
- const predicate = resolveParentPredicate(parent, this);
2015
- const link = new Link({
2016
- source: parent.id,
2017
- predicate,
2018
- target: instance.id,
2019
- });
2020
- await perspective.add(link, 'shared', options?.batchId);
2047
+ await linkToParent(perspective, requireSingleParent(options.parent), this, instance.id, options?.batchId);
2021
2048
  }
2022
2049
  return instance;
2023
2050
  }
@@ -115,9 +115,10 @@ export declare class ModelQueryBuilder<T extends Ad4mModel> {
115
115
  * 3. **String id + model class** — same metadata scan (or field lookup if
116
116
  * options include `field`).
117
117
  * 4. **String id + string predicate** — raw escape hatch, no metadata lookup.
118
- *
119
- * Passing a plain string id with no second argument throws because the
120
- * predicate cannot be resolved without a model class.
118
+ * 5. **String id alone** — containment through the built-in `Container`:
119
+ * the id's `ad4m://has_child` targets, and the targets of the `children`
120
+ * relation of every class the id is an instance of. The executor
121
+ * resolves the predicates; nothing is looked up here.
121
122
  *
122
123
  * @param idOrInstance - The parent's expression URI **or** an Ad4mModel instance
123
124
  * @param modelOrPredicate - A model class (predicate auto-resolved) **or** a raw predicate string
@@ -140,6 +141,9 @@ export declare class ModelQueryBuilder<T extends Ad4mModel> {
140
141
  *
141
142
  * // String id + raw predicate (escape hatch)
142
143
  * Recipe.query(perspective).parent(cookbookId, "cookbook://recipe").get();
144
+ *
145
+ * // String id alone: whatever cookbookId contains
146
+ * Recipe.query(perspective).parent(cookbookId).get();
143
147
  * ```
144
148
  */
145
149
  parent(idOrInstance: string | Ad4mModel, modelOrPredicate?: typeof Ad4mModel | string | {
@@ -162,9 +162,10 @@ export class ModelQueryBuilder {
162
162
  * 3. **String id + model class** — same metadata scan (or field lookup if
163
163
  * options include `field`).
164
164
  * 4. **String id + string predicate** — raw escape hatch, no metadata lookup.
165
- *
166
- * Passing a plain string id with no second argument throws because the
167
- * predicate cannot be resolved without a model class.
165
+ * 5. **String id alone** — containment through the built-in `Container`:
166
+ * the id's `ad4m://has_child` targets, and the targets of the `children`
167
+ * relation of every class the id is an instance of. The executor
168
+ * resolves the predicates; nothing is looked up here.
168
169
  *
169
170
  * @param idOrInstance - The parent's expression URI **or** an Ad4mModel instance
170
171
  * @param modelOrPredicate - A model class (predicate auto-resolved) **or** a raw predicate string
@@ -187,6 +188,9 @@ export class ModelQueryBuilder {
187
188
  *
188
189
  * // String id + raw predicate (escape hatch)
189
190
  * Recipe.query(perspective).parent(cookbookId, "cookbook://recipe").get();
191
+ *
192
+ * // String id alone: whatever cookbookId contains
193
+ * Recipe.query(perspective).parent(cookbookId).get();
190
194
  * ```
191
195
  */
192
196
  parent(idOrInstance, modelOrPredicate, options) {
@@ -214,7 +218,8 @@ export class ModelQueryBuilder {
214
218
  this.queryParams.parent = { id, model: idOrInstance.constructor, ...(field && { field }) };
215
219
  }
216
220
  else {
217
- throw new Error('parent() called with a string id requires a second argument: either a model class or a predicate string');
221
+ // String id alone → containment form of Scope
222
+ this.queryParams.parent = { id };
218
223
  }
219
224
  return this;
220
225
  }
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Shared query helpers used by both the Prolog and SPARQL query pipelines.
3
3
  */
4
- import { isTraverseScope } from "./types";
4
+ import { isContainedScope, isContainmentTraversal, isTraverseScope } from "./types";
5
5
  import { getRelationsMetadata } from "./decorators";
6
6
  /**
7
7
  * Resolves the predicate for a parent query.
@@ -31,6 +31,12 @@ export function resolveParentPredicate(parent, childCtor) {
31
31
  // Raw form — explicit predicate
32
32
  if ('predicate' in parent)
33
33
  return parent.predicate;
34
+ // Containment form — one predicate per containment edge, resolved by the
35
+ // executor from the installed classes. There is no single one to return.
36
+ if (isContainedScope(parent) || isContainmentTraversal(parent)) {
37
+ throw new Error('parent(): a containment scope { id } names no single predicate; the executor resolves ' +
38
+ 'it. Use the model query path (findAll / query / subscribe) to read it.');
39
+ }
34
40
  // Model form — resolve from relation metadata
35
41
  const { model } = parent;
36
42
  const relMeta = getRelationsMetadata(model);
@@ -90,6 +90,13 @@ export type Order = {
90
90
  * **Traverse form** — bounded traversal from one or more anchors, for reading
91
91
  * a tree rather than one node's children. Read-only: AutoProcessor's write
92
92
  * scopes reject it, because it names no single parent to write under.
93
+ *
94
+ * **Containment form** — `{ id }` alone: everything contained in `id`, through
95
+ * the built-in `Container`. That is the targets of `id`'s `ad4m://has_child`
96
+ * links, whatever `id` is, and the targets of the `children` relation (by name,
97
+ * or aliased to `children`) of every class `id` is an instance of. The caller
98
+ * names no class and no predicate; the executor resolves them from the
99
+ * installed classes. See {@link ContainedScope}.
93
100
  */
94
101
  export type Scope = {
95
102
  model: typeof Ad4mModel;
@@ -98,7 +105,22 @@ export type Scope = {
98
105
  } | {
99
106
  id: string;
100
107
  predicate: string;
101
- } | TraverseScope;
108
+ } | TraverseScope | ContainedScope;
109
+ /**
110
+ * Contained in `id`, through `Container`: `{ id }` and nothing else. A
111
+ * misspelt extra field (`{ id, predicat }`) is an error in the executor,
112
+ * never a containment read.
113
+ */
114
+ export interface ContainedScope {
115
+ id: string;
116
+ predicate?: never;
117
+ model?: never;
118
+ field?: never;
119
+ }
120
+ /** Whether this traversal follows containment rather than a named predicate. */
121
+ export declare function isContainmentTraversal(scope: Scope): scope is TraverseByContainment;
122
+ /** Whether this scope is the containment form, `{ id }` alone. */
123
+ export declare function isContainedScope(scope: Scope): scope is ContainedScope;
102
124
  /**
103
125
  * Walk a predicate from several anchors at once, and optionally all the way
104
126
  * down.
@@ -111,7 +133,23 @@ export type Scope = {
111
133
  * or by the model and relation that own it. See {@link TraverseByPredicate} and
112
134
  * {@link TraverseByModel}.
113
135
  */
114
- export type TraverseScope = TraverseByPredicate | TraverseByModel;
136
+ export type TraverseScope = TraverseByPredicate | TraverseByModel | TraverseByContainment;
137
+ /**
138
+ * A traversal over containment, through the built-in `Container`: it names no
139
+ * predicate, and follows every edge the executor resolves from the installed
140
+ * classes — `ad4m://has_child` on any node, and each class's own `children`
141
+ * relation on its instances. `direction: 'in'` from a record reaches whatever
142
+ * holds it: `Container.findAll(p, { parent: { ids: [x], direction: 'in' } })`.
143
+ *
144
+ * The rows are the queried class; the nodes a transitive walk passes through
145
+ * are any container. With no `order`, a transitive walk's rows come nearest
146
+ * first. `levels` is refused on it, and so is `limitPerAnchor` on a
147
+ * transitive one; bound it with `maxDepth`.
148
+ */
149
+ export interface TraverseByContainment extends TraverseOptions {
150
+ predicate?: never;
151
+ model?: never;
152
+ }
115
153
  /** A traversal naming its predicate literally, as the Raw scope does. */
116
154
  export interface TraverseByPredicate extends TraverseOptions {
117
155
  predicate: string;
@@ -181,6 +219,11 @@ export interface TraverseOptions {
181
219
  * every depth.
182
220
  */
183
221
  limitPerAnchor?: number;
222
+ /**
223
+ * With `transitive`, stop the walk after this many hops (`1` is the direct
224
+ * neighbours). Refused without `transitive` and alongside `levels`.
225
+ */
226
+ maxDepth?: number;
184
227
  /**
185
228
  * Walk the relation level by level, keeping this many results per anchor at each depth —
186
229
  * `[10, 5, 3]` is "ten replies, five under each of those, three under each of *those*".
@@ -5,6 +5,14 @@
5
5
  * (`query-utils.ts`, `decorators.ts`, etc.) can import types without
6
6
  * creating circular runtime dependencies on `Ad4mModel.ts`.
7
7
  */
8
+ /** Whether this traversal follows containment rather than a named predicate. */
9
+ export function isContainmentTraversal(scope) {
10
+ return isTraverseScope(scope) && !('predicate' in scope && scope.predicate) && !('model' in scope && scope.model);
11
+ }
12
+ /** Whether this scope is the containment form, `{ id }` alone. */
13
+ export function isContainedScope(scope) {
14
+ return !isTraverseScope(scope) && !('predicate' in scope) && !('model' in scope);
15
+ }
8
16
  /**
9
17
  * Whether this scope is a traversal rather than a single named parent.
10
18
  *
@@ -0,0 +1,41 @@
1
+ import { Ad4mModel } from "../model/Ad4mModel";
2
+ /**
3
+ * The built-in abstract class `Container { children }` (#1446): what holds
4
+ * other records — a channel, a thread, a post, a call, a document, a board.
5
+ *
6
+ * X is contained in P when `P ad4m://has_child X` exists, whatever P is (an
7
+ * instance of any class, or a node no class describes, such as
8
+ * `ad4m://self`), or when P is an instance of a class whose `children`
9
+ * relation (by name, or aliased to `children`) links X:
10
+ *
11
+ * ```typescript
12
+ * @Model({ name: "Block", implements: [Container] })
13
+ * class Block extends Ad4mModel {
14
+ * @HasMany({ through: "we://child", alias: { Container: "children" } })
15
+ * blocks: string[] = [];
16
+ * }
17
+ *
18
+ * // Messages held by P, through has_child or a Block's we://child:
19
+ * await Message.findAll(perspective, { parent: { id: P } });
20
+ * // Everything that holds X:
21
+ * await Container.findAll(perspective, { parent: { ids: [X], direction: "in" } });
22
+ * ```
23
+ *
24
+ * A row's `children` is everything it holds, merged across its classes. A
25
+ * node no class describes is a row of its own when it holds something by
26
+ * `has_child`. Always scope a `Container` query (`where: { id }`, a
27
+ * `children` filter or `parent`): unscoped, it reads every holder in the
28
+ * perspective.
29
+ *
30
+ * Built in: the executor declares it (mirrors
31
+ * `rust-executor/src/perspectives/hardwired_sdna/container.json`) and reads
32
+ * it by its URI, `ad4m://Container`, so a perspective never stores it and an
33
+ * app class named `Container` does not replace it. `register()` on it writes
34
+ * nothing.
35
+ */
36
+ export declare class Container extends Ad4mModel {
37
+ /** The URI the executor reads it by. */
38
+ static readonly builtinUri = "ad4m://Container";
39
+ /** What it holds, whatever their class. */
40
+ children: string[];
41
+ }