@coasys/ad4m 0.12.1-dev → 0.13.0-test-2

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 (97) hide show
  1. package/lib/index.cjs +1469 -781
  2. package/lib/index.js +1453 -779
  3. package/lib/src/Literal.js +6 -5
  4. package/lib/src/agent/AgentClient.d.ts +8 -1
  5. package/lib/src/agent/AgentClient.js +73 -2
  6. package/lib/src/expression/ExpressionRef.js +2 -2
  7. package/lib/src/language/Language.d.ts +41 -3
  8. package/lib/src/model/Ad4mModel.d.ts +28 -28
  9. package/lib/src/model/Ad4mModel.js +129 -101
  10. package/lib/src/model/Ad4mModel.test.js +1543 -535
  11. package/lib/src/model/ModelQueryBuilder.d.ts +48 -34
  12. package/lib/src/model/ModelQueryBuilder.js +163 -78
  13. package/lib/src/model/Subject.js +6 -6
  14. package/lib/src/model/decorators.d.ts +14 -8
  15. package/lib/src/model/decorators.js +41 -14
  16. package/lib/src/model/hydration-batch.d.ts +34 -0
  17. package/lib/src/model/hydration-batch.js +147 -0
  18. package/lib/src/model/hydration.d.ts +3 -3
  19. package/lib/src/model/hydration.js +106 -36
  20. package/lib/src/model/index.d.ts +4 -1
  21. package/lib/src/model/index.js +4 -1
  22. package/lib/src/model/json-schema.js +2 -2
  23. package/lib/src/model/query-cache.d.ts +30 -0
  24. package/lib/src/model/query-cache.js +66 -0
  25. package/lib/src/model/query-cache.test.d.ts +1 -0
  26. package/lib/src/model/query-cache.test.js +43 -0
  27. package/lib/src/model/query-common.d.ts +1 -1
  28. package/lib/src/model/query-common.js +1 -1
  29. package/lib/src/model/query-sparql-batch.d.ts +17 -0
  30. package/lib/src/model/query-sparql-batch.js +260 -0
  31. package/lib/src/model/query-sparql.d.ts +47 -0
  32. package/lib/src/model/query-sparql.js +336 -0
  33. package/lib/src/model/query-utils.d.ts +45 -0
  34. package/lib/src/model/query-utils.js +140 -0
  35. package/lib/src/model/relation-filtering.test.js +15 -15
  36. package/lib/src/model/sdna.js +1 -1
  37. package/lib/src/model/shacl-gen.js +42 -18
  38. package/lib/src/model/subscription-pool.d.ts +39 -0
  39. package/lib/src/model/subscription-pool.js +119 -0
  40. package/lib/src/model/types.d.ts +3 -3
  41. package/lib/src/model/types.js +1 -1
  42. package/lib/src/perspectives/PerspectiveClient.d.ts +1 -17
  43. package/lib/src/perspectives/PerspectiveClient.js +5 -57
  44. package/lib/src/perspectives/PerspectiveProxy.d.ts +51 -30
  45. package/lib/src/perspectives/PerspectiveProxy.js +224 -177
  46. package/lib/src/perspectives/PerspectiveResolver.d.ts +0 -1
  47. package/lib/src/perspectives/PerspectiveResolver.js +0 -11
  48. package/lib/src/perspectives/WakerSubscriptionManager.d.ts +3 -3
  49. package/lib/src/perspectives/WakerSubscriptionManager.js +7 -8
  50. package/lib/src/runtime/RuntimeClient.d.ts +2 -0
  51. package/lib/src/runtime/RuntimeClient.js +17 -0
  52. package/lib/src/runtime/RuntimeResolver.d.ts +14 -0
  53. package/lib/src/runtime/RuntimeResolver.js +84 -0
  54. package/lib/src/schema.gql +14 -1
  55. package/lib/src/shacl/SHACLFlow.d.ts +1 -1
  56. package/lib/src/shacl/SHACLFlow.js +9 -9
  57. package/lib/src/shacl/SHACLShape.d.ts +1 -1
  58. package/lib/src/shacl/SHACLShape.js +38 -38
  59. package/lib/src/typeDefs.js +14 -1
  60. package/lib/src/utils.d.ts +6 -6
  61. package/lib/src/utils.js +6 -6
  62. package/package.json +1 -1
  63. package/src/Literal.test.ts +10 -5
  64. package/src/Literal.ts +6 -5
  65. package/src/agent/AgentClient.ts +81 -1
  66. package/src/expression/ExpressionRef.ts +2 -2
  67. package/src/language/Language.ts +48 -3
  68. package/src/model/Ad4mModel.test.ts +1515 -565
  69. package/src/model/Ad4mModel.ts +142 -102
  70. package/src/model/ModelQueryBuilder.ts +185 -86
  71. package/src/model/Subject.ts +6 -6
  72. package/src/model/decorators.ts +51 -22
  73. package/src/model/hydration-batch.ts +205 -0
  74. package/src/model/hydration.ts +102 -39
  75. package/src/model/index.ts +4 -1
  76. package/src/model/json-schema.ts +2 -2
  77. package/src/model/query-cache.test.ts +54 -0
  78. package/src/model/query-cache.ts +79 -0
  79. package/src/model/query-common.ts +1 -1
  80. package/src/model/query-sparql-batch.ts +301 -0
  81. package/src/model/query-sparql.ts +363 -0
  82. package/src/model/{surreal-utils.ts → query-utils.ts} +40 -27
  83. package/src/model/relation-filtering.test.ts +15 -15
  84. package/src/model/sdna.ts +1 -1
  85. package/src/model/shacl-gen.ts +42 -17
  86. package/src/model/subscription-pool.ts +163 -0
  87. package/src/model/types.ts +3 -3
  88. package/src/perspectives/PerspectiveClient.ts +5 -61
  89. package/src/perspectives/PerspectiveProxy.ts +226 -181
  90. package/src/perspectives/PerspectiveResolver.ts +0 -8
  91. package/src/perspectives/WakerSubscriptionManager.ts +8 -9
  92. package/src/runtime/RuntimeClient.ts +19 -0
  93. package/src/runtime/RuntimeResolver.ts +58 -0
  94. package/src/shacl/SHACLFlow.ts +9 -9
  95. package/src/shacl/SHACLShape.ts +39 -39
  96. package/src/utils.ts +6 -6
  97. package/src/model/query-surreal.ts +0 -280
@@ -12,13 +12,16 @@ import { AIClient } from "../ai/AIClient";
12
12
  import { PERSPECTIVE_QUERY_SUBSCRIPTION } from "./PerspectiveResolver";
13
13
  import { gql } from "@apollo/client/core";
14
14
  import { getPropertiesMetadata, getRelationsMetadata } from "../model/decorators";
15
+ import { getCachedResult, setCachedResult, invalidatePerspectiveCache } from "../model/query-cache";
15
16
  import { AllInstancesResult } from "../model/types";
16
- import { escapeSurrealString } from "../utils";
17
+
17
18
  import { SHACLShape } from "../shacl/SHACLShape";
18
19
  import { SHACLFlow, LinkPattern } from "../shacl/SHACLFlow";
19
20
 
20
21
  type QueryCallback = (result: AllInstancesResult) => void;
21
22
 
23
+
24
+
22
25
  // Generic subscription interface that matches Apollo's Subscription
23
26
  interface Unsubscribable {
24
27
  unsubscribe(): void;
@@ -71,7 +74,6 @@ export class QuerySubscriptionProxy {
71
74
  #initReject?: (reason?: any) => void;
72
75
  #initTimeoutId?: NodeJS.Timeout;
73
76
  #query: string;
74
- isSurrealDB: boolean = false;
75
77
 
76
78
  /** Creates a new query subscription
77
79
  * @param uuid - The UUID of the perspective
@@ -114,11 +116,7 @@ export class QuerySubscriptionProxy {
114
116
  try {
115
117
  // Initialize the query subscription
116
118
  let initialResult;
117
- if (this.isSurrealDB) {
118
- initialResult = await this.#client.perspectiveSubscribeSurrealQuery(this.#uuid, this.#query);
119
- } else {
120
- initialResult = await this.#client.subscribeQuery(this.#uuid, this.#query);
121
- }
119
+ initialResult = await this.#client.subscribeQuery(this.#uuid, this.#query);
122
120
  this.#subscriptionId = initialResult.subscriptionId;
123
121
 
124
122
  // Process the initial result immediately for fast UX
@@ -180,11 +178,7 @@ export class QuerySubscriptionProxy {
180
178
  if (this.#disposed) return;
181
179
 
182
180
  try {
183
- if (this.isSurrealDB) {
184
- await this.#client.perspectiveKeepAliveSurrealQuery(this.#uuid, this.#subscriptionId);
185
- } else {
186
- await this.#client.keepAliveQuery(this.#uuid, this.#subscriptionId);
187
- }
181
+ await this.#client.keepAliveQuery(this.#uuid, this.#subscriptionId);
188
182
  } catch (e) {
189
183
  console.error('Error in keepalive:', e);
190
184
  // try to reinitialize the subscription
@@ -308,13 +302,8 @@ export class QuerySubscriptionProxy {
308
302
 
309
303
  // Tell the backend to dispose of the subscription
310
304
  if (this.#subscriptionId) {
311
- if (this.isSurrealDB) {
312
- this.#client.perspectiveDisposeSurrealQuerySubscription(this.#uuid, this.#subscriptionId)
313
- .catch(e => console.error('Error disposing surreal query subscription:', e));
314
- } else {
315
- this.#client.disposeQuerySubscription(this.#uuid, this.#subscriptionId)
316
- .catch(e => console.error('Error disposing query subscription:', e));
317
- }
305
+ this.#client.disposeQuerySubscription(this.#uuid, this.#subscriptionId)
306
+ .catch(e => console.error('Error disposing query subscription:', e));
318
307
  }
319
308
  }
320
309
  }
@@ -391,6 +380,7 @@ export class PerspectiveProxy {
391
380
  #perspectiveLinkRemovedCallbacks: LinkCallback[]
392
381
  #perspectiveLinkUpdatedCallbacks: LinkCallback[]
393
382
  #perspectiveSyncStateChangeCallbacks: SyncStateChangeCallback[]
383
+ #ensuredSubjectClasses = new Set<string>()
394
384
 
395
385
  /**
396
386
  * Creates a new PerspectiveProxy instance.
@@ -489,7 +479,9 @@ export class PerspectiveProxy {
489
479
  * @param batchId - Optional batch ID to group this operation with others
490
480
  */
491
481
  async executeAction(actions, expression, parameters: Parameter[], batchId?: string) {
492
- return await this.#client.executeCommands(this.#handle.uuid, JSON.stringify(actions), expression, JSON.stringify(parameters), batchId)
482
+ const result = await this.#client.executeCommands(this.#handle.uuid, JSON.stringify(actions), expression, JSON.stringify(parameters), batchId)
483
+ invalidatePerspectiveCache(this.#handle.uuid);
484
+ return result
493
485
  }
494
486
 
495
487
  /**
@@ -545,34 +537,27 @@ export class PerspectiveProxy {
545
537
  }
546
538
 
547
539
  /**
548
- * Executes a SurrealQL query against the perspective's link cache.
549
- * This allows powerful SQL-like queries on the link data stored in SurrealDB.
540
+ * Executes a SPARQL query against the perspective's link cache.
541
+ * This allows powerful SQL-like queries on the link data stored in SPARQL.
550
542
  *
551
543
  * **Security Note:** Only read-only queries (SELECT, RETURN, etc.) are permitted.
552
544
  * Mutating operations (DELETE, UPDATE, INSERT, CREATE, DROP, DEFINE, etc.) are
553
545
  * blocked for security reasons. Use the perspective's add/remove methods to modify links.
554
546
  *
555
- * @param query - SurrealQL query string (read-only operations only)
547
+ * @param query - SPARQL query string (read-only operations only)
556
548
  * @returns Query results as parsed JSON
557
549
  *
558
- * @example
559
- * ```typescript
560
- * // Get all links
561
- * const links = await perspective.querySurrealDB('SELECT * FROM link');
562
- *
563
- * // Filter links by predicate
564
- * const follows = await perspective.querySurrealDB(
565
- * "SELECT * FROM link WHERE predicate = 'follows'"
566
- * );
567
- *
568
- * // Complex aggregation query
569
- * const stats = await perspective.querySurrealDB(
570
- * "SELECT predicate, count() as total FROM link GROUP BY predicate"
571
- * );
572
- * ```
550
+ * Executes a SPARQL query against the perspective's RDF (Oxigraph) store.
551
+ *
552
+ * @param query - SPARQL query string
553
+ * @returns Query results as parsed JSON
573
554
  */
574
- async querySurrealDB(query: string): Promise<any> {
575
- return await this.#client.querySurrealDB(this.#handle.uuid, query)
555
+ async querySparql(query: string): Promise<any> {
556
+ const cached = getCachedResult(this.#handle.uuid, query);
557
+ if (cached !== undefined) return cached;
558
+ const result = await this.#client.querySparql(this.#handle.uuid, query);
559
+ setCachedResult(this.#handle.uuid, query, result);
560
+ return result;
576
561
  }
577
562
 
578
563
  /**
@@ -601,7 +586,9 @@ export class PerspectiveProxy {
601
586
  * ```
602
587
  */
603
588
  async add(link: Link, status: LinkStatus = 'shared', batchId?: string): Promise<LinkExpression> {
604
- return await this.#client.addLink(this.#handle.uuid, link, status, batchId)
589
+ const result = await this.#client.addLink(this.#handle.uuid, link, status, batchId)
590
+ invalidatePerspectiveCache(this.#handle.uuid);
591
+ return result;
605
592
  }
606
593
 
607
594
  /**
@@ -614,7 +601,9 @@ export class PerspectiveProxy {
614
601
  * @returns Array of created LinkExpressions
615
602
  */
616
603
  async addLinks(links: Link[], status: LinkStatus = 'shared', batchId?: string): Promise<LinkExpression[]> {
617
- return await this.#client.addLinks(this.#handle.uuid, links, status, batchId)
604
+ const result = await this.#client.addLinks(this.#handle.uuid, links, status, batchId)
605
+ invalidatePerspectiveCache(this.#handle.uuid);
606
+ return result;
618
607
  }
619
608
 
620
609
  /**
@@ -625,7 +614,9 @@ export class PerspectiveProxy {
625
614
  * @returns Array of removed LinkExpressions
626
615
  */
627
616
  async removeLinks(links: LinkExpressionInput[], batchId?: string): Promise<LinkExpression[]> {
628
- return await this.#client.removeLinks(this.#handle.uuid, links, batchId)
617
+ const result = await this.#client.removeLinks(this.#handle.uuid, links, batchId)
618
+ invalidatePerspectiveCache(this.#handle.uuid);
619
+ return result;
629
620
  }
630
621
 
631
622
  /**
@@ -637,7 +628,9 @@ export class PerspectiveProxy {
637
628
  * @returns Object containing results of the mutations
638
629
  */
639
630
  async linkMutations(mutations: LinkMutations, status: LinkStatus = 'shared'): Promise<LinkExpressionMutations> {
640
- return await this.#client.linkMutations(this.#handle.uuid, mutations, status)
631
+ const result = await this.#client.linkMutations(this.#handle.uuid, mutations, status)
632
+ invalidatePerspectiveCache(this.#handle.uuid);
633
+ return result;
641
634
  }
642
635
 
643
636
  /**
@@ -660,7 +653,9 @@ export class PerspectiveProxy {
660
653
  * @param batchId - Optional batch ID to group this operation with others
661
654
  */
662
655
  async update(oldLink: LinkExpressionInput, newLink: Link, batchId?: string): Promise<LinkExpression> {
663
- return await this.#client.updateLink(this.#handle.uuid, oldLink, newLink, batchId)
656
+ const result = await this.#client.updateLink(this.#handle.uuid, oldLink, newLink, batchId)
657
+ invalidatePerspectiveCache(this.#handle.uuid);
658
+ return result;
664
659
  }
665
660
 
666
661
  /**
@@ -670,7 +665,9 @@ export class PerspectiveProxy {
670
665
  * @param batchId - Optional batch ID to group this operation with others
671
666
  */
672
667
  async remove(link: LinkExpressionInput, batchId?: string): Promise<boolean> {
673
- return await this.#client.removeLink(this.#handle.uuid, link, batchId)
668
+ const result = await this.#client.removeLink(this.#handle.uuid, link, batchId)
669
+ invalidatePerspectiveCache(this.#handle.uuid);
670
+ return result;
674
671
  }
675
672
 
676
673
  /** Creates a new batch for grouping operations */
@@ -680,9 +677,9 @@ export class PerspectiveProxy {
680
677
 
681
678
  /** Commits a batch of operations */
682
679
  async commitBatch(batchId: string): Promise<LinkExpressionMutations> {
683
- return await this.#client.commitBatch(this.#handle.uuid, batchId)
684
-
685
-
680
+ const result = await this.#client.commitBatch(this.#handle.uuid, batchId)
681
+ invalidatePerspectiveCache(this.#handle.uuid);
682
+ return result;
686
683
  }
687
684
  /**
688
685
  * Retrieves and renders an Expression referenced in this perspective.
@@ -1075,6 +1072,14 @@ export class PerspectiveProxy {
1075
1072
  return this.#client.addSdna(this.#handle.uuid, name, sdnaCode, sdnaType, shaclJson)
1076
1073
  }
1077
1074
 
1075
+ /**
1076
+ * Adds a subject class to the perspective.
1077
+ * Alias for addSdna() with sdnaType='subject_class'.
1078
+ */
1079
+ async addSubjectClass(name: string, shaclJson: string) {
1080
+ return this.addSdna(name, '', 'subject_class', shaclJson);
1081
+ }
1082
+
1078
1083
  /**
1079
1084
  * **Recommended way to add SDNA schemas.**
1080
1085
  *
@@ -1107,7 +1112,7 @@ export class PerspectiveProxy {
1107
1112
  const shapeLinks = shape.toLinks();
1108
1113
 
1109
1114
  // Create name -> shape mapping links
1110
- const nameMapping = Literal.fromUrl(`literal://string:shacl://${name}`);
1115
+ const nameMapping = Literal.fromUrl(`literal:string:shacl://${name}`);
1111
1116
  const allLinks: Link[] = [
1112
1117
  ...shapeLinks.map(l => new Link({
1113
1118
  source: l.source,
@@ -1135,7 +1140,7 @@ export class PerspectiveProxy {
1135
1140
  */
1136
1141
  async getShacl(name: string): Promise<SHACLShape | null> {
1137
1142
  // Find the shape URI from the name mapping
1138
- const nameMapping = Literal.fromUrl(`literal://string:shacl://${name}`);
1143
+ const nameMapping = Literal.fromUrl(`literal:string:shacl://${name}`);
1139
1144
  const shapeUriLinks = await this.get(new LinkQuery({
1140
1145
  source: nameMapping.toUrl(),
1141
1146
  predicate: "ad4m://shacl_shape_uri"
@@ -1146,7 +1151,6 @@ export class PerspectiveProxy {
1146
1151
  }
1147
1152
 
1148
1153
  const shapeUri = shapeUriLinks[0].data.target;
1149
- const escapedShapeUri = escapeSurrealString(shapeUri);
1150
1154
 
1151
1155
  // First get property shape URIs so we can query everything in one go
1152
1156
  const propertyLinks = await this.get(new LinkQuery({
@@ -1154,18 +1158,21 @@ export class PerspectiveProxy {
1154
1158
  predicate: "sh://property"
1155
1159
  }));
1156
1160
 
1157
- // Build a single surreal query that fetches all relevant links
1161
+ // Fetch all links from the shape and its property shapes
1158
1162
  const sourceUris = [shapeUri, ...propertyLinks.map(l => l.data.target)];
1159
- const escapedSources = sourceUris.map(u => `'${escapeSurrealString(u)}'`).join(', ');
1160
-
1161
- const query = `SELECT in.uri AS source, predicate, out.uri AS target FROM link WHERE in.uri IN [${escapedSources}]`;
1162
- const result = await this.querySurrealDB(query);
1163
+ const allLinks: Array<{source: string, predicate: string, target: string}> = [];
1164
+ for (const uri of sourceUris) {
1165
+ const links = await this.get(new LinkQuery({ source: uri }));
1166
+ for (const l of links) {
1167
+ allLinks.push({
1168
+ source: l.data.source,
1169
+ predicate: l.data.predicate,
1170
+ target: l.data.target
1171
+ });
1172
+ }
1173
+ }
1163
1174
 
1164
- const shapeLinks = (result || []).map((r: any) => ({
1165
- source: r.source,
1166
- predicate: r.predicate,
1167
- target: r.target
1168
- }));
1175
+ const shapeLinks = allLinks;
1169
1176
 
1170
1177
  return SHACLShape.fromLinks(shapeLinks, shapeUri);
1171
1178
  }
@@ -1279,22 +1286,22 @@ export class PerspectiveProxy {
1279
1286
  }
1280
1287
 
1281
1288
  const flowUri = flowUriLinks[0].data.target;
1282
- const escapedFlowUri = escapeSurrealString(flowUri);
1283
-
1284
1289
  // Compute alternate prefix for state/transition URIs
1285
1290
  const alternatePrefix = flowUri.endsWith('Flow')
1286
1291
  ? flowUri.slice(0, -4) + '.'
1287
1292
  : flowUri + '.';
1288
- const escapedAltPrefix = escapeSurrealString(alternatePrefix);
1289
1293
 
1290
- // Single surreal query to get all flow-related links
1291
- const query = `SELECT in.uri AS source, predicate, out.uri AS target FROM link WHERE in.uri = '${escapedFlowUri}' OR string::starts_with(in.uri, '${escapedAltPrefix}')`;
1292
- const result = await this.querySurrealDB(query);
1294
+ // Fetch flow links using SPARQL to match flowUri source OR alternatePrefix sources
1295
+ const sparqlQuery = `SELECT ?s ?p ?o WHERE {
1296
+ ?s ?p ?o .
1297
+ FILTER(?s = <${flowUri}> || STRSTARTS(STR(?s), "${alternatePrefix}"))
1298
+ }`;
1299
+ const sparqlResult = await this.querySparql(sparqlQuery);
1293
1300
 
1294
- const flowLinks = (result || []).map((r: any) => ({
1295
- source: r.source,
1296
- predicate: r.predicate,
1297
- target: r.target
1301
+ const flowLinks = (sparqlResult || []).map((r: any) => ({
1302
+ source: r.s,
1303
+ predicate: r.p,
1304
+ target: r.o
1298
1305
  }));
1299
1306
 
1300
1307
  return SHACLFlow.fromLinks(flowLinks, flowUri);
@@ -1427,8 +1434,8 @@ export class PerspectiveProxy {
1427
1434
 
1428
1435
  for (const link of links) {
1429
1436
  if (shapePattern.test(link.data.source)) {
1430
- // Parse actions from literal://string:{json}
1431
- const prefix = "literal://string:";
1437
+ // Parse actions from literal:string:{json}
1438
+ const prefix = "literal:string:";
1432
1439
  if (link.data.target.startsWith(prefix)) {
1433
1440
  const jsonStr = link.data.target.slice(prefix.length);
1434
1441
  // Decode URL-encoded JSON if needed, with fallback for raw % characters
@@ -1488,38 +1495,21 @@ export class PerspectiveProxy {
1488
1495
 
1489
1496
  // If no required triples, any expression with links is an instance
1490
1497
  if (metadata.requiredTriples.length === 0) {
1491
- const escapedExpression = escapeSurrealString(expression);
1492
- const checkQuery = `SELECT count() AS count FROM link WHERE in.uri = '${escapedExpression}'`;
1493
- const result = await this.querySurrealDB(checkQuery);
1494
- const count = result[0]?.count ?? 0;
1495
- const countValue = typeof count === 'object' && count?.Int !== undefined ? count.Int : count;
1496
- return countValue > 0;
1498
+ const links = await this.get(new LinkQuery({ source: expression }));
1499
+ return links.length > 0;
1497
1500
  }
1498
1501
 
1499
1502
  // Check if the expression has all required triples (predicate + optional exact target)
1500
1503
  for (const triple of metadata.requiredTriples) {
1501
- const escapedExpression = escapeSurrealString(expression);
1502
- const escapedPredicate = escapeSurrealString(triple.predicate);
1503
- let checkQuery: string;
1504
+ let query: LinkQuery;
1504
1505
  if (triple.target) {
1505
- // Flag: must match both predicate AND exact target value
1506
- const escapedTarget = escapeSurrealString(triple.target);
1507
- checkQuery = `SELECT count() AS count FROM link WHERE in.uri = '${escapedExpression}' AND predicate = '${escapedPredicate}' AND out.uri = '${escapedTarget}'`;
1506
+ query = new LinkQuery({ source: expression, predicate: triple.predicate, target: triple.target });
1508
1507
  } else {
1509
- // Property: just check predicate exists
1510
- checkQuery = `SELECT count() AS count FROM link WHERE in.uri = '${escapedExpression}' AND predicate = '${escapedPredicate}'`;
1511
- }
1512
- const result = await this.querySurrealDB(checkQuery);
1513
-
1514
- if (!result || result.length === 0) {
1515
- return false;
1508
+ query = new LinkQuery({ source: expression, predicate: triple.predicate });
1516
1509
  }
1510
+ const links = await this.get(query);
1517
1511
 
1518
- const count = result[0]?.count ?? 0;
1519
- // Handle potential object response like {Int: 0}
1520
- const countValue = typeof count === 'object' && count?.Int !== undefined ? count.Int : count;
1521
-
1522
- if (countValue === 0) {
1512
+ if (!links || links.length === 0) {
1523
1513
  return false;
1524
1514
  }
1525
1515
  }
@@ -1551,6 +1541,16 @@ export class PerspectiveProxy {
1551
1541
  * Gets subject class metadata from SHACL links using SHACLShape.fromLinks().
1552
1542
  * Retrieves the SHACL shape and extracts metadata for instance queries.
1553
1543
  */
1544
+ async getSubjectClassMetadata(className: string): Promise<{
1545
+ requiredPredicates: string[],
1546
+ requiredTriples: Array<{predicate: string, target?: string}>,
1547
+ properties: Map<string, { predicate: string, resolveLanguage?: string }>,
1548
+ relations: Map<string, { predicate: string, instanceFilter?: string, condition?: string }>
1549
+ } | null> {
1550
+ return this.getSubjectClassMetadataFromSDNA(className);
1551
+ }
1552
+
1553
+ /** @deprecated Use getSubjectClassMetadata() */
1554
1554
  async getSubjectClassMetadataFromSDNA(className: string): Promise<{
1555
1555
  requiredPredicates: string[],
1556
1556
  requiredTriples: Array<{predicate: string, target?: string}>,
@@ -1612,40 +1612,61 @@ export class PerspectiveProxy {
1612
1612
  }
1613
1613
  }
1614
1614
  /**
1615
- * Generates a SurrealDB query to find instances based on class metadata.
1615
+ * Generates a SPARQL query to find instances based on class metadata.
1616
1616
  */
1617
- private generateSurrealInstanceQuery(metadata: {
1617
+ /**
1618
+ * Finds all instances matching subject class metadata by querying links.
1619
+ * Returns base URIs of matching instances.
1620
+ */
1621
+ private async findInstancesByMetadata(metadata: {
1618
1622
  requiredPredicates: string[],
1619
1623
  requiredTriples: Array<{predicate: string, target?: string}>,
1620
1624
  properties: Map<string, { predicate: string, resolveLanguage?: string }>,
1621
1625
  relations: Map<string, { predicate: string, instanceFilter?: string, condition?: string }>
1622
- }): string {
1626
+ }): Promise<Array<{base: string}>> {
1623
1627
  if (metadata.requiredTriples.length === 0) {
1624
- // No required triples - any node with links is an instance
1625
- return `SELECT DISTINCT uri AS base FROM node WHERE count(->link) > 0`;
1628
+ // No required triples - return all unique sources that have any link
1629
+ const allLinks = await this.get(new LinkQuery({}));
1630
+ const sources = new Set(allLinks.map(l => l.data.source));
1631
+ return Array.from(sources).map(s => ({ base: s }));
1626
1632
  }
1627
1633
 
1628
- // Generate WHERE conditions for each required triple (predicate + optional exact target)
1629
- const whereConditions = metadata.requiredTriples.map(triple => {
1630
- const escapedPredicate = escapeSurrealString(triple.predicate);
1631
- if (triple.target) {
1632
- // Flag: must match both predicate AND exact target value
1633
- const escapedTarget = escapeSurrealString(triple.target);
1634
- return `count(->link[WHERE predicate = '${escapedPredicate}' AND out.uri = '${escapedTarget}']) > 0`;
1635
- } else {
1636
- // Property: just check predicate exists
1637
- return `count(->link[WHERE predicate = '${escapedPredicate}']) > 0`;
1634
+ // Use first required triple to get candidate set, then filter by rest
1635
+ const first = metadata.requiredTriples[0];
1636
+ let query: LinkQuery;
1637
+ if (first.target) {
1638
+ query = new LinkQuery({ predicate: first.predicate, target: first.target });
1639
+ } else {
1640
+ query = new LinkQuery({ predicate: first.predicate });
1641
+ }
1642
+ const candidateLinks = await this.get(query);
1643
+ let candidates = [...new Set(candidateLinks.map(l => l.data.source))];
1644
+
1645
+ // Filter by remaining required triples
1646
+ for (let i = 1; i < metadata.requiredTriples.length; i++) {
1647
+ const triple = metadata.requiredTriples[i];
1648
+ const remaining: string[] = [];
1649
+ for (const expr of candidates) {
1650
+ let q: LinkQuery;
1651
+ if (triple.target) {
1652
+ q = new LinkQuery({ source: expr, predicate: triple.predicate, target: triple.target });
1653
+ } else {
1654
+ q = new LinkQuery({ source: expr, predicate: triple.predicate });
1655
+ }
1656
+ const links = await this.get(q);
1657
+ if (links.length > 0) remaining.push(expr);
1638
1658
  }
1639
- }).join(' AND ');
1659
+ candidates = remaining;
1660
+ }
1640
1661
 
1641
- return `SELECT uri AS base FROM node WHERE ${whereConditions}`;
1662
+ return candidates.map(c => ({ base: c }));
1642
1663
  }
1643
1664
 
1644
1665
  /**
1645
- * Gets a property value using SurrealDB when Prolog fails.
1666
+ * Gets a property value using SPARQL when Prolog fails.
1646
1667
  * This is used as a fallback in SdnaOnly mode where link data isn't in Prolog.
1647
1668
  */
1648
- async getPropertyValueViaSurreal(baseExpression: string, className: string, propertyName: string): Promise<any> {
1669
+ async getPropertyValueViaSparql(baseExpression: string, className: string, propertyName: string): Promise<any> {
1649
1670
  const metadata = await this.getSubjectClassMetadataFromSDNA(className);
1650
1671
  if (!metadata) {
1651
1672
  return undefined;
@@ -1656,16 +1677,13 @@ export class PerspectiveProxy {
1656
1677
  return undefined;
1657
1678
  }
1658
1679
 
1659
- const escapedBaseExpression = escapeSurrealString(baseExpression);
1660
- const escapedPredicate = escapeSurrealString(propMeta.predicate);
1661
- const query = `SELECT out.uri AS value FROM link WHERE in.uri = '${escapedBaseExpression}' AND predicate = '${escapedPredicate}' LIMIT 1`;
1662
- const result = await this.querySurrealDB(query);
1680
+ const links = await this.get(new LinkQuery({ source: baseExpression, predicate: propMeta.predicate }));
1663
1681
 
1664
- if (!result || result.length === 0) {
1682
+ if (!links || links.length === 0) {
1665
1683
  return undefined;
1666
1684
  }
1667
1685
 
1668
- const value = result[0].value;
1686
+ const value = links[0].data.target;
1669
1687
 
1670
1688
  // Handle expression resolution if needed
1671
1689
  if (propMeta.resolveLanguage && value) {
@@ -1685,11 +1703,11 @@ export class PerspectiveProxy {
1685
1703
  }
1686
1704
 
1687
1705
  /**
1688
- * Gets relation values using SurrealDB when Prolog fails.
1706
+ * Gets relation values using SPARQL when Prolog fails.
1689
1707
  * This is used as a fallback in SdnaOnly mode where link data isn't in Prolog.
1690
1708
  * Note: This is used by Subject.ts (legacy pattern). Ad4mModel.ts uses getModelMetadata() instead.
1691
1709
  */
1692
- async getRelationValuesViaSurreal(baseExpression: string, className: string, relationName: string): Promise<any[]> {
1710
+ async getRelationValuesViaSparql(baseExpression: string, className: string, relationName: string): Promise<any[]> {
1693
1711
  const metadata = await this.getSubjectClassMetadataFromSDNA(className);
1694
1712
  if (!metadata) {
1695
1713
  return [];
@@ -1700,16 +1718,16 @@ export class PerspectiveProxy {
1700
1718
  return [];
1701
1719
  }
1702
1720
 
1703
- const escapedBaseExpression = escapeSurrealString(baseExpression);
1704
- const escapedPredicate = escapeSurrealString(relMeta.predicate);
1705
- const query = `SELECT out.uri AS value, timestamp FROM link WHERE in.uri = '${escapedBaseExpression}' AND predicate = '${escapedPredicate}' ORDER BY timestamp ASC`;
1706
- const result = await this.querySurrealDB(query);
1721
+ const links = await this.get(new LinkQuery({ source: baseExpression, predicate: relMeta.predicate }));
1707
1722
 
1708
- if (!result || result.length === 0) {
1723
+ if (!links || links.length === 0) {
1709
1724
  return [];
1710
1725
  }
1711
1726
 
1712
- let values = result.map(r => r.value).filter(v => v !== "" && v !== '');
1727
+ // Sort by timestamp ascending
1728
+ links.sort((a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime());
1729
+
1730
+ let values = links.map(l => l.data.target).filter(v => v !== "" && v !== '');
1713
1731
 
1714
1732
  // Apply condition filtering if present
1715
1733
  if (relMeta.condition && values.length > 0) {
@@ -1722,14 +1740,26 @@ export class PerspectiveProxy {
1722
1740
  .replace(/\$base/g, `'${baseExpression}'`)
1723
1741
  .replace(/Target/g, `'${value.replace(/'/g, "\\'")}'`);
1724
1742
 
1725
- // If condition starts with WHERE, wrap in array length check
1726
- if (condition.trim().startsWith('WHERE')) {
1727
- condition = `array::len(SELECT * FROM link ${condition}) > 0`;
1728
- }
1743
+ // Parse condition to extract link query parameters
1744
+ // Conditions typically look like: WHERE in.uri = 'X' AND predicate = 'Y' AND out.uri = 'Z'
1745
+ // or: array::len(SELECT * FROM link WHERE ...) > 0
1746
+ // Convert to queryLinks calls
1747
+ const sourceMatch = condition.match(/in\.uri\s*=\s*'([^']+)'/);
1748
+ const predicateMatch = condition.match(/predicate\s*=\s*'([^']+)'/);
1749
+ const targetMatch = condition.match(/out\.uri\s*=\s*'([^']+)'/);
1729
1750
 
1730
- const filterResult = await this.querySurrealDB(`RETURN ${condition}`);
1731
- const isTrue = filterResult === true || (Array.isArray(filterResult) && filterResult.length > 0 && filterResult[0] === true);
1732
- if (isTrue) {
1751
+ if (sourceMatch || predicateMatch || targetMatch) {
1752
+ const linkQuery: any = {};
1753
+ if (sourceMatch) linkQuery.source = sourceMatch[1];
1754
+ if (predicateMatch) linkQuery.predicate = predicateMatch[1];
1755
+ if (targetMatch) linkQuery.target = targetMatch[1];
1756
+
1757
+ const matchingLinks = await this.get(new LinkQuery(linkQuery));
1758
+ if (matchingLinks.length > 0) {
1759
+ filteredValues.push(value);
1760
+ }
1761
+ } else {
1762
+ // Can't parse condition, include by default
1733
1763
  filteredValues.push(value);
1734
1764
  }
1735
1765
  }
@@ -1760,7 +1790,7 @@ export class PerspectiveProxy {
1760
1790
  }
1761
1791
 
1762
1792
  /**
1763
- * Batch-checks multiple expressions against subject class metadata using a single or limited SurrealDB queries.
1793
+ * Batch-checks multiple expressions against subject class metadata using a single or limited SPARQL queries.
1764
1794
  * This avoids N+1 query problems by checking all values at once.
1765
1795
  */
1766
1796
  async batchCheckSubjectInstances(
@@ -1778,33 +1808,30 @@ export class PerspectiveProxy {
1778
1808
 
1779
1809
  // If no required triples, check which expressions have any links
1780
1810
  if (metadata.requiredTriples.length === 0) {
1781
- const escapedExpressions = expressions.map(e => `'${escapeSurrealString(e)}'`).join(', ');
1782
- const checkQuery = `SELECT in.uri AS uri FROM link WHERE in.uri IN [${escapedExpressions}] GROUP BY in.uri HAVING count() > 0`;
1783
- const result = await this.querySurrealDB(checkQuery);
1784
- return result.map(r => r.uri);
1811
+ const results: string[] = [];
1812
+ for (const expr of expressions) {
1813
+ const links = await this.get(new LinkQuery({ source: expr }));
1814
+ if (links.length > 0) results.push(expr);
1815
+ }
1816
+ return results;
1785
1817
  }
1786
1818
 
1787
- // For each required triple, build a query that finds matching expressions
1819
+ // For each required triple, find which expressions match
1788
1820
  const validExpressionSets: Set<string>[] = [];
1789
1821
 
1790
1822
  for (const triple of metadata.requiredTriples) {
1791
- const escapedExpressions = expressions.map(e => `'${escapeSurrealString(e)}'`).join(', ');
1792
- const escapedPredicate = escapeSurrealString(triple.predicate);
1793
-
1794
- let checkQuery: string;
1795
- if (triple.target) {
1796
- // Flag: must match both predicate AND exact target value
1797
- const escapedTarget = escapeSurrealString(triple.target);
1798
- // Note: Removed GROUP BY because it was causing SurrealDB to only return one result
1799
- checkQuery = `SELECT in.uri AS uri FROM link WHERE in.uri IN [${escapedExpressions}] AND predicate = '${escapedPredicate}' AND out.uri = '${escapedTarget}'`;
1800
- } else {
1801
- // Property: just check predicate exists
1802
- // Note: Removed GROUP BY because it was causing SurrealDB to only return one result
1803
- checkQuery = `SELECT in.uri AS uri FROM link WHERE in.uri IN [${escapedExpressions}] AND predicate = '${escapedPredicate}'`;
1823
+ const matchingExprs = new Set<string>();
1824
+ for (const expr of expressions) {
1825
+ let query: LinkQuery;
1826
+ if (triple.target) {
1827
+ query = new LinkQuery({ source: expr, predicate: triple.predicate, target: triple.target });
1828
+ } else {
1829
+ query = new LinkQuery({ source: expr, predicate: triple.predicate });
1830
+ }
1831
+ const links = await this.get(query);
1832
+ if (links.length > 0) matchingExprs.add(expr);
1804
1833
  }
1805
-
1806
- const result = await this.querySurrealDB(checkQuery);
1807
- validExpressionSets.push(new Set(result.map(r => r.uri)));
1834
+ validExpressionSets.push(matchingExprs);
1808
1835
  }
1809
1836
 
1810
1837
  // Find intersection: expressions that passed ALL required triple checks
@@ -1860,13 +1887,13 @@ export class PerspectiveProxy {
1860
1887
  let instances = []
1861
1888
  for(let className of classes) {
1862
1889
  //console.log(`getAllSubjectInstances: Processing class ${className}`);
1863
- // Query SDNA for metadata, then query SurrealDB for instances
1890
+ // Query SDNA for metadata, then query SPARQL for instances
1864
1891
  const metadata = await this.getSubjectClassMetadataFromSDNA(className);
1865
1892
  //console.log(`getAllSubjectInstances: Got metadata for ${className}:`, metadata);
1866
1893
  if (metadata) {
1867
- const surrealQuery = this.generateSurrealInstanceQuery(metadata);
1868
- const results = await this.querySurrealDB(surrealQuery);
1869
- // console.log(`getAllSubjectInstances: SurrealDB returned ${results?.length || 0} results`);
1894
+ const results = await this.findInstancesByMetadata(metadata);
1895
+
1896
+ // console.log(`getAllSubjectInstances: SPARQL returned ${results?.length || 0} results`);
1870
1897
 
1871
1898
  for (const result of results || []) {
1872
1899
  //console.log(`getAllSubjectInstances: Creating subject for base ${result.base}`);
@@ -1912,11 +1939,11 @@ export class PerspectiveProxy {
1912
1939
 
1913
1940
  let instances = []
1914
1941
  for(let className of classes) {
1915
- // Query SDNA for metadata, then query SurrealDB for instances
1942
+ // Query SDNA for metadata, then query SPARQL for instances
1916
1943
  const metadata = await this.getSubjectClassMetadataFromSDNA(className);
1917
1944
  if (metadata) {
1918
- const surrealQuery = this.generateSurrealInstanceQuery(metadata);
1919
- const results = await this.querySurrealDB(surrealQuery);
1945
+ const results = await this.findInstancesByMetadata(metadata);
1946
+
1920
1947
 
1921
1948
  for (const result of results || []) {
1922
1949
  try {
@@ -1967,16 +1994,16 @@ export class PerspectiveProxy {
1967
1994
  return null;
1968
1995
  }
1969
1996
 
1970
- // Single SurrealDB query to find all classes and their properties/relations
1971
- const query = `SELECT
1972
- in.uri AS shape_source,
1973
- predicate,
1974
- out.uri AS target
1975
- FROM link
1976
- WHERE predicate IN ['rdf://type', 'sh://property', 'sh://collection']`;
1977
-
1978
- const results = await this.querySurrealDB(query);
1979
- if (!results || results.length === 0) return null;
1997
+ // Query links for class shapes using queryLinks
1998
+ const typeLinks = await this.get(new LinkQuery({ predicate: 'rdf://type', target: 'ad4m://SubjectClass' }));
1999
+ const propLinks = await this.get(new LinkQuery({ predicate: 'sh://property' }));
2000
+ const collLinks = await this.get(new LinkQuery({ predicate: 'sh://collection' }));
2001
+ const results = [
2002
+ ...typeLinks.map(l => ({ shape_source: l.data.source, predicate: l.data.predicate, target: l.data.target })),
2003
+ ...propLinks.map(l => ({ shape_source: l.data.source, predicate: l.data.predicate, target: l.data.target })),
2004
+ ...collLinks.map(l => ({ shape_source: l.data.source, predicate: l.data.predicate, target: l.data.target })),
2005
+ ];
2006
+ if (results.length === 0) return null;
1980
2007
 
1981
2008
  // Build a map of className -> { properties, relations }
1982
2009
  const classShapes: Map<string, { shapeUri: string, properties: string[], relations: string[] }> = new Map();
@@ -2076,9 +2103,17 @@ export class PerspectiveProxy {
2076
2103
  * static generateSDNA() function and adds it to the perspective's SDNA.
2077
2104
  */
2078
2105
  async ensureSDNASubjectClass(jsClass: any): Promise<void> {
2106
+ return this.ensureSubjectClass(jsClass);
2107
+ }
2108
+
2109
+ /** Takes a JS class (its constructor) and ensures the SHACL subject class exists. */
2110
+ async ensureSubjectClass(jsClass: any): Promise<void> {
2079
2111
  // Get the class name from the JS class
2080
2112
  const className = jsClass.className || jsClass.prototype?.className || jsClass.name;
2081
2113
 
2114
+ // Skip if already registered for this perspective instance
2115
+ if (this.#ensuredSubjectClasses.has(className)) return;
2116
+
2082
2117
  // Note: Duplicate checking is handled on the Rust side in add_sdna
2083
2118
 
2084
2119
  // Generate SHACL SDNA (Prolog-free)
@@ -2095,6 +2130,16 @@ export class PerspectiveProxy {
2095
2130
  // Pass SHACL JSON to backend (Prolog-free)
2096
2131
  // Backend stores SHACL links directly
2097
2132
  await this.addSdna(className, '', 'subject_class', shaclJson);
2133
+
2134
+ // Mark as registered for this perspective instance
2135
+ this.#ensuredSubjectClasses.add(className);
2136
+ }
2137
+
2138
+ /** Clear the per-instance ensured subject class cache.
2139
+ * Call this after wiping a perspective's links so that
2140
+ * subsequent register() calls re-add SHACL definitions. */
2141
+ clearEnsuredSubjectClasses(): void {
2142
+ this.#ensuredSubjectClasses.clear();
2098
2143
  }
2099
2144
 
2100
2145
  getNeighbourhoodProxy(): NeighbourhoodProxy {
@@ -2175,7 +2220,7 @@ export class PerspectiveProxy {
2175
2220
  }
2176
2221
 
2177
2222
  /**
2178
- * Creates a subscription for a SurrealQL query that updates in real-time.
2223
+ * Creates a subscription for a SPARQL query that updates in real-time.
2179
2224
  *
2180
2225
  * This method:
2181
2226
  * 1. Creates the subscription on the Rust side
@@ -2190,16 +2235,16 @@ export class PerspectiveProxy {
2190
2235
  * when dispose() is called. Make sure to call dispose() when you're done to
2191
2236
  * prevent memory leaks and ensure proper cleanup of resources.
2192
2237
  *
2193
- * @param query - SurrealQL query string
2238
+ /** Subscribe to a query with live updates via the SPARQL subscription endpoint.
2239
+ * @param query - Query string
2194
2240
  * @returns Initialized QuerySubscriptionProxy instance
2195
2241
  */
2196
- async subscribeSurrealDB(query: string): Promise<QuerySubscriptionProxy> {
2242
+ async subscribeQuery(query: string): Promise<QuerySubscriptionProxy> {
2197
2243
  const subscriptionProxy = new QuerySubscriptionProxy(
2198
2244
  this.uuid,
2199
2245
  query,
2200
2246
  this.#client
2201
2247
  );
2202
- subscriptionProxy.isSurrealDB = true;
2203
2248
 
2204
2249
  // Start the subscription on the Rust side first to get the real subscription ID
2205
2250
  await subscriptionProxy.subscribe();