@coasys/ad4m 0.12.0-rc1-dev.1 → 0.12.0-rc1-dev.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 (124) hide show
  1. package/jest.config.js +8 -1
  2. package/lib/index.cjs +13793 -12854
  3. package/lib/index.js +13782 -12851
  4. package/lib/src/Ad4mClient.test.d.ts +1 -0
  5. package/lib/src/Ad4mClient.test.js +1204 -0
  6. package/lib/src/Literal.test.d.ts +1 -0
  7. package/lib/src/Literal.test.js +41 -0
  8. package/lib/src/model/Ad4mModel.d.ts +528 -101
  9. package/lib/src/model/Ad4mModel.js +1670 -748
  10. package/lib/src/model/Ad4mModel.test.js +140 -156
  11. package/lib/src/model/Subject.d.ts +3 -3
  12. package/lib/src/model/Subject.js +25 -25
  13. package/lib/src/model/decorators.d.ts +259 -247
  14. package/lib/src/model/decorators.js +379 -422
  15. package/lib/src/model/mutation.d.ts +81 -0
  16. package/lib/src/model/mutation.js +317 -0
  17. package/lib/src/model/parentUtils.d.ts +32 -0
  18. package/lib/src/model/parentUtils.js +64 -0
  19. package/lib/src/model/prolog/generatePrologFacts.d.ts +36 -0
  20. package/lib/src/model/prolog/generatePrologFacts.js +139 -0
  21. package/lib/src/model/prolog/index.d.ts +1 -0
  22. package/lib/src/model/prolog/index.js +1 -0
  23. package/lib/src/model/query/ModelQueryBuilder.d.ts +82 -0
  24. package/lib/src/model/query/ModelQueryBuilder.js +115 -0
  25. package/lib/src/model/query/QueryBuilder.d.ts +101 -0
  26. package/lib/src/model/query/QueryBuilder.js +193 -0
  27. package/lib/src/model/query/SurrealQueryBuilder.d.ts +48 -0
  28. package/lib/src/model/query/SurrealQueryBuilder.js +371 -0
  29. package/lib/src/model/query/fetchInstance.d.ts +24 -0
  30. package/lib/src/model/query/fetchInstance.js +144 -0
  31. package/lib/src/model/query/hydration.d.ts +54 -0
  32. package/lib/src/model/query/hydration.js +214 -0
  33. package/lib/src/model/query/operations.d.ts +59 -0
  34. package/lib/src/model/query/operations.js +384 -0
  35. package/lib/src/model/query/snapshot.d.ts +59 -0
  36. package/lib/src/model/query/snapshot.js +106 -0
  37. package/lib/src/model/query/surrealCompiler.d.ts +42 -0
  38. package/lib/src/model/query/surrealCompiler.js +304 -0
  39. package/lib/src/model/schema/fromJSONSchema.d.ts +67 -0
  40. package/lib/src/model/schema/fromJSONSchema.js +264 -0
  41. package/lib/src/model/schema/metadata.d.ts +15 -0
  42. package/lib/src/model/schema/metadata.js +112 -0
  43. package/lib/src/model/subscription.d.ts +47 -0
  44. package/lib/src/model/subscription.js +231 -0
  45. package/lib/src/model/transaction.d.ts +27 -0
  46. package/lib/src/model/transaction.js +32 -0
  47. package/lib/src/model/types.d.ts +195 -0
  48. package/lib/src/model/types.js +8 -0
  49. package/lib/src/model/util.d.ts +6 -6
  50. package/lib/src/model/util.js +22 -22
  51. package/lib/src/neighbourhood/NeighbourhoodClient.js +31 -12
  52. package/lib/src/perspectives/PerspectiveProxy.d.ts +9 -9
  53. package/lib/src/perspectives/PerspectiveProxy.js +63 -51
  54. package/lib/src/shacl/SHACLShape.d.ts +9 -0
  55. package/lib/src/shacl/SHACLShape.js +28 -4
  56. package/lib/src/shims/reflect-metadata.d.ts +0 -0
  57. package/lib/src/shims/type-graphql.d.ts +32 -0
  58. package/lib/src/src/Ad4mClient.d.ts +28 -0
  59. package/lib/src/src/Address.d.ts +1 -0
  60. package/lib/src/src/DID.d.ts +1 -0
  61. package/lib/src/src/Exception.d.ts +7 -0
  62. package/lib/src/src/Literal.d.ts +7 -0
  63. package/lib/src/src/PubSub.d.ts +17 -0
  64. package/lib/src/src/SmartLiteral.d.ts +12 -0
  65. package/lib/src/src/agent/Agent.d.ts +110 -0
  66. package/lib/src/src/agent/AgentClient.d.ts +62 -0
  67. package/lib/src/src/agent/AgentResolver.d.ts +30 -0
  68. package/lib/src/src/agent/AgentStatus.d.ts +8 -0
  69. package/lib/src/src/ai/AIClient.d.ts +32 -0
  70. package/lib/src/src/ai/AIResolver.d.ts +75 -0
  71. package/lib/src/src/ai/Tasks.d.ts +37 -0
  72. package/lib/src/src/buildSchema.d.ts +1 -0
  73. package/lib/src/src/expression/Expression.d.ts +28 -0
  74. package/lib/src/src/expression/ExpressionClient.d.ts +13 -0
  75. package/lib/src/src/expression/ExpressionRef.d.ts +9 -0
  76. package/lib/src/src/expression/ExpressionResolver.d.ts +10 -0
  77. package/lib/src/src/index.d.ts +35 -0
  78. package/lib/src/src/jestSetup.d.ts +1 -0
  79. package/lib/src/src/language/Icon.d.ts +4 -0
  80. package/lib/src/src/language/Language.d.ts +206 -0
  81. package/lib/src/src/language/LanguageClient.d.ts +17 -0
  82. package/lib/src/src/language/LanguageContext.d.ts +37 -0
  83. package/lib/src/src/language/LanguageHandle.d.ts +9 -0
  84. package/lib/src/src/language/LanguageMeta.d.ts +35 -0
  85. package/lib/src/src/language/LanguageRef.d.ts +6 -0
  86. package/lib/src/src/language/LanguageResolver.d.ts +19 -0
  87. package/lib/src/src/links/Links.d.ts +39 -0
  88. package/lib/src/src/links/Links.test.d.ts +1 -0
  89. package/lib/src/src/model/Ad4mModel.d.ts +1438 -0
  90. package/lib/src/src/model/Ad4mModel.test.d.ts +1 -0
  91. package/lib/src/src/model/Subject.d.ts +25 -0
  92. package/lib/src/src/model/decorators.d.ts +545 -0
  93. package/lib/src/src/model/util.d.ts +12 -0
  94. package/lib/src/src/neighbourhood/Neighbourhood.d.ts +10 -0
  95. package/lib/src/src/neighbourhood/NeighbourhoodClient.d.ts +25 -0
  96. package/lib/src/src/neighbourhood/NeighbourhoodProxy.d.ts +19 -0
  97. package/lib/src/src/neighbourhood/NeighbourhoodProxy.test.d.ts +1 -0
  98. package/lib/src/src/neighbourhood/NeighbourhoodResolver.d.ts +24 -0
  99. package/lib/src/src/perspectives/LinkQuery.d.ts +11 -0
  100. package/lib/src/src/perspectives/Perspective.d.ts +38 -0
  101. package/lib/src/src/perspectives/Perspective.test.d.ts +1 -0
  102. package/lib/src/src/perspectives/PerspectiveClient.d.ts +97 -0
  103. package/lib/src/src/perspectives/PerspectiveDiff.d.ts +9 -0
  104. package/lib/src/src/perspectives/PerspectiveHandle.d.ts +18 -0
  105. package/lib/src/src/perspectives/PerspectiveProxy.d.ts +865 -0
  106. package/lib/src/src/perspectives/PerspectiveResolver.d.ts +57 -0
  107. package/lib/src/src/runtime/RuntimeClient.d.ts +56 -0
  108. package/lib/src/src/runtime/RuntimeResolver.d.ts +132 -0
  109. package/lib/src/src/shacl/SHACLFlow.d.ts +171 -0
  110. package/lib/src/src/shacl/SHACLFlow.test.d.ts +1 -0
  111. package/lib/src/src/shacl/SHACLShape.d.ts +117 -0
  112. package/lib/src/src/shacl/SHACLShape.test.d.ts +1 -0
  113. package/lib/src/src/typeDefs.d.ts +1 -0
  114. package/lib/src/src/unwrapApolloResult.d.ts +2 -0
  115. package/lib/src/src/utils.d.ts +25 -0
  116. package/package.json +20 -24
  117. package/src/model/Ad4mModel.test.ts +132 -149
  118. package/src/model/Ad4mModel.ts +1930 -784
  119. package/src/model/Subject.ts +24 -24
  120. package/src/model/decorators.ts +626 -482
  121. package/src/model/util.ts +22 -22
  122. package/src/neighbourhood/NeighbourhoodClient.ts +32 -16
  123. package/src/perspectives/PerspectiveProxy.ts +69 -55
  124. package/src/shacl/SHACLShape.ts +33 -4
package/src/model/util.ts CHANGED
@@ -31,41 +31,41 @@ export function pluralToSingular(plural: string): string {
31
31
  }
32
32
 
33
33
  // e.g. "comments" -> "addComment"
34
- export function collectionToAdderName(collection: string): string {
35
- return `add${capitalize(pluralToSingular(collection))}`
34
+ export function relationToAdderName(relation: string): string {
35
+ return `add${capitalize(pluralToSingular(relation))}`
36
36
  }
37
37
 
38
38
  // e.g. "addComments" -> "comments"
39
- export function collectionAdderToName(adderName: string): string {
40
- // Extract the collection name after "add" and lowercase first char
41
- // The method name already has the plural collection name (e.g., "addComments")
42
- let collectionName = adderName.substring(3)
43
- return collectionName.charAt(0).toLowerCase() + collectionName.slice(1)
39
+ export function relationAdderToName(adderName: string): string {
40
+ // Extract the relation name after "add" and lowercase first char
41
+ // The method name already has the plural relation name (e.g., "addComments")
42
+ let relationName = adderName.substring(3)
43
+ return relationName.charAt(0).toLowerCase() + relationName.slice(1)
44
44
  }
45
45
 
46
46
  // e.g. "comments" -> "removeComment"
47
- export function collectionToRemoverName(collection: string): string {
48
- return `remove${capitalize(pluralToSingular(collection))}`
47
+ export function relationToRemoverName(relation: string): string {
48
+ return `remove${capitalize(pluralToSingular(relation))}`
49
49
  }
50
50
 
51
51
  // e.g. "removeComments" -> "comments"
52
- export function collectionRemoverToName(removerName: string): string {
53
- // Extract the collection name after "remove" and lowercase first char
54
- // The method name already has the plural collection name (e.g., "removeComments")
55
- let collectionName = removerName.substring(6)
56
- return collectionName.charAt(0).toLowerCase() + collectionName.slice(1)
52
+ export function relationRemoverToName(removerName: string): string {
53
+ // Extract the relation name after "remove" and lowercase first char
54
+ // The method name already has the plural relation name (e.g., "removeComments")
55
+ let relationName = removerName.substring(6)
56
+ return relationName.charAt(0).toLowerCase() + relationName.slice(1)
57
57
  }
58
58
 
59
- export function collectionSetterToName(setterName: string): string {
60
- // Extract the collection name after "setCollection" and lowercase first char
61
- // The method name already has the plural collection name (e.g., "setCollectionComments")
62
- let collectionName = setterName.substring(13)
63
- return collectionName.charAt(0).toLowerCase() + collectionName.slice(1)
59
+ export function relationSetterToName(setterName: string): string {
60
+ // Extract the relation name after "set" and lowercase first char
61
+ // The method name already has the plural relation name (e.g., "setComments")
62
+ let relationName = setterName.substring(3)
63
+ return relationName.charAt(0).toLowerCase() + relationName.slice(1)
64
64
  }
65
65
 
66
- // e.g. "comments" -> "addComment"
67
- export function collectionToSetterName(collection: string): string {
68
- return `setCollection${capitalize(pluralToSingular(collection))}`
66
+ // e.g. "comments" -> "setComments"
67
+ export function relationToSetterName(relation: string): string {
68
+ return `set${capitalize(relation)}`
69
69
  }
70
70
 
71
71
 
@@ -1,4 +1,4 @@
1
- import { ApolloClient, ApolloQueryResult, gql } from "@apollo/client/core"
1
+ import { ApolloClient, gql, FetchResult } from "@apollo/client/core"
2
2
  import { Address } from "../Address"
3
3
  import { DID } from "../DID"
4
4
  import { OnlineAgent, TelepresenceSignalCallback } from "../language/Language"
@@ -16,7 +16,7 @@ export class NeighbourhoodClient {
16
16
  }
17
17
 
18
18
  async publishFromPerspective(
19
- perspectiveUUID: string,
19
+ perspectiveUUID: string,
20
20
  linkLanguage: Address,
21
21
  meta: Perspective
22
22
  ): Promise<string> {
@@ -45,18 +45,18 @@ export class NeighbourhoodClient {
45
45
  name
46
46
  sharedUrl
47
47
  state
48
- neighbourhood {
48
+ neighbourhood {
49
49
  data {
50
- linkLanguage
51
- meta {
50
+ linkLanguage
51
+ meta {
52
52
  links
53
53
  {
54
54
  author
55
55
  timestamp
56
56
  data { source, predicate, target }
57
57
  proof { valid, invalid, signature, key }
58
- }
59
- }
58
+ }
59
+ }
60
60
  }
61
61
  author
62
62
  }
@@ -95,7 +95,7 @@ export class NeighbourhoodClient {
95
95
  status {
96
96
  author
97
97
  timestamp
98
- data {
98
+ data {
99
99
  links {
100
100
  author
101
101
  timestamp
@@ -225,13 +225,19 @@ export class NeighbourhoodClient {
225
225
  dispatchSignal(perspectiveUUID:string, signal: any) {
226
226
  const handlers = this.#signalHandlers.get(perspectiveUUID)
227
227
  if (handlers) {
228
- handlers.forEach(handler => handler(signal))
228
+ for (const handler of handlers) {
229
+ try {
230
+ handler(signal)
231
+ } catch(e) {
232
+ console.error("Error in signal handler:", e)
233
+ }
234
+ }
229
235
  }
230
236
  }
231
237
 
232
238
  async subscribeToSignals(perspectiveUUID: string): Promise<void> {
233
239
  const that = this
234
- await this.#apolloClient.subscribe({
240
+ this.#apolloClient.subscribe({
235
241
  query: gql`subscription neighbourhoodSignal($perspectiveUUID: String!) {
236
242
  neighbourhoodSignal(perspectiveUUID: $perspectiveUUID) {
237
243
  author
@@ -243,16 +249,23 @@ export class NeighbourhoodClient {
243
249
  timestamp
244
250
  data { source, predicate, target }
245
251
  proof { valid, invalid, signature, key }
246
- }
252
+ }
247
253
  }
248
254
  proof { valid, invalid, signature, key }
249
255
  }
250
256
  }`,
251
257
  variables: { perspectiveUUID }
252
258
  }).subscribe({
253
- next: (result: ApolloQueryResult<any>) => {
254
- const { neighbourhoodSignal } = unwrapApolloResult(result)
255
- that.dispatchSignal(perspectiveUUID, neighbourhoodSignal)
259
+ next: (result: FetchResult<any>) => {
260
+ try {
261
+ const { neighbourhoodSignal } = unwrapApolloResult(result)
262
+ that.dispatchSignal(perspectiveUUID, neighbourhoodSignal)
263
+ } catch(e) {
264
+ console.error("Error in signal subscription:", e)
265
+ }
266
+ },
267
+ error: (err: any) => {
268
+ console.error("Signal subscription error for perspective", perspectiveUUID, err)
256
269
  }
257
270
  })
258
271
  }
@@ -262,9 +275,12 @@ export class NeighbourhoodClient {
262
275
  if (!handlersForPerspective) {
263
276
  handlersForPerspective = []
264
277
  this.#signalHandlers.set(perspectiveUUID, handlersForPerspective)
278
+ // Push handler BEFORE subscribing so it's available when signals arrive
279
+ handlersForPerspective.push(handler)
265
280
  await this.subscribeToSignals(perspectiveUUID)
281
+ } else {
282
+ handlersForPerspective.push(handler)
266
283
  }
267
- handlersForPerspective.push(handler)
268
284
  }
269
285
 
270
286
  removeSignalHandler(perspectiveUUID: string, handler: TelepresenceSignalCallback): void {
@@ -276,4 +292,4 @@ export class NeighbourhoodClient {
276
292
  }
277
293
  }
278
294
  }
279
- }
295
+ }
@@ -11,6 +11,7 @@ import { NeighbourhoodExpression } from "../neighbourhood/Neighbourhood";
11
11
  import { AIClient } from "../ai/AIClient";
12
12
  import { PERSPECTIVE_QUERY_SUBSCRIPTION } from "./PerspectiveResolver";
13
13
  import { gql } from "@apollo/client/core";
14
+ import { getPropertiesMetadata, getRelationsMetadata } from "../model/decorators";
14
15
  import { AllInstancesResult } from "../model/Ad4mModel";
15
16
  import { escapeSurrealString } from "../utils";
16
17
  import { SHACLShape } from "../shacl/SHACLShape";
@@ -446,7 +447,7 @@ export class PerspectiveProxy {
446
447
  * - `addLink`: Creates a new link
447
448
  * - `removeLink`: Removes an existing link
448
449
  * - `setSingleTarget`: Removes all existing links with the same source/predicate and adds a new one
449
- * - `collectionSetter`: Special command for setting collection properties
450
+ * - `collectionSetter`: Special command for setting relation properties
450
451
  *
451
452
  * When used with parameters, the special value "value" in the target field will be
452
453
  * replaced with the actual parameter value.
@@ -1096,7 +1097,7 @@ export class PerspectiveProxy {
1096
1097
  * shape.addProperty({
1097
1098
  * name: 'ingredients',
1098
1099
  * path: 'recipe://has_ingredient',
1099
- * // No maxCount = collection
1100
+ * // No maxCount = relation
1100
1101
  * });
1101
1102
  *
1102
1103
  * await perspective.addShacl('Recipe', shape);
@@ -1554,7 +1555,7 @@ export class PerspectiveProxy {
1554
1555
  requiredPredicates: string[],
1555
1556
  requiredTriples: Array<{predicate: string, target?: string}>,
1556
1557
  properties: Map<string, { predicate: string, resolveLanguage?: string }>,
1557
- collections: Map<string, { predicate: string, instanceFilter?: string, condition?: string }>
1558
+ relations: Map<string, { predicate: string, instanceFilter?: string, condition?: string }>
1558
1559
  } | null> {
1559
1560
  try {
1560
1561
  // Use getShacl() to retrieve the shape via SHACLShape.fromLinks()
@@ -1567,9 +1568,9 @@ export class PerspectiveProxy {
1567
1568
  const requiredPredicates: string[] = [];
1568
1569
  const requiredTriples: Array<{predicate: string, target?: string}> = [];
1569
1570
  const properties = new Map<string, { predicate: string, resolveLanguage?: string }>();
1570
- const collections = new Map<string, { predicate: string, instanceFilter?: string }>();
1571
+ const relations = new Map<string, { predicate: string, instanceFilter?: string }>();
1571
1572
 
1572
- // Build property/collection maps and track writable predicates from shape properties
1573
+ // Build property/relation maps and track writable predicates from shape properties
1573
1574
  const writablePredicates = new Set<string>();
1574
1575
  for (const prop of shape.properties) {
1575
1576
  if (!prop.path || !prop.name) continue;
@@ -1578,9 +1579,9 @@ export class PerspectiveProxy {
1578
1579
  writablePredicates.add(prop.path);
1579
1580
  }
1580
1581
 
1581
- const isCollection = prop.adder && prop.adder.length > 0;
1582
- if (isCollection) {
1583
- collections.set(prop.name, { predicate: prop.path });
1582
+ const isRelation = prop.adder && prop.adder.length > 0;
1583
+ if (isRelation) {
1584
+ relations.set(prop.name, { predicate: prop.path });
1584
1585
  } else {
1585
1586
  properties.set(prop.name, {
1586
1587
  predicate: prop.path,
@@ -1604,7 +1605,7 @@ export class PerspectiveProxy {
1604
1605
  }
1605
1606
  }
1606
1607
 
1607
- return { requiredPredicates, requiredTriples, properties, collections };
1608
+ return { requiredPredicates, requiredTriples, properties, relations };
1608
1609
  } catch (e) {
1609
1610
  console.error(`Error getting SHACL metadata for ${className}:`, e);
1610
1611
  return null;
@@ -1617,7 +1618,7 @@ export class PerspectiveProxy {
1617
1618
  requiredPredicates: string[],
1618
1619
  requiredTriples: Array<{predicate: string, target?: string}>,
1619
1620
  properties: Map<string, { predicate: string, resolveLanguage?: string }>,
1620
- collections: Map<string, { predicate: string, instanceFilter?: string, condition?: string }>
1621
+ relations: Map<string, { predicate: string, instanceFilter?: string, condition?: string }>
1621
1622
  }): string {
1622
1623
  if (metadata.requiredTriples.length === 0) {
1623
1624
  // No required triples - any node with links is an instance
@@ -1684,23 +1685,23 @@ export class PerspectiveProxy {
1684
1685
  }
1685
1686
 
1686
1687
  /**
1687
- * Gets collection values using SurrealDB when Prolog fails.
1688
+ * Gets relation values using SurrealDB when Prolog fails.
1688
1689
  * This is used as a fallback in SdnaOnly mode where link data isn't in Prolog.
1689
1690
  * Note: This is used by Subject.ts (legacy pattern). Ad4mModel.ts uses getModelMetadata() instead.
1690
1691
  */
1691
- async getCollectionValuesViaSurreal(baseExpression: string, className: string, collectionName: string): Promise<any[]> {
1692
+ async getRelationValuesViaSurreal(baseExpression: string, className: string, relationName: string): Promise<any[]> {
1692
1693
  const metadata = await this.getSubjectClassMetadataFromSDNA(className);
1693
1694
  if (!metadata) {
1694
1695
  return [];
1695
1696
  }
1696
1697
 
1697
- const collMeta = metadata.collections.get(collectionName);
1698
- if (!collMeta) {
1698
+ const relMeta = metadata.relations.get(relationName);
1699
+ if (!relMeta) {
1699
1700
  return [];
1700
1701
  }
1701
1702
 
1702
1703
  const escapedBaseExpression = escapeSurrealString(baseExpression);
1703
- const escapedPredicate = escapeSurrealString(collMeta.predicate);
1704
+ const escapedPredicate = escapeSurrealString(relMeta.predicate);
1704
1705
  const query = `SELECT out.uri AS value, timestamp FROM link WHERE in.uri = '${escapedBaseExpression}' AND predicate = '${escapedPredicate}' ORDER BY timestamp ASC`;
1705
1706
  const result = await this.querySurrealDB(query);
1706
1707
 
@@ -1711,12 +1712,12 @@ export class PerspectiveProxy {
1711
1712
  let values = result.map(r => r.value).filter(v => v !== "" && v !== '');
1712
1713
 
1713
1714
  // Apply condition filtering if present
1714
- if (collMeta.condition && values.length > 0) {
1715
+ if (relMeta.condition && values.length > 0) {
1715
1716
  try {
1716
1717
  const filteredValues: string[] = [];
1717
1718
 
1718
1719
  for (const value of values) {
1719
- let condition = collMeta.condition
1720
+ let condition = relMeta.condition
1720
1721
  .replace(/\$perspective/g, `'${this.uuid}'`)
1721
1722
  .replace(/\$base/g, `'${baseExpression}'`)
1722
1723
  .replace(/Target/g, `'${value.replace(/'/g, "\\'")}'`);
@@ -1735,23 +1736,23 @@ export class PerspectiveProxy {
1735
1736
 
1736
1737
  values = filteredValues;
1737
1738
  } catch (error) {
1738
- console.warn(`Failed to apply condition filter for ${collectionName}:`, error);
1739
+ console.warn(`Failed to apply condition filter for ${relationName}:`, error);
1739
1740
  }
1740
1741
  }
1741
1742
 
1742
1743
  // Apply instance filter if present - batch-check all values at once
1743
- if (collMeta.instanceFilter) {
1744
+ if (relMeta.instanceFilter) {
1744
1745
  try {
1745
- const filterMetadata = await this.getSubjectClassMetadataFromSDNA(collMeta.instanceFilter);
1746
+ const filterMetadata = await this.getSubjectClassMetadataFromSDNA(relMeta.instanceFilter);
1746
1747
  if (!filterMetadata) {
1747
1748
  // Fallback to sequential checks if metadata isn't available
1748
- return this.filterInstancesSequential(values, collMeta.instanceFilter);
1749
+ return this.filterInstancesSequential(values, relMeta.instanceFilter);
1749
1750
  }
1750
1751
 
1751
1752
  return await this.batchCheckSubjectInstances(values, filterMetadata);
1752
1753
  } catch (err) {
1753
1754
  // Fallback to sequential checks on error
1754
- return this.filterInstancesSequential(values, collMeta.instanceFilter);
1755
+ return this.filterInstancesSequential(values, relMeta.instanceFilter);
1755
1756
  }
1756
1757
  }
1757
1758
 
@@ -1768,7 +1769,7 @@ export class PerspectiveProxy {
1768
1769
  requiredPredicates: string[],
1769
1770
  requiredTriples: Array<{predicate: string, target?: string}>,
1770
1771
  properties: Map<string, { predicate: string, resolveLanguage?: string }>,
1771
- collections: Map<string, { predicate: string, instanceFilter?: string, condition?: string }>
1772
+ relations: Map<string, { predicate: string, instanceFilter?: string, condition?: string }>
1772
1773
  }
1773
1774
  ): Promise<string[]> {
1774
1775
  if (expressions.length === 0) {
@@ -1933,33 +1934,40 @@ export class PerspectiveProxy {
1933
1934
 
1934
1935
 
1935
1936
  /**
1936
- * Find a subject class by matching an object's properties/collections against SHACL shapes.
1937
+ * Find a subject class by matching an object's properties/relations against SHACL shapes.
1937
1938
  * Queries SHACL links client-side to find a class whose properties contain all required ones.
1938
1939
  * @returns The matching class name, or null if no match found.
1939
1940
  */
1940
1941
  private async findClassByProperties(obj: object): Promise<string | null> {
1941
- // Extract properties and collections from the object
1942
+ // Extract properties and relations from the object
1942
1943
  let properties: string[] = [];
1943
- let collections: string[] = [];
1944
+ let relations: string[] = [];
1944
1945
  const proto = Object.getPrototypeOf(obj);
1946
+ const ctor = proto?.constructor;
1945
1947
 
1946
- if (proto?.__properties) {
1947
- properties = Object.keys(proto.__properties);
1948
+ const registryProps = ctor ? getPropertiesMetadata(ctor) : {};
1949
+ if (Object.keys(registryProps).length > 0) {
1950
+ properties = Object.keys(registryProps);
1948
1951
  } else {
1949
1952
  properties = Object.keys(obj).filter(key => !Array.isArray((obj as any)[key]));
1950
1953
  }
1951
1954
 
1952
- if (proto?.__collections) {
1953
- collections = Object.keys(proto.__collections).filter(key => key !== 'isSubjectInstance');
1955
+ const registryRelations = ctor
1956
+ ? Object.fromEntries(
1957
+ Object.entries(getRelationsMetadata(ctor)).filter(([, r]) => r.kind === 'hasMany' || r.kind === 'belongsToMany')
1958
+ )
1959
+ : {};
1960
+ if (Object.keys(registryRelations).length > 0) {
1961
+ relations = Object.keys(registryRelations).filter(key => key !== 'isSubjectInstance');
1954
1962
  } else {
1955
- collections = Object.keys(obj).filter(key => Array.isArray((obj as any)[key]) && key !== 'isSubjectInstance');
1963
+ relations = Object.keys(obj).filter(key => Array.isArray((obj as any)[key]) && key !== 'isSubjectInstance');
1956
1964
  }
1957
1965
 
1958
- if (properties.length === 0 && collections.length === 0) {
1966
+ if (properties.length === 0 && relations.length === 0) {
1959
1967
  return null;
1960
1968
  }
1961
1969
 
1962
- // Single SurrealDB query to find all classes and their properties/collections
1970
+ // Single SurrealDB query to find all classes and their properties/relations
1963
1971
  const query = `SELECT
1964
1972
  in.uri AS shape_source,
1965
1973
  predicate,
@@ -1970,8 +1978,8 @@ export class PerspectiveProxy {
1970
1978
  const results = await this.querySurrealDB(query);
1971
1979
  if (!results || results.length === 0) return null;
1972
1980
 
1973
- // Build a map of className -> { properties, collections }
1974
- const classShapes: Map<string, { shapeUri: string, properties: string[], collections: string[] }> = new Map();
1981
+ // Build a map of className -> { properties, relations }
1982
+ const classShapes: Map<string, { shapeUri: string, properties: string[], relations: string[] }> = new Map();
1975
1983
 
1976
1984
  // First pass: find all subject classes
1977
1985
  for (const r of results) {
@@ -1981,11 +1989,11 @@ export class PerspectiveProxy {
1981
1989
  if (sepIdx < 0) continue;
1982
1990
  const className = source.substring(sepIdx + 3).split('/').pop();
1983
1991
  if (!className) continue;
1984
- classShapes.set(className, { shapeUri: source, properties: [], collections: [] });
1992
+ classShapes.set(className, { shapeUri: source, properties: [], relations: [] });
1985
1993
  }
1986
1994
  }
1987
1995
 
1988
- // Second pass: collect properties and collections for each class
1996
+ // Second pass: collect properties and relations for each class
1989
1997
  for (const r of results) {
1990
1998
  if (r.predicate === 'sh://property' || r.predicate === 'sh://collection') {
1991
1999
  // Match shape source to class (e.g., "recipe://RecipeShape" -> "Recipe")
@@ -1997,18 +2005,18 @@ export class PerspectiveProxy {
1997
2005
  if (r.predicate === 'sh://property') {
1998
2006
  shape.properties.push(name);
1999
2007
  } else {
2000
- shape.collections.push(name);
2008
+ shape.relations.push(name);
2001
2009
  }
2002
2010
  }
2003
2011
  }
2004
2012
  }
2005
2013
  }
2006
2014
 
2007
- // Find a class that has all required properties and collections
2015
+ // Find a class that has all required properties and relations
2008
2016
  for (const [className, shape] of classShapes) {
2009
2017
  const hasAllProps = properties.every(p => shape.properties.includes(p));
2010
- const hasAllCols = collections.every(c => shape.collections.includes(c));
2011
- if (hasAllProps && hasAllCols) {
2018
+ const hasAllRels = relations.every(c => shape.relations.includes(c));
2019
+ if (hasAllProps && hasAllRels) {
2012
2020
  return className;
2013
2021
  }
2014
2022
  }
@@ -2018,9 +2026,9 @@ export class PerspectiveProxy {
2018
2026
 
2019
2027
  /** Returns all subject classes that match the given template object.
2020
2028
  * This function looks at the properties of the template object and
2021
- * its setters and collections to create a Prolog query that finds
2029
+ * its setters and relations to create a Prolog query that finds
2022
2030
  * all subject classes that would be converted to a proxy object
2023
- * with exactly the same properties and collections.
2031
+ * with exactly the same properties and relations.
2024
2032
  *
2025
2033
  * Since there could be multiple subject classes that match the given
2026
2034
  * criteria, this function returns a list of class names.
@@ -2028,17 +2036,13 @@ export class PerspectiveProxy {
2028
2036
  * @param obj The template object
2029
2037
  */
2030
2038
  async subjectClassesByTemplate(obj: object): Promise<string[]> {
2031
- // SHACL-based lookup: try property matching first (more precise), fall back to className
2032
- try {
2033
- const match = await this.findClassByProperties(obj);
2034
- if (match) {
2035
- return [match];
2036
- }
2037
- } catch (e) {
2038
- console.warn('subjectClassesByTemplate: property matching failed:', e);
2039
- }
2040
-
2041
- // Fall back to className lookup
2039
+ // className lookup first: the @Model decorator sets a precise className on the prototype,
2040
+ // so this is always more specific than property-set matching.
2041
+ // Property matching alone has a superset-ambiguity problem: if DerivedModel adds
2042
+ // properties to BaseModel, then DerivedModel's shape is a superset of BaseModel's
2043
+ // property list, so findClassByProperties could wrongly return DerivedModel for a
2044
+ // BaseModel instance (causing the derived SDNA constructor to fire and inject extra
2045
+ // links into what should be a plain base instance).
2042
2046
  try {
2043
2047
  // @ts-ignore - className is added dynamically by decorators
2044
2048
  const className = obj.className || obj.constructor?.className || obj.constructor?.prototype?.className;
@@ -2052,6 +2056,16 @@ export class PerspectiveProxy {
2052
2056
  console.warn('subjectClassesByTemplate: className lookup failed:', e);
2053
2057
  }
2054
2058
 
2059
+ // Fall back to SHACL-based property matching for undecorated / dynamic objects
2060
+ try {
2061
+ const match = await this.findClassByProperties(obj);
2062
+ if (match) {
2063
+ return [match];
2064
+ }
2065
+ } catch (e) {
2066
+ console.warn('subjectClassesByTemplate: property matching failed:', e);
2067
+ }
2068
+
2055
2069
  return [];
2056
2070
  }
2057
2071
 
@@ -2069,7 +2083,7 @@ export class PerspectiveProxy {
2069
2083
 
2070
2084
  // Generate SHACL SDNA (Prolog-free)
2071
2085
  if (!jsClass.generateSHACL) {
2072
- throw new Error(`Class ${jsClass.name} must have generateSHACL(). Use @ModelOptions decorator.`);
2086
+ throw new Error(`Class ${jsClass.name} must have generateSHACL(). Use @Model decorator.`);
2073
2087
  }
2074
2088
 
2075
2089
  // Get SHACL shape (W3C standard + AD4M action definitions)
@@ -169,6 +169,9 @@ export class SHACLShape {
169
169
  /** AD4M-specific: Destructor actions for removing instances */
170
170
  destructor_actions?: AD4MAction[];
171
171
 
172
+ /** Parent shape URIs for model inheritance (sh:node references) */
173
+ parentShapes: string[];
174
+
172
175
  /**
173
176
  * Create a new SHACL Shape
174
177
  * @param targetClassOrShapeUri - If one argument: the target class (shape URI auto-derived as {class}Shape)
@@ -189,6 +192,19 @@ export class SHACLShape {
189
192
  this.nodeShapeUri = `${namespace}${localName}Shape`;
190
193
  }
191
194
  this.properties = [];
195
+ this.parentShapes = [];
196
+ }
197
+
198
+ /**
199
+ * Add a parent shape reference (sh:node) for model inheritance.
200
+ * When a @Model class extends another @Model, the child shape
201
+ * references the parent shape so SHACL validators can walk the
202
+ * class hierarchy.
203
+ */
204
+ addParentShape(parentShapeUri: string): void {
205
+ if (!this.parentShapes.includes(parentShapeUri)) {
206
+ this.parentShapes.push(parentShapeUri);
207
+ }
192
208
  }
193
209
 
194
210
  /**
@@ -227,6 +243,11 @@ export class SHACLShape {
227
243
  if (this.targetClass) {
228
244
  turtle += ` sh:targetClass <${this.targetClass}> ;\n`;
229
245
  }
246
+
247
+ // Emit sh:node references for parent shapes (model inheritance)
248
+ for (const parentUri of this.parentShapes) {
249
+ turtle += ` sh:node <${parentUri}> ;\n`;
250
+ }
230
251
 
231
252
  // Add property shapes
232
253
  for (let i = 0; i < this.properties.length; i++) {
@@ -308,8 +329,10 @@ export class SHACLShape {
308
329
  });
309
330
  }
310
331
 
311
- // Constructor actions
312
- if (this.constructor_actions && this.constructor_actions.length > 0) {
332
+ // Constructor actions — always emit, even for an empty array.
333
+ // An empty `[]` tells the executor the shape is valid but has no
334
+ // required initial links (all-optional model with no @Flag).
335
+ if (this.constructor_actions) {
313
336
  links.push({
314
337
  source: this.nodeShapeUri,
315
338
  predicate: "ad4m://constructor",
@@ -317,8 +340,8 @@ export class SHACLShape {
317
340
  });
318
341
  }
319
342
 
320
- // Destructor actions
321
- if (this.destructor_actions && this.destructor_actions.length > 0) {
343
+ // Destructor actions — same rationale as constructor.
344
+ if (this.destructor_actions) {
322
345
  links.push({
323
346
  source: this.nodeShapeUri,
324
347
  predicate: "ad4m://destructor",
@@ -691,6 +714,7 @@ export class SHACLShape {
691
714
  return {
692
715
  node_shape_uri: this.nodeShapeUri,
693
716
  target_class: this.targetClass,
717
+ parent_shapes: this.parentShapes.length > 0 ? this.parentShapes : undefined,
694
718
  properties: this.properties.map(p => ({
695
719
  path: p.path,
696
720
  name: p.name,
@@ -749,6 +773,11 @@ export class SHACLShape {
749
773
  if (json.destructor_actions) {
750
774
  shape.destructor_actions = json.destructor_actions;
751
775
  }
776
+ if (json.parent_shapes) {
777
+ for (const ps of json.parent_shapes) {
778
+ shape.addParentShape(ps);
779
+ }
780
+ }
752
781
 
753
782
  return shape;
754
783
  }