@coasys/ad4m 0.13.0-test-interpretation-1 → 0.13.0-test-model-layer

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 (279) hide show
  1. package/lib/index.cjs +2409 -625
  2. package/lib/index.js +2406 -626
  3. package/lib/src/Literal.js +8 -0
  4. package/lib/src/ai/AIClient.js +6 -3
  5. package/lib/src/apiClient.d.ts +40 -4
  6. package/lib/src/apiClient.js +149 -9
  7. package/lib/src/generated/api/RunInterpretationRequest.d.ts +16 -0
  8. package/lib/src/index.d.ts +3 -1
  9. package/lib/src/index.js +2 -0
  10. package/lib/src/model/Ad4mModel.d.ts +34 -16
  11. package/lib/src/model/Ad4mModel.js +302 -63
  12. package/lib/src/model/Ad4mModel.test.js +480 -735
  13. package/lib/src/model/ModelQueryBuilder.js +2 -2
  14. package/lib/src/model/decorators.d.ts +199 -12
  15. package/lib/src/model/decorators.js +88 -32
  16. package/lib/src/model/json-schema.js +7 -21
  17. package/lib/src/model/model-manifest.d.ts +41 -0
  18. package/lib/src/model/model-manifest.js +11 -0
  19. package/lib/src/model/query-common.d.ts +2 -2
  20. package/lib/src/model/query-sparql.d.ts +62 -0
  21. package/lib/src/model/query-sparql.js +78 -15
  22. package/lib/src/model/query-sparql.test.js +92 -10
  23. package/lib/src/model/query-utils.d.ts +7 -2
  24. package/lib/src/model/query-utils.js +21 -11
  25. package/lib/src/model/shacl-gen.js +77 -15
  26. package/lib/src/model/types.d.ts +32 -8
  27. package/lib/src/neighbourhood/NeighbourhoodProxy.test.js +33 -33
  28. package/lib/src/perspectives/AutoProcessor.d.ts +198 -2
  29. package/lib/src/perspectives/FlowInstance.d.ts +187 -0
  30. package/lib/src/perspectives/FlowInstance.js +336 -0
  31. package/lib/src/perspectives/FlowModels.d.ts +94 -0
  32. package/lib/src/perspectives/FlowModels.js +182 -0
  33. package/lib/src/perspectives/InterpretationModels.d.ts +41 -3
  34. package/lib/src/perspectives/InterpretationModels.js +60 -26
  35. package/lib/src/perspectives/PerspectiveClient.d.ts +88 -7
  36. package/lib/src/perspectives/PerspectiveClient.js +138 -11
  37. package/lib/src/perspectives/PerspectiveProxy.d.ts +150 -57
  38. package/lib/src/perspectives/PerspectiveProxy.js +411 -287
  39. package/lib/src/perspectives/SparqlBindings.d.ts +24 -3
  40. package/lib/src/perspectives/SparqlBindings.js +57 -6
  41. package/lib/src/shacl/SHACLFlow.d.ts +273 -47
  42. package/lib/src/shacl/SHACLFlow.js +397 -88
  43. package/lib/src/shacl/SHACLShape.d.ts +19 -3
  44. package/lib/src/shacl/SHACLShape.js +30 -1
  45. package/lib/src/shacl/SHACLShape.test.js +82 -0
  46. package/lib/src/shacl/index.d.ts +1 -1
  47. package/lib/src/shacl/index.js +1 -1
  48. package/package.json +3 -3
  49. package/src/Literal.ts +7 -0
  50. package/src/ai/AIClient.ts +6 -3
  51. package/src/apiClient.test.ts +227 -0
  52. package/src/apiClient.ts +185 -9
  53. package/src/generated/api/RunInterpretationRequest.ts +19 -3
  54. package/src/index.ts +3 -1
  55. package/src/model/Ad4mModel.test.ts +729 -22
  56. package/src/model/Ad4mModel.ts +305 -66
  57. package/src/model/ModelQueryBuilder.ts +2 -2
  58. package/src/model/decorators.ts +278 -44
  59. package/src/model/json-schema.ts +10 -25
  60. package/src/model/query-common.ts +2 -2
  61. package/src/model/query-sparql.test.ts +114 -13
  62. package/src/model/query-sparql.ts +83 -14
  63. package/src/model/query-utils.ts +22 -12
  64. package/src/model/relation-filtering.test.ts +70 -20
  65. package/src/model/shacl-gen.ts +78 -13
  66. package/src/model/shacl-roundtrip.test.ts +134 -2
  67. package/src/model/types.ts +30 -8
  68. package/src/perspectives/AutoProcessor.ts +204 -2
  69. package/src/perspectives/FlowInstance.ts +369 -0
  70. package/src/perspectives/FlowModels.ts +157 -0
  71. package/src/perspectives/InterpretationModels.ts +91 -21
  72. package/src/perspectives/PerspectiveClient.test.ts +67 -6
  73. package/src/perspectives/PerspectiveClient.ts +190 -14
  74. package/src/perspectives/PerspectiveProxy.test.ts +406 -0
  75. package/src/perspectives/PerspectiveProxy.ts +494 -308
  76. package/src/perspectives/SparqlBindings.test.ts +134 -0
  77. package/src/perspectives/SparqlBindings.ts +57 -6
  78. package/src/perspectives/shacl-rpc.test.ts +258 -0
  79. package/src/shacl/SHACLFlow.test.ts +762 -35
  80. package/src/shacl/SHACLFlow.ts +680 -112
  81. package/src/shacl/SHACLShape.test.ts +30 -4
  82. package/src/shacl/SHACLShape.ts +59 -6
  83. package/src/shacl/index.ts +1 -1
  84. package/lib/src/generated/rest/AIModelLoadingStatus.d.ts +0 -7
  85. package/lib/src/generated/rest/AIModelLoadingStatus.js +0 -2
  86. package/lib/src/generated/rest/AddAgentInfosRequest.d.ts +0 -3
  87. package/lib/src/generated/rest/AddAgentInfosRequest.js +0 -2
  88. package/lib/src/generated/rest/AddLinkExpressionRequest.d.ts +0 -6
  89. package/lib/src/generated/rest/AddLinkExpressionRequest.js +0 -1
  90. package/lib/src/generated/rest/AddLinkRequest.d.ts +0 -6
  91. package/lib/src/generated/rest/AddLinkRequest.js +0 -1
  92. package/lib/src/generated/rest/AddLinksBulkRequest.d.ts +0 -6
  93. package/lib/src/generated/rest/AddLinksBulkRequest.js +0 -1
  94. package/lib/src/generated/rest/AddSdnaRequest.d.ts +0 -6
  95. package/lib/src/generated/rest/AddSdnaRequest.js +0 -2
  96. package/lib/src/generated/rest/ApplyTemplateRequest.d.ts +0 -4
  97. package/lib/src/generated/rest/ApplyTemplateRequest.js +0 -2
  98. package/lib/src/generated/rest/AuthInfoInput.d.ts +0 -10
  99. package/lib/src/generated/rest/AuthInfoInput.js +0 -1
  100. package/lib/src/generated/rest/BroadcastRequest.d.ts +0 -6
  101. package/lib/src/generated/rest/BroadcastRequest.js +0 -1
  102. package/lib/src/generated/rest/CapabilityInput.d.ts +0 -5
  103. package/lib/src/generated/rest/CapabilityInput.js +0 -1
  104. package/lib/src/generated/rest/CommitBatchRequest.d.ts +0 -3
  105. package/lib/src/generated/rest/CommitBatchRequest.js +0 -2
  106. package/lib/src/generated/rest/ComputeLogEntry.d.ts +0 -9
  107. package/lib/src/generated/rest/ComputeLogEntry.js +0 -2
  108. package/lib/src/generated/rest/CreateExpressionRequest.d.ts +0 -4
  109. package/lib/src/generated/rest/CreateExpressionRequest.js +0 -2
  110. package/lib/src/generated/rest/CreatePerspectiveRequest.d.ts +0 -3
  111. package/lib/src/generated/rest/CreatePerspectiveRequest.js +0 -2
  112. package/lib/src/generated/rest/CreateSubjectRequest.d.ts +0 -6
  113. package/lib/src/generated/rest/CreateSubjectRequest.js +0 -2
  114. package/lib/src/generated/rest/CreateUserRequest.d.ts +0 -4
  115. package/lib/src/generated/rest/CreateUserRequest.js +0 -2
  116. package/lib/src/generated/rest/CreateUserResponse.d.ts +0 -5
  117. package/lib/src/generated/rest/CreateUserResponse.js +0 -2
  118. package/lib/src/generated/rest/DecoratedExpressionProof.d.ts +0 -6
  119. package/lib/src/generated/rest/DecoratedExpressionProof.js +0 -2
  120. package/lib/src/generated/rest/DecoratedLinkExpression.d.ts +0 -10
  121. package/lib/src/generated/rest/DecoratedLinkExpression.js +0 -1
  122. package/lib/src/generated/rest/DisposeQueryRequest.d.ts +0 -3
  123. package/lib/src/generated/rest/DisposeQueryRequest.js +0 -2
  124. package/lib/src/generated/rest/EmailTestRequest.d.ts +0 -6
  125. package/lib/src/generated/rest/EmailTestRequest.js +0 -2
  126. package/lib/src/generated/rest/EmbedRequest.d.ts +0 -4
  127. package/lib/src/generated/rest/EmbedRequest.js +0 -2
  128. package/lib/src/generated/rest/EntanglementProofInput.d.ts +0 -6
  129. package/lib/src/generated/rest/EntanglementProofInput.js +0 -2
  130. package/lib/src/generated/rest/EntanglementProofPreflightRequest.d.ts +0 -4
  131. package/lib/src/generated/rest/EntanglementProofPreflightRequest.js +0 -2
  132. package/lib/src/generated/rest/ExecuteCommandsRequest.d.ts +0 -4
  133. package/lib/src/generated/rest/ExecuteCommandsRequest.js +0 -2
  134. package/lib/src/generated/rest/ExportRequest.d.ts +0 -5
  135. package/lib/src/generated/rest/ExportRequest.js +0 -2
  136. package/lib/src/generated/rest/ExpressionManyRequest.d.ts +0 -3
  137. package/lib/src/generated/rest/ExpressionManyRequest.js +0 -2
  138. package/lib/src/generated/rest/ExpressionProof.d.ts +0 -4
  139. package/lib/src/generated/rest/ExpressionProof.js +0 -2
  140. package/lib/src/generated/rest/ExpressionProofInput.d.ts +0 -6
  141. package/lib/src/generated/rest/ExpressionProofInput.js +0 -2
  142. package/lib/src/generated/rest/FriendSendMessageRequest.d.ts +0 -3
  143. package/lib/src/generated/rest/FriendSendMessageRequest.js +0 -2
  144. package/lib/src/generated/rest/FriendsListRequest.d.ts +0 -3
  145. package/lib/src/generated/rest/FriendsListRequest.js +0 -2
  146. package/lib/src/generated/rest/GenerateAgentRequest.d.ts +0 -3
  147. package/lib/src/generated/rest/GenerateAgentRequest.js +0 -2
  148. package/lib/src/generated/rest/GenerateJwtRequest.d.ts +0 -4
  149. package/lib/src/generated/rest/GenerateJwtRequest.js +0 -2
  150. package/lib/src/generated/rest/GetSubjectDataRequest.d.ts +0 -4
  151. package/lib/src/generated/rest/GetSubjectDataRequest.js +0 -2
  152. package/lib/src/generated/rest/HostingInfoResponse.d.ts +0 -5
  153. package/lib/src/generated/rest/HostingInfoResponse.js +0 -2
  154. package/lib/src/generated/rest/HostingWalletResponse.d.ts +0 -4
  155. package/lib/src/generated/rest/HostingWalletResponse.js +0 -2
  156. package/lib/src/generated/rest/ImportAgentRequest.d.ts +0 -6
  157. package/lib/src/generated/rest/ImportAgentRequest.js +0 -2
  158. package/lib/src/generated/rest/ImportRequest.d.ts +0 -4
  159. package/lib/src/generated/rest/ImportRequest.js +0 -2
  160. package/lib/src/generated/rest/JoinNeighbourhoodRequest.d.ts +0 -3
  161. package/lib/src/generated/rest/JoinNeighbourhoodRequest.js +0 -2
  162. package/lib/src/generated/rest/KeepAliveQueryRequest.d.ts +0 -3
  163. package/lib/src/generated/rest/KeepAliveQueryRequest.js +0 -2
  164. package/lib/src/generated/rest/LanguageMetaInput.d.ts +0 -6
  165. package/lib/src/generated/rest/LanguageMetaInput.js +0 -2
  166. package/lib/src/generated/rest/Link.d.ts +0 -5
  167. package/lib/src/generated/rest/Link.js +0 -2
  168. package/lib/src/generated/rest/LinkExpression.d.ts +0 -10
  169. package/lib/src/generated/rest/LinkExpression.js +0 -1
  170. package/lib/src/generated/rest/LinkExpressionInput.d.ts +0 -10
  171. package/lib/src/generated/rest/LinkExpressionInput.js +0 -1
  172. package/lib/src/generated/rest/LinkInput.d.ts +0 -5
  173. package/lib/src/generated/rest/LinkInput.js +0 -2
  174. package/lib/src/generated/rest/LinkLanguageTemplatesRequest.d.ts +0 -3
  175. package/lib/src/generated/rest/LinkLanguageTemplatesRequest.js +0 -2
  176. package/lib/src/generated/rest/LinkMutationRequest.d.ts +0 -12
  177. package/lib/src/generated/rest/LinkMutationRequest.js +0 -1
  178. package/lib/src/generated/rest/LinkMutationResponse.d.ts +0 -9
  179. package/lib/src/generated/rest/LinkMutationResponse.js +0 -1
  180. package/lib/src/generated/rest/LinkMutations.d.ts +0 -6
  181. package/lib/src/generated/rest/LinkMutations.js +0 -1
  182. package/lib/src/generated/rest/LinkMutationsRequest.d.ts +0 -5
  183. package/lib/src/generated/rest/LinkMutationsRequest.js +0 -1
  184. package/lib/src/generated/rest/LinkStatus.d.ts +0 -1
  185. package/lib/src/generated/rest/LinkStatus.js +0 -2
  186. package/lib/src/generated/rest/LinkUpdateInput.d.ts +0 -5
  187. package/lib/src/generated/rest/LinkUpdateInput.js +0 -1
  188. package/lib/src/generated/rest/LockAgentRequest.d.ts +0 -3
  189. package/lib/src/generated/rest/LockAgentRequest.js +0 -2
  190. package/lib/src/generated/rest/LoginUserRequest.d.ts +0 -5
  191. package/lib/src/generated/rest/LoginUserRequest.js +0 -2
  192. package/lib/src/generated/rest/ModelType.d.ts +0 -1
  193. package/lib/src/generated/rest/ModelType.js +0 -2
  194. package/lib/src/generated/rest/NotificationGrantRequest.d.ts +0 -3
  195. package/lib/src/generated/rest/NotificationGrantRequest.js +0 -2
  196. package/lib/src/generated/rest/NotificationInput.d.ts +0 -10
  197. package/lib/src/generated/rest/NotificationInput.js +0 -2
  198. package/lib/src/generated/rest/OpenLinkRequest.d.ts +0 -3
  199. package/lib/src/generated/rest/OpenLinkRequest.js +0 -2
  200. package/lib/src/generated/rest/PermitCapabilityRequest.d.ts +0 -3
  201. package/lib/src/generated/rest/PermitCapabilityRequest.js +0 -2
  202. package/lib/src/generated/rest/PerspectiveInput.d.ts +0 -4
  203. package/lib/src/generated/rest/PerspectiveInput.js +0 -1
  204. package/lib/src/generated/rest/PromptRequest.d.ts +0 -4
  205. package/lib/src/generated/rest/PromptRequest.js +0 -2
  206. package/lib/src/generated/rest/PublicPerspectiveInput.d.ts +0 -4
  207. package/lib/src/generated/rest/PublicPerspectiveInput.js +0 -1
  208. package/lib/src/generated/rest/PublishLanguageRequest.d.ts +0 -5
  209. package/lib/src/generated/rest/PublishLanguageRequest.js +0 -1
  210. package/lib/src/generated/rest/PublishNeighbourhoodRequest.d.ts +0 -6
  211. package/lib/src/generated/rest/PublishNeighbourhoodRequest.js +0 -1
  212. package/lib/src/generated/rest/QueryRequest.d.ts +0 -7
  213. package/lib/src/generated/rest/QueryRequest.js +0 -2
  214. package/lib/src/generated/rest/RemoveLinkRequest.d.ts +0 -5
  215. package/lib/src/generated/rest/RemoveLinkRequest.js +0 -1
  216. package/lib/src/generated/rest/RemoveLinksBulkRequest.d.ts +0 -5
  217. package/lib/src/generated/rest/RemoveLinksBulkRequest.js +0 -1
  218. package/lib/src/generated/rest/RequestCapabilityRequest.d.ts +0 -4
  219. package/lib/src/generated/rest/RequestCapabilityRequest.js +0 -1
  220. package/lib/src/generated/rest/RequestPaymentRequest.d.ts +0 -3
  221. package/lib/src/generated/rest/RequestPaymentRequest.js +0 -2
  222. package/lib/src/generated/rest/RequestVerificationRequest.d.ts +0 -4
  223. package/lib/src/generated/rest/RequestVerificationRequest.js +0 -2
  224. package/lib/src/generated/rest/ResourceInput.d.ts +0 -4
  225. package/lib/src/generated/rest/ResourceInput.js +0 -2
  226. package/lib/src/generated/rest/SetDefaultModelRequest.d.ts +0 -4
  227. package/lib/src/generated/rest/SetDefaultModelRequest.js +0 -1
  228. package/lib/src/generated/rest/SetFreeHostingEnabledRequest.d.ts +0 -3
  229. package/lib/src/generated/rest/SetFreeHostingEnabledRequest.js +0 -2
  230. package/lib/src/generated/rest/SetHotWalletAddressRequest.d.ts +0 -3
  231. package/lib/src/generated/rest/SetHotWalletAddressRequest.js +0 -2
  232. package/lib/src/generated/rest/SetMultiUserRequest.d.ts +0 -3
  233. package/lib/src/generated/rest/SetMultiUserRequest.js +0 -2
  234. package/lib/src/generated/rest/SetOnlineStatusRequest.d.ts +0 -5
  235. package/lib/src/generated/rest/SetOnlineStatusRequest.js +0 -1
  236. package/lib/src/generated/rest/SetStatusRequest.d.ts +0 -3
  237. package/lib/src/generated/rest/SetStatusRequest.js +0 -2
  238. package/lib/src/generated/rest/SetUserFreeAccessRequest.d.ts +0 -4
  239. package/lib/src/generated/rest/SetUserFreeAccessRequest.js +0 -2
  240. package/lib/src/generated/rest/SignMessageRequest.d.ts +0 -3
  241. package/lib/src/generated/rest/SignMessageRequest.js +0 -2
  242. package/lib/src/generated/rest/SignalRequest.d.ts +0 -6
  243. package/lib/src/generated/rest/SignalRequest.js +0 -1
  244. package/lib/src/generated/rest/SubscribeQueryRequest.d.ts +0 -3
  245. package/lib/src/generated/rest/SubscribeQueryRequest.js +0 -2
  246. package/lib/src/generated/rest/SubscribeQueryResponse.d.ts +0 -4
  247. package/lib/src/generated/rest/SubscribeQueryResponse.js +0 -2
  248. package/lib/src/generated/rest/TrustedAgentsRequest.d.ts +0 -3
  249. package/lib/src/generated/rest/TrustedAgentsRequest.js +0 -2
  250. package/lib/src/generated/rest/UnlockAgentRequest.d.ts +0 -4
  251. package/lib/src/generated/rest/UnlockAgentRequest.js +0 -2
  252. package/lib/src/generated/rest/UpdateLinkRequest.d.ts +0 -7
  253. package/lib/src/generated/rest/UpdateLinkRequest.js +0 -1
  254. package/lib/src/generated/rest/UpdatePerspectiveRequest.d.ts +0 -3
  255. package/lib/src/generated/rest/UpdatePerspectiveRequest.js +0 -2
  256. package/lib/src/generated/rest/UpdateProfileRequest.d.ts +0 -5
  257. package/lib/src/generated/rest/UpdateProfileRequest.js +0 -1
  258. package/lib/src/generated/rest/UserStatistics.d.ts +0 -9
  259. package/lib/src/generated/rest/UserStatistics.js +0 -2
  260. package/lib/src/generated/rest/VerificationRequestResult.d.ts +0 -6
  261. package/lib/src/generated/rest/VerificationRequestResult.js +0 -2
  262. package/lib/src/generated/rest/VerifyEmailRequest.d.ts +0 -6
  263. package/lib/src/generated/rest/VerifyEmailRequest.js +0 -2
  264. package/lib/src/generated/rest/VerifySignatureRequest.d.ts +0 -5
  265. package/lib/src/generated/rest/VerifySignatureRequest.js +0 -2
  266. package/lib/src/generated/rest/WriteSettingsRequest.d.ts +0 -3
  267. package/lib/src/generated/rest/WriteSettingsRequest.js +0 -2
  268. package/lib/src/generated/rest/index.d.ts +0 -73
  269. package/lib/src/generated/rest/index.js +0 -8
  270. package/lib/src/generated/rest/routes.d.ts +0 -587
  271. package/lib/src/generated/rest/routes.js +0 -3
  272. package/lib/src/model/query-surreal.d.ts +0 -44
  273. package/lib/src/model/query-surreal.js +0 -249
  274. package/lib/src/model/surreal-utils.d.ts +0 -42
  275. package/lib/src/model/surreal-utils.js +0 -128
  276. package/lib/src/perspectives/PerspectiveProxy.test.d.ts +0 -1
  277. package/lib/src/perspectives/PerspectiveProxy.test.js +0 -34
  278. package/lib/src/restClient.d.ts +0 -52
  279. package/lib/src/restClient.js +0 -227
package/lib/index.cjs CHANGED
@@ -27,6 +27,8 @@ class ApiClient {
27
27
  // ── WebSocket RPC core ──────────────────────────────────────────────────
28
28
  this._ws = null;
29
29
  this._wsCallbacks = new Set();
30
+ this._reconnectCallbacks = new Set();
31
+ this._hasConnectedOnce = false;
30
32
  this._pendingCalls = new Map();
31
33
  this._wsReady = null;
32
34
  this._wsReadyResolve = null;
@@ -34,6 +36,7 @@ class ApiClient {
34
36
  this._wsReconnectDelay = INITIAL_RECONNECT_DELAY_MS;
35
37
  this._wsClosed = false;
36
38
  this._wsPingTimer = null;
39
+ this._ignoredResponseIds = new Set();
37
40
  this.baseUrl = baseUrl;
38
41
  this.token = token;
39
42
  this._webSocketImpl = webSocketImpl;
@@ -68,7 +71,22 @@ class ApiClient {
68
71
  this._wsReadyResolve = resolve;
69
72
  });
70
73
  const url = this._getWsUrl();
71
- const WsImpl = this._webSocketImpl ?? WebSocket;
74
+ // Fallback order: injected impl → globalThis.WebSocket (browsers, Node ≥ 22) → require('ws') (Node ≤ 20).
75
+ // globalThis lookup avoids a ReferenceError on Node 18 where `WebSocket` is not a global.
76
+ const globalWs = globalThis.WebSocket;
77
+ let WsImpl;
78
+ if (this._webSocketImpl) {
79
+ WsImpl = this._webSocketImpl;
80
+ }
81
+ else if (globalWs) {
82
+ WsImpl = globalWs;
83
+ }
84
+ else {
85
+ // Lazy CommonJS require so bundlers targeting browsers don't try to bundle `ws`.
86
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
87
+ const req = eval('require');
88
+ WsImpl = req('ws');
89
+ }
72
90
  const ws = new WsImpl(url);
73
91
  this._ws = ws;
74
92
  ws.onopen = () => {
@@ -78,6 +96,18 @@ class ApiClient {
78
96
  this._wsReadyResolve = null;
79
97
  }
80
98
  this._startPing();
99
+ // Fire reconnect callbacks only on reconnect (not first connect)
100
+ if (this._hasConnectedOnce) {
101
+ for (const cb of this._reconnectCallbacks) {
102
+ try {
103
+ cb();
104
+ }
105
+ catch (e) {
106
+ console.error('Error in reconnect callback:', e);
107
+ }
108
+ }
109
+ }
110
+ this._hasConnectedOnce = true;
81
111
  };
82
112
  ws.onmessage = (event) => {
83
113
  let parsed;
@@ -106,6 +136,13 @@ class ApiClient {
106
136
  }
107
137
  return;
108
138
  }
139
+ // Discard ack responses to cancel requests we sent — they have
140
+ // an id that was never in _pendingCalls, so without this guard
141
+ // they'd leak into subscriber callbacks as spurious events.
142
+ if (id && this._ignoredResponseIds.has(id)) {
143
+ this._ignoredResponseIds.delete(id);
144
+ return;
145
+ }
109
146
  // Server-push event (no id, or id not in pending) → route to subscribers
110
147
  for (const cb of this._wsCallbacks)
111
148
  cb(parsed);
@@ -162,40 +199,130 @@ class ApiClient {
162
199
  if (this._wsReady)
163
200
  await this._wsReady;
164
201
  }
202
+ /**
203
+ * Like `_ready()`, but races the connection against an AbortSignal so
204
+ * that callers don't hang if the signal fires while connecting.
205
+ */
206
+ async _readyOrAbort(signal) {
207
+ if (signal?.aborted) {
208
+ throw new DOMException('Aborted', 'AbortError');
209
+ }
210
+ await new Promise((resolve, reject) => {
211
+ let settled = false;
212
+ const finish = (fn) => {
213
+ if (settled)
214
+ return;
215
+ settled = true;
216
+ if (signal && onAbort) {
217
+ signal.removeEventListener('abort', onAbort);
218
+ }
219
+ fn();
220
+ };
221
+ const onAbort = signal
222
+ ? () => finish(() => reject(new DOMException('Aborted', 'AbortError')))
223
+ : null;
224
+ if (onAbort) {
225
+ signal.addEventListener('abort', onAbort, { once: true });
226
+ }
227
+ this._ready().then(() => finish(resolve), (error) => finish(() => reject(error)));
228
+ });
229
+ }
165
230
  // ── RPC call method ─────────────────────────────────────────────────────
166
231
  /**
167
232
  * Send an RPC call over the WebSocket connection.
168
233
  * @param type - The operation type (e.g. 'agent.get', 'perspective.all')
169
234
  * @param params - Optional parameters to include in the message
170
- * @param timeoutMs - Optional per-call timeout override in ms. Defaults to
171
- * [[DEFAULT_TIMEOUT_MS]]. Use for long-running calls (LLM prompts,
172
- * holochain ops) that legitimately exceed the default.
235
+ * @param options - Optional call options: `signal` (AbortSignal for
236
+ * cancellation) and/or `timeoutMs` (per-call timeout override,
237
+ * defaults to [[DEFAULT_TIMEOUT_MS]] — use for long-running calls
238
+ * like LLM prompts or holochain ops that legitimately exceed it).
173
239
  * @returns Promise that resolves with the result from the server
174
240
  */
175
- async call(type, params, timeoutMs) {
176
- await this._ready();
241
+ async call(type, params, options) {
242
+ // Fast-path: if the caller already aborted, bail out before
243
+ // opening the socket. Matches fetch()'s behaviour.
244
+ const signal = options?.signal;
245
+ if (signal?.aborted) {
246
+ throw new DOMException('Aborted', 'AbortError');
247
+ }
248
+ await this._readyOrAbort(signal);
177
249
  const id = nextId();
178
250
  // Put params under a "params" key to avoid collision with
179
251
  // protocol fields "id" and "type" (e.g. params might contain
180
252
  // { id: modelId } or { type: "db" }).
181
253
  const message = { id, type, params: params || {} };
182
- const effectiveTimeout = timeoutMs ?? DEFAULT_TIMEOUT_MS;
254
+ const effectiveTimeout = options?.timeoutMs ?? DEFAULT_TIMEOUT_MS;
183
255
  return new Promise((resolve, reject) => {
256
+ let abortHandler = null;
257
+ const cleanup = () => {
258
+ if (signal && abortHandler) {
259
+ signal.removeEventListener('abort', abortHandler);
260
+ abortHandler = null;
261
+ }
262
+ };
184
263
  const timer = setTimeout(() => {
185
264
  this._pendingCalls.delete(id);
265
+ cleanup();
186
266
  reject(new RpcError(408, `RPC call '${type}' timed out after ${effectiveTimeout}ms`));
187
267
  }, effectiveTimeout);
268
+ // Wrap resolve/reject so we always clean up the abort listener.
188
269
  this._pendingCalls.set(id, {
189
- resolve: resolve,
190
- reject,
270
+ resolve: (value) => { cleanup(); resolve(value); },
271
+ reject: (reason) => { cleanup(); reject(reason); },
191
272
  timer,
192
273
  });
274
+ if (signal) {
275
+ abortHandler = () => {
276
+ // Drop the pending entry first so the late server
277
+ // reply (if any) routes to the event subscribers,
278
+ // not to a stale resolver.
279
+ this._pendingCalls.delete(id);
280
+ clearTimeout(timer);
281
+ cleanup();
282
+ // Best-effort `request.cancel` — the executor will
283
+ // race the cancellation token against the in-flight
284
+ // handler. If the socket is already gone there's
285
+ // nothing useful we can send; the client side is
286
+ // still aborted either way.
287
+ if (this._ws && this._ws.readyState === 1 /* OPEN */) {
288
+ try {
289
+ const cancelId = nextId();
290
+ this._ignoredResponseIds.add(cancelId);
291
+ // Safety-net eviction: if the executor's ack never
292
+ // arrives (e.g. the socket drops right after we
293
+ // send request.cancel), the normal cleanup path
294
+ // (deleting the id when its response lands) never
295
+ // fires and the entry would live in this set for
296
+ // the lifetime of the client. Bound it instead —
297
+ // DEFAULT_TIMEOUT_MS is already the ceiling every
298
+ // other in-flight call uses, so an ack that hasn't
299
+ // shown up by then isn't coming.
300
+ setTimeout(() => {
301
+ this._ignoredResponseIds.delete(cancelId);
302
+ }, DEFAULT_TIMEOUT_MS);
303
+ this._ws.send(JSON.stringify({
304
+ id: cancelId,
305
+ type: 'request.cancel',
306
+ params: { targetId: id },
307
+ }));
308
+ }
309
+ catch (e) {
310
+ // Swallow — the user-visible failure mode is the
311
+ // AbortError below; a socket send failure here
312
+ // doesn't change client semantics.
313
+ }
314
+ }
315
+ reject(new DOMException('Aborted', 'AbortError'));
316
+ };
317
+ signal.addEventListener('abort', abortHandler, { once: true });
318
+ }
193
319
  if (this._ws && this._ws.readyState === 1 /* OPEN */) {
194
320
  this._ws.send(JSON.stringify(message));
195
321
  }
196
322
  else {
197
323
  this._pendingCalls.delete(id);
198
324
  clearTimeout(timer);
325
+ cleanup();
199
326
  reject(new RpcError(503, 'WebSocket not connected'));
200
327
  }
201
328
  });
@@ -233,6 +360,13 @@ class ApiClient {
233
360
  this._wsReady = null;
234
361
  }
235
362
  }
363
+ /** Register a callback that fires after a successful WebSocket reconnect.
364
+ * Does NOT fire on the initial connection — only on reconnects.
365
+ * Returns an unsubscribe function. */
366
+ onReconnect(callback) {
367
+ this._reconnectCallbacks.add(callback);
368
+ return () => { this._reconnectCallbacks.delete(callback); };
369
+ }
236
370
  /** Close all open WebSocket connections and reject pending calls. */
237
371
  closeAll() {
238
372
  // Reject pending calls
@@ -243,6 +377,12 @@ class ApiClient {
243
377
  this._pendingCalls.clear();
244
378
  this._closeWs();
245
379
  this._wsCallbacks.clear();
380
+ this._reconnectCallbacks.clear();
381
+ // Reset the first-connect gate so a reused client (closeAll() →
382
+ // later call()/subscribe() reopening via _ensureWs) does not fire
383
+ // freshly registered onReconnect callbacks on the initial open of
384
+ // the new connection — see the contract on onReconnect().
385
+ this._hasConnectedOnce = false;
246
386
  }
247
387
  }
248
388
 
@@ -783,6 +923,14 @@ class Literal {
783
923
  const numberString = body.substring(7);
784
924
  return parseFloat(numberString);
785
925
  }
926
+ if (body.startsWith("boolean:")) {
927
+ const boolString = decodeURIComponent(body.substring(8));
928
+ if (boolString === "true")
929
+ return true;
930
+ if (boolString === "false")
931
+ return false;
932
+ throw new Error(`Can't parse boolean literal: ${boolString}`);
933
+ }
786
934
  if (body.startsWith("json:")) {
787
935
  const json = body.substring(5);
788
936
  return JSON.parse(decodeURIComponent(json));
@@ -1193,6 +1341,13 @@ class SHACLShape {
1193
1341
  if (prop.writable !== undefined) {
1194
1342
  turtle += ` ad4m:writable ${prop.writable} ;\n`;
1195
1343
  }
1344
+ // Interpreter dedup key: `toLinks()` and `toJSON()` preserve
1345
+ // `identity`; a Turtle export must too or the round-trip through
1346
+ // Turtle silently drops the interpretation-dedup marker
1347
+ // (CodeRabbit #881 review).
1348
+ if (prop.identity !== undefined) {
1349
+ turtle += ` ad4m:identity ${prop.identity} ;\n`;
1350
+ }
1196
1351
  // Remove trailing semicolon and close bracket
1197
1352
  turtle = turtle.slice(0, -2) + '\n';
1198
1353
  turtle += isLast ? ` ] .\n` : ` ] ;\n`;
@@ -1275,6 +1430,13 @@ class SHACLShape {
1275
1430
  target: prop.path
1276
1431
  });
1277
1432
  // Constraints
1433
+ if (prop.ordering) {
1434
+ links.push({
1435
+ source: propShapeId,
1436
+ predicate: "ad4m://ordering",
1437
+ target: `literal:string:${prop.ordering}`
1438
+ });
1439
+ }
1278
1440
  if (prop.datatype) {
1279
1441
  links.push({
1280
1442
  source: propShapeId,
@@ -1521,6 +1683,10 @@ class SHACLShape {
1521
1683
  const datatypeLink = links.find(l => l.source === propShapeId && l.predicate === "sh://datatype");
1522
1684
  if (datatypeLink)
1523
1685
  prop.datatype = datatypeLink.target;
1686
+ const orderingLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://ordering");
1687
+ if (orderingLink) {
1688
+ prop.ordering = orderingLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
1689
+ }
1524
1690
  const nodeKindLink = links.find(l => l.source === propShapeId && l.predicate === "sh://nodeKind");
1525
1691
  if (nodeKindLink) {
1526
1692
  prop.nodeKind = nodeKindLink.target.replace('sh://', '');
@@ -1582,10 +1748,15 @@ class SHACLShape {
1582
1748
  val = val.substring(8);
1583
1749
  prop.writable = val === 'true';
1584
1750
  }
1751
+ // The general language selector (e.g. "literal" or a custom address).
1585
1752
  const resolveLangLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://resolveLanguage");
1586
1753
  if (resolveLangLink) {
1587
1754
  prop.resolveLanguage = resolveLangLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
1588
1755
  }
1756
+ // Storage mode is derived from `resolveLanguage` alone:
1757
+ // - unset → deterministic typed literal (fast path)
1758
+ // - "literal" → signed envelope on the built-in literal language
1759
+ // - <address> → expression on that custom language
1589
1760
  // Parse action arrays
1590
1761
  const setterLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://setter");
1591
1762
  if (setterLink) {
@@ -1753,6 +1924,11 @@ class SHACLShape {
1753
1924
  transform: p.transform,
1754
1925
  interpretation_hint: p.interpretationHint,
1755
1926
  identity: p.identity,
1927
+ // The backend reads the ordering declaration back from the
1928
+ // `ad4m://ordering` link that `parse_shacl_to_links` writes from this
1929
+ // field. `ensureSubjectClass` ships `toJSON()`, so omitting it here
1930
+ // leaves `@HasMany({ ordering })` inert no matter what `toLinks()` does.
1931
+ ordering: p.ordering,
1756
1932
  })),
1757
1933
  constructor_actions: this.constructor_actions,
1758
1934
  destructor_actions: this.destructor_actions,
@@ -1784,7 +1960,7 @@ class SHACLShape {
1784
1960
  hasValue: p.has_value,
1785
1961
  local: p.local,
1786
1962
  writable: p.writable,
1787
- resolveLanguage: p.resolve_language,
1963
+ resolveLanguage: p.resolve_language ?? p.resolveLanguage,
1788
1964
  setter: p.setter,
1789
1965
  adder: p.adder,
1790
1966
  remover: p.remover,
@@ -1800,6 +1976,7 @@ class SHACLShape {
1800
1976
  transform: p.transform,
1801
1977
  interpretationHint: p.interpretation_hint,
1802
1978
  identity: p.identity,
1979
+ ordering: p.ordering,
1803
1980
  });
1804
1981
  }
1805
1982
  if (json.constructor_actions) {
@@ -1924,20 +2101,38 @@ interpretationHint) {
1924
2101
  name: propName,
1925
2102
  path: propMeta.through,
1926
2103
  };
1927
- // Determine datatype from initial value or resolveLanguage
1928
- if (propMeta.resolveLanguage === "literal") {
1929
- propShape.datatype = "xsd://string";
2104
+ // Determine datatype from JS field value type; the resolve* options
2105
+ // control storage mode (deterministic vs envelope), not scalar type.
2106
+ // A value stored on the literal language (deterministic or envelope,
2107
+ // i.e. resolveLanguage unset or "literal") gets a string datatype when
2108
+ // no initial value pins a more specific type. A custom resolveLanguage
2109
+ // yields an expression URI, not a literal.
2110
+ //
2111
+ // Skip auto-datatype for properties with a custom `getter` — those
2112
+ // typically return URIs (e.g. `@Optional({ getter: "SELECT ?target ..." })`
2113
+ // that hops through a link to another instance's URI). Autosetting
2114
+ // `sh:datatype xsd:string` there would trip the hydration decode gate
2115
+ // and silently transform `literal:string:<hex>` URIs into their inner
2116
+ // plain-string form on read. Users who want a getter to return literal
2117
+ // values can opt in explicitly by setting `datatype` on the property
2118
+ // options (handled below).
2119
+ if (propMeta.datatype) {
2120
+ // Explicit opt-in from PropertyOptions always wins over inference.
2121
+ propShape.datatype = propMeta.datatype;
1930
2122
  }
1931
- else if (propMeta.initial) {
1932
- const initialType = typeof obj[propName];
1933
- if (initialType === "number") {
1934
- propShape.datatype = "xsd://integer";
1935
- }
1936
- else if (initialType === "boolean") {
1937
- propShape.datatype = "xsd://boolean";
1938
- }
1939
- else if (initialType === "string") {
1940
- propShape.datatype = "xsd://string";
2123
+ else {
2124
+ const isLiteral = propMeta.resolveLanguage === undefined || propMeta.resolveLanguage === "literal";
2125
+ if ((propMeta.initial !== undefined || isLiteral) && !propMeta.getter) {
2126
+ const initialType = typeof obj[propName];
2127
+ if (initialType === "number") {
2128
+ propShape.datatype = "xsd://integer";
2129
+ }
2130
+ else if (initialType === "boolean") {
2131
+ propShape.datatype = "xsd://boolean";
2132
+ }
2133
+ else if (initialType === "string" || isLiteral) {
2134
+ propShape.datatype = "xsd://string";
2135
+ }
1941
2136
  }
1942
2137
  }
1943
2138
  // Cardinality constraints
@@ -2039,8 +2234,19 @@ interpretationHint) {
2039
2234
  name: relName,
2040
2235
  path: synthesizedPath,
2041
2236
  };
2042
- // Relations typically contain IRIs
2043
- relShape.nodeKind = 'IRI';
2237
+ // A relation with a declared `datatype` holds encoded literal
2238
+ // values (e.g. `HasMany<string>` with `datatype: "xsd:string"`).
2239
+ // Everything else is a URI relation pointing at another
2240
+ // instance. The executor uses `sh:datatype` on hydration to
2241
+ // decide whether to decode `literal:<type>:<value>` wire form
2242
+ // (yes for literals, no for URIs).
2243
+ if (relMeta.datatype) {
2244
+ relShape.datatype = relMeta.datatype;
2245
+ relShape.nodeKind = 'Literal';
2246
+ }
2247
+ else {
2248
+ relShape.nodeKind = 'IRI';
2249
+ }
2044
2250
  // Encode relation kind so the executor can derive direction and
2045
2251
  // scalar-vs-collection rendering without consulting the JS class.
2046
2252
  relShape.relationKind = relMeta.kind;
@@ -2055,10 +2261,24 @@ interpretationHint) {
2055
2261
  if (relMeta.filter === false) {
2056
2262
  relShape.filter = false;
2057
2263
  }
2264
+ // Ordering is declared in the type system so the executor can act on it
2265
+ // for every writer, not just this client.
2266
+ if (relMeta.ordering) {
2267
+ relShape.ordering = relMeta.ordering.strategy;
2268
+ }
2058
2269
  // AD4M-specific metadata
2059
2270
  if (relMeta.local !== undefined) {
2060
2271
  relShape.local = relMeta.local;
2061
2272
  }
2273
+ // Per-relation interpretation hint — sentence-level meaning that
2274
+ // steers the harness LLM's `_propose_link_child` `predicate` field
2275
+ // description. Read back on the Rust side by
2276
+ // `ShaclProperty.interpretation_hint` and rendered into the tool
2277
+ // schema alongside the predicate URI enum (so `basedOn` reads
2278
+ // "prior beliefs this intention derives from", not just "some link").
2279
+ if (relMeta.interpretationHint) {
2280
+ relShape.interpretationHint = relMeta.interpretationHint;
2281
+ }
2062
2282
  // Adder / Remover actions — only meaningful for relations backed
2063
2283
  // by a real link predicate. Getter-only relations are read-only.
2064
2284
  if (relMeta.predicate) {
@@ -2195,6 +2415,25 @@ interpretationHint) {
2195
2415
  }
2196
2416
  shape.addProperty(relShape);
2197
2417
  }
2418
+ // ── Ordering links ─────────────────────────────────────────────────
2419
+ // Ordering entries are stored on the *parent*, under one shared predicate,
2420
+ // so that reconstruction needs no extra query: they arrive with the
2421
+ // instance's own links. That only works if the instance query asks for them,
2422
+ // and it builds its predicate filter from the shape's declared paths — so a
2423
+ // class owning any ordered collection has to declare the predicate, or the
2424
+ // very links the ordering depends on are filtered out of the read that needs
2425
+ // them.
2426
+ //
2427
+ // One entry covers every ordered relation on the class; each entry names the
2428
+ // relation it belongs to.
2429
+ const hasOrderedRelation = Object.values(allRelationsMeta).some((m) => m.ordering);
2430
+ if (hasOrderedRelation) {
2431
+ shape.addProperty({
2432
+ name: '_collectionOrder',
2433
+ path: 'ad4m://collection_order',
2434
+ nodeKind: 'IRI',
2435
+ });
2436
+ }
2198
2437
  // Always set constructor and destructor actions on the shape, even
2199
2438
  // when empty. An empty array serialises to `literal:string:[]`
2200
2439
  // which the Rust executor parses as a valid (no-op) command list,
@@ -2464,7 +2703,7 @@ function applyPropertyMetadata(opts) {
2464
2703
  *
2465
2704
  * @description
2466
2705
  * Equivalent to `@Property` but defaults `required` to `false` and does not
2467
- * apply `resolveLanguage` or `initial` defaults. Use this when a property
2706
+ * apply any `initial` defaults. Use this when a property
2468
2707
  * may or may not have a value, and you want full control over its configuration.
2469
2708
  *
2470
2709
  * @example
@@ -2587,8 +2826,7 @@ function Flag(opts) {
2587
2826
  * @Model({ name: "Recipe" })
2588
2827
  * class Recipe extends Ad4mModel {
2589
2828
  * @Property({
2590
- * through: "recipe://name",
2591
- * resolveLanguage: "literal"
2829
+ * through: "recipe://name"
2592
2830
  * })
2593
2831
  * name: string = "";
2594
2832
  *
@@ -2645,7 +2883,9 @@ function Model$1(opts) {
2645
2883
  * Smart defaults (all overridable):
2646
2884
  * - `required` → `false`
2647
2885
  * - `readOnly` → `false`
2648
- * - `resolveLanguage` → `"literal"`
2886
+ * - `resolveLanguage` → unset → deterministic typed literal storage
2887
+ * (the perf default). Set `resolveLanguage: "literal"` for a signed-envelope
2888
+ * value, or a custom language address to resolve through that language.
2649
2889
  * - `initial` → `undefined` (no link created until a value is explicitly set)
2650
2890
  *
2651
2891
  * Properties are optional by default. When a model instance is created without
@@ -2678,7 +2918,8 @@ function Model$1(opts) {
2678
2918
  * })
2679
2919
  * role: string = "";
2680
2920
  *
2681
- * // Optional property with literal resolution
2921
+ * // Optional property with signed-envelope literal storage
2922
+ * // (per-value provenance)
2682
2923
  * @Property({
2683
2924
  * through: "user://bio",
2684
2925
  * resolveLanguage: "literal"
@@ -2691,18 +2932,22 @@ function Model$1(opts) {
2691
2932
  * @param {string} opts.through - The predicate URI for the property
2692
2933
  * @param {boolean} [opts.required=false] - Whether the property is required (adds query filters and sentinel initial value)
2693
2934
  * @param {string} [opts.initial] - Initial value (defaults to "literal:string:uninitialized" when required)
2694
- * @param {string} [opts.resolveLanguage] - Language to use for value resolution (e.g. "literal")
2935
+ * @param {string} [opts.resolveLanguage] - Value-resolution language: unset (deterministic typed literal, the perf default), "literal" (signed envelope), or a custom language address
2695
2936
  * @param {string} [opts.prologGetter] - Custom Prolog code for getting the property value
2696
2937
  * @param {string} [opts.prologSetter] - Custom Prolog code for setting the property value
2697
2938
  * @param {boolean} [opts.local] - Whether the property should only be stored locally
2698
2939
  */
2699
2940
  function Property(opts) {
2700
2941
  const required = opts.required ?? false;
2942
+ // `resolveLanguage` is intentionally NOT defaulted here.
2943
+ // The effective storage mode is derived from what the user explicitly set:
2944
+ // - unset → deterministic typed literal (the perf default)
2945
+ // - "literal" → signed literal envelope (per-value provenance)
2946
+ // - <custom address> → expression on that custom language
2701
2947
  return applyPropertyMetadata({
2702
2948
  ...opts,
2703
2949
  required,
2704
2950
  readOnly: opts.readOnly ?? false,
2705
- resolveLanguage: opts.resolveLanguage ?? "literal",
2706
2951
  initial: opts.initial ?? (required ? "literal:string:uninitialized" : undefined),
2707
2952
  });
2708
2953
  }
@@ -2757,7 +3002,7 @@ function Property(opts) {
2757
3002
  * @param {PropertyOptions} opts - Property configuration
2758
3003
  * @param {string} opts.through - The predicate URI for the property
2759
3004
  * @param {string} [opts.initial] - Initial value (if property should have one)
2760
- * @param {string} [opts.resolveLanguage] - Language to use for value resolution (e.g. "literal")
3005
+ * @param {string} [opts.resolveLanguage] - Value-resolution language: unset (deterministic typed literal, the perf default), "literal" (signed envelope), or a custom language address
2761
3006
  * @param {string} [opts.prologGetter] - Custom Prolog code for getting the property value
2762
3007
  * @param {boolean} [opts.local] - Whether the property should only be stored locally
2763
3008
  */
@@ -2778,35 +3023,57 @@ function resolveRelationArgs(first, second) {
2778
3023
  const opts = typeof first === 'function'
2779
3024
  ? { ...(second || {}), target: first }
2780
3025
  : first;
2781
- // getter is mutually exclusive with through, target, and where
3026
+ // `where` and `filter: false` contradict each other on every relation,
3027
+ // getter-backed ones included — checked before the getter path returns.
3028
+ if (opts.where && opts.filter === false) {
3029
+ throw new Error('Relation decorator: `where` and `filter: false` are contradictory. ' +
3030
+ '`where` adds filtering constraints; `filter: false` disables filtering.');
3031
+ }
3032
+ // getter is mutually exclusive with through
2782
3033
  if (opts.getter) {
2783
3034
  if (opts.through) {
2784
3035
  throw new Error('Relation decorator: `getter` and `through` are mutually exclusive. ' +
2785
3036
  'Use `getter` alone for custom read-only relations, or `through` ' +
2786
3037
  '(with optional `target`) for standard link-based relations.');
2787
3038
  }
2788
- if (opts.target) {
2789
- throw new Error('Relation decorator: `getter` and `target` are mutually exclusive. ' +
2790
- '`target` auto-generates a conformance getter from the model shape; ' +
2791
- 'providing both is contradictory.');
2792
- }
2793
- if (opts.where) {
2794
- throw new Error('Relation decorator: `where` and `getter` are mutually exclusive. ' +
2795
- 'Use `where` for DSL-based filtering, or `getter` for raw getter expression.');
2796
- }
3039
+ // `target` and `where` are NOT mutually exclusive with `getter`.
3040
+ //
3041
+ // `target` does two separable jobs: it auto-derives a conformance
3042
+ // getter, and it names the class the relation's values hydrate into.
3043
+ // Only the first conflicts with an explicit getter, and `buildSHACL`
3044
+ // already resolves that on its own — an explicit getter wins the getter
3045
+ // slot, while `sh:class` / `ad4m:targetClassName` are emitted from
3046
+ // `target` independently.
3047
+ //
3048
+ // Refusing the pair cost the one thing a custom getter is for. A getter
3049
+ // expresses a traversal the link-shaped DSL cannot — most usefully
3050
+ // through a reified edge, where the connection is a record rather than
3051
+ // a predicate:
3052
+ //
3053
+ // @HasMany({
3054
+ // getter: "SELECT ?target WHERE { \
3055
+ // ?citation <paper://cites_from> <Base> . \
3056
+ // ?citation <paper://cites_to> ?target . }",
3057
+ // target: () => Paper,
3058
+ // })
3059
+ // cited: Paper[] = [];
3060
+ //
3061
+ // Without `target` the relation has no target class, so `include` on it
3062
+ // resolves a shape named "" and fails — leaving a traversal that can
3063
+ // only ever return bare URIs. With it, the values hydrate like any other
3064
+ // relation, because getters are evaluated before include resolution.
3065
+ //
3066
+ // `where` is the same story: the executor applies post-getter where
3067
+ // filters specifically to getter-backed relations
3068
+ // (`apply_where_filter_to_relation`), and emitting `wherePredicates`
3069
+ // needs `target` to resolve the target's metadata — so the runtime is
3070
+ // built for all three together and only this check said otherwise.
2797
3071
  return opts;
2798
3072
  }
2799
3073
  // Default predicate when not provided
2800
3074
  if (!opts.through) {
2801
3075
  opts.through = 'ad4m://has_child';
2802
3076
  }
2803
- // where validation
2804
- if (opts.where) {
2805
- if (opts.filter === false) {
2806
- throw new Error('Relation decorator: `where` and `filter: false` are contradictory. ' +
2807
- '`where` adds filtering constraints; `filter: false` disables filtering.');
2808
- }
2809
- }
2810
3077
  return opts;
2811
3078
  }
2812
3079
  function HasMany(first, second) {
@@ -2825,6 +3092,11 @@ function HasMany(first, second) {
2825
3092
  ...(opts.getter && { getter: opts.getter }),
2826
3093
  ...(opts.filter !== undefined && { filter: opts.filter }),
2827
3094
  ...(opts.where && { where: opts.where }),
3095
+ ...(opts.datatype && { datatype: opts.datatype }),
3096
+ ...(opts.polymorphic && { polymorphic: opts.polymorphic }),
3097
+ ...(opts.instantiateAs && { instantiateAs: opts.instantiateAs }),
3098
+ ...(opts.ordering && { ordering: opts.ordering }),
3099
+ ...(opts.interpretationHint && { interpretationHint: opts.interpretationHint }),
2828
3100
  };
2829
3101
  const relKey = key;
2830
3102
  // Only add mutation methods when a predicate is available
@@ -2858,6 +3130,11 @@ function HasOne(first, second) {
2858
3130
  local: opts.local,
2859
3131
  ...(opts.filter !== undefined && { filter: opts.filter }),
2860
3132
  ...(opts.where && { where: opts.where }),
3133
+ ...(opts.datatype && { datatype: opts.datatype }),
3134
+ ...(opts.polymorphic && { polymorphic: opts.polymorphic }),
3135
+ ...(opts.instantiateAs && { instantiateAs: opts.instantiateAs }),
3136
+ ...(opts.ordering && { ordering: opts.ordering }),
3137
+ ...(opts.interpretationHint && { interpretationHint: opts.interpretationHint }),
2861
3138
  };
2862
3139
  const relKey = key;
2863
3140
  if (opts.through) {
@@ -2867,15 +3144,23 @@ function HasOne(first, second) {
2867
3144
  readOnly: false,
2868
3145
  local: opts.local,
2869
3146
  })(target, key);
2870
- // Add prototype methods for add/remove/set (mirroring @HasMany)
2871
- target[`add${capitalize(relKey)}`] = async function (arg) {
2872
- return this.addRelationValue(relKey, arg);
3147
+ // Add prototype methods for add/remove/set (mirroring @HasMany).
3148
+ //
3149
+ // `batchId` is part of that mirroring: without it a to-one link
3150
+ // cannot join a write group, so anything that creates a record and
3151
+ // then points it at something has to commit twice and every
3152
+ // subscriber sees the state in between — a record whose to-one
3153
+ // relation is still empty. Anything rendering from a subscription
3154
+ // therefore has a frame in which the record exists and points at
3155
+ // nothing.
3156
+ target[`add${capitalize(relKey)}`] = async function (arg, batchId) {
3157
+ return this.addRelationValue(relKey, arg, batchId);
2873
3158
  };
2874
- target[`remove${capitalize(relKey)}`] = async function (arg) {
2875
- return this.removeRelationValue(relKey, arg);
3159
+ target[`remove${capitalize(relKey)}`] = async function (arg, batchId) {
3160
+ return this.removeRelationValue(relKey, arg, batchId);
2876
3161
  };
2877
- target[`set${capitalize(relKey)}`] = async function (arg) {
2878
- return this.setRelationValues(relKey, arg);
3162
+ target[`set${capitalize(relKey)}`] = async function (arg, batchId) {
3163
+ return this.setRelationValues(relKey, arg, batchId);
2879
3164
  };
2880
3165
  }
2881
3166
  else {
@@ -2898,6 +3183,11 @@ function BelongsToOne(first, second) {
2898
3183
  local: opts.local,
2899
3184
  ...(opts.filter !== undefined && { filter: opts.filter }),
2900
3185
  ...(opts.where && { where: opts.where }),
3186
+ ...(opts.datatype && { datatype: opts.datatype }),
3187
+ ...(opts.polymorphic && { polymorphic: opts.polymorphic }),
3188
+ ...(opts.instantiateAs && { instantiateAs: opts.instantiateAs }),
3189
+ ...(opts.ordering && { ordering: opts.ordering }),
3190
+ ...(opts.interpretationHint && { interpretationHint: opts.interpretationHint }),
2901
3191
  };
2902
3192
  if (opts.through) {
2903
3193
  // Read-only property (the owning side manages the link)
@@ -2927,6 +3217,11 @@ function BelongsToMany(first, second) {
2927
3217
  ...(opts.getter && { getter: opts.getter }),
2928
3218
  ...(opts.filter !== undefined && { filter: opts.filter }),
2929
3219
  ...(opts.where && { where: opts.where }),
3220
+ ...(opts.datatype && { datatype: opts.datatype }),
3221
+ ...(opts.polymorphic && { polymorphic: opts.polymorphic }),
3222
+ ...(opts.instantiateAs && { instantiateAs: opts.instantiateAs }),
3223
+ ...(opts.ordering && { ordering: opts.ordering }),
3224
+ ...(opts.interpretationHint && { interpretationHint: opts.interpretationHint }),
2930
3225
  };
2931
3226
  // @BelongsToMany is the inverse/read-only side — do NOT generate add*/remove*/set*
2932
3227
  // prototype methods. Mutation must go through the owning side's @HasMany decorator.
@@ -3002,59 +3297,82 @@ function queryCacheSize() {
3002
3297
  return cache.size;
3003
3298
  }
3004
3299
 
3300
+ /**
3301
+ * Runtime shape check for a decoded `ModelQuery`. Deserialization paths use
3302
+ * this to guard against malformed guard arrays leaking into flow metadata
3303
+ * (an untyped `Array.isArray` would happily accept `[null]` or `[{}]`).
3304
+ * Only the mandatory `className: string` field is enforced — richer
3305
+ * validation stays with the runtime engine that will actually execute the
3306
+ * query.
3307
+ */
3308
+ function isModelQueryShape(v) {
3309
+ if (typeof v !== "object" ||
3310
+ v === null ||
3311
+ typeof v.className !== "string" ||
3312
+ v.className.length === 0) {
3313
+ return false;
3314
+ }
3315
+ const or = v.or;
3316
+ if (or !== undefined) {
3317
+ if (!Array.isArray(or) || !or.every(isModelQueryShape))
3318
+ return false;
3319
+ }
3320
+ return true;
3321
+ }
3322
+ /**
3323
+ * Runtime shape check for a decoded `ConsensusRule`. Enforces the one
3324
+ * mandatory field (`n: number` with a sane range) and, when `fromRole`
3325
+ * is present, that it's a valid ModelQuery. A malformed literal (e.g.
3326
+ * `{ n: "many" }` or `{ n: 1, fromRole: null }`) leaves the field unset
3327
+ * rather than becoming corrupt flow metadata that downstream engines
3328
+ * would trip over.
3329
+ */
3330
+ function isConsensusRuleShape(v) {
3331
+ if (typeof v !== "object" || v === null)
3332
+ return false;
3333
+ const n = v.n;
3334
+ if (typeof n !== "number" || !Number.isFinite(n) || n < 1 || !Number.isInteger(n)) {
3335
+ return false;
3336
+ }
3337
+ const fromRole = v.fromRole;
3338
+ if (fromRole !== undefined && !isModelQueryShape(fromRole))
3339
+ return false;
3340
+ return true;
3341
+ }
3005
3342
  /**
3006
3343
  * SHACL Flow - represents a state machine for AD4M expressions
3007
3344
  *
3008
3345
  * Flows define:
3009
- * - Which expressions can enter the flow (flowable condition)
3010
- * - What states exist and how to detect them (via link patterns)
3011
- * - How to transition between states (via actions)
3346
+ * - Which expressions can enter the flow (via `inputTypes`)
3347
+ * - What states exist and their per-state guards (via `requires`)
3348
+ * - How to transition between states (via transitions + consensus rules)
3349
+ *
3350
+ * State lives on the on-graph `FlowInstanceRecord.currentState` and is
3351
+ * read/written through the `FlowInstance` wrapper class
3352
+ * ({@link FlowInstance.start} / {@link FlowInstance.findAll}) — see design
3353
+ * doc §4.3/§5.
3012
3354
  *
3013
3355
  * @example
3014
3356
  * ```typescript
3015
3357
  * const todoFlow = new SHACLFlow('todo://TODO', 'todo://');
3016
3358
  *
3017
3359
  * // Any expression can become a TODO
3018
- * todoFlow.flowable = 'any';
3019
- *
3020
- * // Define states
3021
- * todoFlow.addState({
3022
- * name: 'ready',
3023
- * value: 0,
3024
- * stateCheck: { predicate: 'todo://state', target: 'todo://ready' }
3025
- * });
3026
- * todoFlow.addState({
3027
- * name: 'doing',
3028
- * value: 0.5,
3029
- * stateCheck: { predicate: 'todo://state', target: 'todo://doing' }
3030
- * });
3031
- * todoFlow.addState({
3032
- * name: 'done',
3033
- * value: 1,
3034
- * stateCheck: { predicate: 'todo://state', target: 'todo://done' }
3035
- * });
3360
+ * todoFlow.inputTypes = ['any'];
3036
3361
  *
3037
- * // Define start action
3038
- * todoFlow.startAction = [{
3039
- * action: 'addLink',
3040
- * source: 'this',
3041
- * predicate: 'todo://state',
3042
- * target: 'todo://ready'
3043
- * }];
3362
+ * todoFlow.addState({ name: 'ready', value: 0 });
3363
+ * todoFlow.addState({ name: 'doing', value: 0.5 });
3364
+ * todoFlow.addState({ name: 'done', value: 1 });
3044
3365
  *
3045
- * // Define transitions
3046
3366
  * todoFlow.addTransition({
3047
3367
  * actionName: 'Start',
3048
3368
  * fromState: 'ready',
3049
3369
  * toState: 'doing',
3050
- * actions: [
3051
- * { action: 'addLink', source: 'this', predicate: 'todo://state', target: 'todo://doing' },
3052
- * { action: 'removeLink', source: 'this', predicate: 'todo://state', target: 'todo://ready' }
3053
- * ]
3370
+ * actions: [],
3054
3371
  * });
3055
3372
  *
3056
- * // Store in perspective
3373
+ * // Register on the perspective and mint an instance on a subject.
3057
3374
  * await perspective.addFlow('TODO', todoFlow);
3375
+ * const instance = await FlowInstance.start(perspective, 'TODO', 'expr://123');
3058
3376
  * ```
3059
3377
  */
3060
3378
  class SHACLFlow {
@@ -3064,11 +3382,41 @@ class SHACLFlow {
3064
3382
  * @param namespace - Namespace for URIs (e.g., "todo://")
3065
3383
  */
3066
3384
  constructor(name, namespace) {
3067
- /** Condition for which expressions can start this flow */
3068
- this.flowable = "any";
3069
- /** Actions to execute when starting the flow */
3070
- this.startAction = [];
3071
- /** States in this flow */
3385
+ /**
3386
+ * Subject-class URIs the flow accepts as its base expression.
3387
+ *
3388
+ * Design doc §4.1: a flow's *typed input*. When an
3389
+ * expression whose class matches any URI in this array enters scope,
3390
+ * the flow-spawn engine considers it a candidate base. Superseded
3391
+ * the older link-level `flowable: LinkPattern` primitive — model-level
3392
+ * matching by subject class instead of link matching. Empty array =
3393
+ * flow declares no typed input. The `"any"` sentinel is accepted as
3394
+ * a wildcard for tests and legacy flows.
3395
+ */
3396
+ this.inputTypes = [];
3397
+ /**
3398
+ * Subject-class URIs the flow must produce (linked to the base) for a
3399
+ * run to count as complete.
3400
+ *
3401
+ * Design doc §4.1: a flow's *typed output*. Two jobs:
3402
+ * (a) documentation for stateful flows — records what a completed run
3403
+ * leaves in the graph; (b) **terminal condition** for zero-state flows —
3404
+ * a flow with no `FlowState`s completes when at least one instance of
3405
+ * each `outputTypes` entry exists in scope and is linked to the base,
3406
+ * and `consensusRule` fires. This is what makes "Like" a first-class
3407
+ * flow with no state machine.
3408
+ */
3409
+ this.outputTypes = [];
3410
+ /**
3411
+ * States in this flow.
3412
+ *
3413
+ * **Ordering convention (James PR #929 R9):** the array is stored sorted
3414
+ * ascending by `value`. `states[0]` is the initial state — the one
3415
+ * {@link FlowInstance.start} mints a fresh instance into. A flow author
3416
+ * who wants a specific state as the entry point must give it the lowest
3417
+ * `value` in the set. `fromLinks` enforces this sort, so link-order on
3418
+ * the graph never dictates the initial state.
3419
+ */
3072
3420
  this._states = [];
3073
3421
  /** Transitions between states */
3074
3422
  this._transitions = [];
@@ -3136,27 +3484,63 @@ class SHACLFlow {
3136
3484
  predicate: "ad4m://flowName",
3137
3485
  target: Literal.from(this.name).toUrl()
3138
3486
  });
3139
- // Flowable condition
3140
- if (this.flowable === "any") {
3487
+ // Top-level interpretation hint (optional, drives AI state suggestion).
3488
+ // Empty strings are treated as "unset" so a round-trip through the graph
3489
+ // doesn't materialise an empty-hint predicate that consumers would then
3490
+ // read back as a meaningful value.
3491
+ if (this.interpretationHint) {
3141
3492
  links.push({
3142
3493
  source: flowUri,
3143
- predicate: "ad4m://flowable",
3144
- target: "ad4m://any"
3494
+ predicate: "ad4m://interpretationHint",
3495
+ target: Literal.from(this.interpretationHint).toUrl()
3145
3496
  });
3146
3497
  }
3147
- else {
3498
+ // Typed I/O (flow-level, design §4.1). Both arrays are only
3499
+ // serialized when non-empty — an empty list is indistinguishable
3500
+ // from "unset" for a round-trip, and emitting one would give
3501
+ // downstream consumers a meaningless predicate to interpret.
3502
+ if (this.inputTypes.length > 0) {
3503
+ links.push({
3504
+ source: flowUri,
3505
+ predicate: "ad4m://inputTypes",
3506
+ target: `literal:string:${encodeURIComponent(JSON.stringify(this.inputTypes))}`
3507
+ });
3508
+ }
3509
+ if (this.outputTypes.length > 0) {
3510
+ links.push({
3511
+ source: flowUri,
3512
+ predicate: "ad4m://outputTypes",
3513
+ target: `literal:string:${encodeURIComponent(JSON.stringify(this.outputTypes))}`
3514
+ });
3515
+ }
3516
+ // Flow-level `creationHint` — same empty-string-is-unset guard as
3517
+ // `interpretationHint`, same reason (round-trip fidelity).
3518
+ if (this.creationHint) {
3519
+ links.push({
3520
+ source: flowUri,
3521
+ predicate: "ad4m://creationHint",
3522
+ target: Literal.from(this.creationHint).toUrl()
3523
+ });
3524
+ }
3525
+ // Flow-level `context` — background queries the LLM sees but not
3526
+ // guard evidence. Single JSON literal, consumers parse back.
3527
+ if (this.context && this.context.length > 0) {
3148
3528
  links.push({
3149
3529
  source: flowUri,
3150
- predicate: "ad4m://flowable",
3151
- target: `literal:string:${encodeURIComponent(JSON.stringify(this.flowable))}`
3530
+ predicate: "ad4m://context",
3531
+ target: `literal:string:${encodeURIComponent(JSON.stringify(this.context))}`
3152
3532
  });
3153
3533
  }
3154
- // Start action
3155
- if (this.startAction.length > 0) {
3534
+ // Flow-level `consensusRule` — default for state transitions when a
3535
+ // FlowState omits its own rule; also the terminal-firing rule for
3536
+ // zero-state flows. Serialized as one JSON literal (the shape is
3537
+ // fixed and cheap to parse; consistent with `context` / `requires`
3538
+ // so consumers only need one parser).
3539
+ if (this.consensusRule) {
3156
3540
  links.push({
3157
3541
  source: flowUri,
3158
- predicate: "ad4m://startAction",
3159
- target: `literal:string:${encodeURIComponent(JSON.stringify(this.startAction))}`
3542
+ predicate: "ad4m://consensusRule",
3543
+ target: `literal:string:${encodeURIComponent(JSON.stringify(this.consensusRule))}`
3160
3544
  });
3161
3545
  }
3162
3546
  // States
@@ -3186,12 +3570,45 @@ class SHACLFlow {
3186
3570
  predicate: "ad4m://stateValue",
3187
3571
  target: Literal.from(state.value).toUrl()
3188
3572
  });
3189
- // State check pattern
3190
- links.push({
3191
- source: stateUri,
3192
- predicate: "ad4m://stateCheck",
3193
- target: `literal:string:${encodeURIComponent(JSON.stringify(state.stateCheck))}`
3194
- });
3573
+ // Per-state interpretation hint (optional, drives AI state suggestion).
3574
+ // Empty strings treated as unset — same rationale as the flow-level hint.
3575
+ if (state.interpretationHint) {
3576
+ links.push({
3577
+ source: stateUri,
3578
+ predicate: "ad4m://interpretationHint",
3579
+ target: Literal.from(state.interpretationHint).toUrl()
3580
+ });
3581
+ }
3582
+ // Per-state `requires` guard — array of ModelQueries, AND-combined.
3583
+ // Serialized as one JSON string on `ad4m://requires`. Consumers
3584
+ // (state-transition engine, `flow.availableActions`) parse back.
3585
+ if (state.requires && state.requires.length > 0) {
3586
+ links.push({
3587
+ source: stateUri,
3588
+ predicate: "ad4m://requires",
3589
+ target: `literal:string:${encodeURIComponent(JSON.stringify(state.requires))}`
3590
+ });
3591
+ }
3592
+ // Per-state `semanticCheck` hint — optional English confirmation
3593
+ // that runs after `requires` matches, for states where structural
3594
+ // presence isn't sufficient evidence. Empty string = unset.
3595
+ if (state.semanticCheck) {
3596
+ links.push({
3597
+ source: stateUri,
3598
+ predicate: "ad4m://semanticCheck",
3599
+ target: Literal.from(state.semanticCheck).toUrl()
3600
+ });
3601
+ }
3602
+ // Per-state `consensusRule` override — one JSON literal on the
3603
+ // state, same predicate name as the flow-level rule but scoped by
3604
+ // source URI so the reader can tell them apart.
3605
+ if (state.consensusRule) {
3606
+ links.push({
3607
+ source: stateUri,
3608
+ predicate: "ad4m://consensusRule",
3609
+ target: `literal:string:${encodeURIComponent(JSON.stringify(state.consensusRule))}`
3610
+ });
3611
+ }
3195
3612
  }
3196
3613
  // Transitions
3197
3614
  for (const transition of this._transitions) {
@@ -3256,31 +3673,96 @@ class SHACLFlow {
3256
3673
  const namespace = withoutSuffix.slice(0, lastSlashOrColon + 1);
3257
3674
  const name = withoutSuffix.slice(lastSlashOrColon + 1);
3258
3675
  const flow = new SHACLFlow(name, namespace);
3259
- // Find flowable condition
3260
- const flowableLink = links.find(l => l.source === flowUri && l.predicate === "ad4m://flowable");
3261
- if (flowableLink) {
3262
- if (flowableLink.target === "ad4m://any") {
3263
- flow.flowable = "any";
3676
+ // Find top-level interpretation hint. Only accept a decoded value that
3677
+ // is a non-empty string — malformed literals (Literal.get() can return
3678
+ // an object, number, etc.) leave the field unset rather than becoming
3679
+ // corrupt flow metadata.
3680
+ const flowHintLink = links.find(l => l.source === flowUri && l.predicate === "ad4m://interpretationHint");
3681
+ if (flowHintLink) {
3682
+ try {
3683
+ const decoded = Literal.fromUrl(flowHintLink.target).get();
3684
+ if (typeof decoded === "string" && decoded.length > 0) {
3685
+ flow.interpretationHint = decoded;
3686
+ }
3264
3687
  }
3265
- else {
3266
- try {
3267
- const jsonStr = flowableLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
3268
- flow.flowable = JSON.parse(decodeURIComponent(jsonStr));
3688
+ catch {
3689
+ // Ignore parse errors — leave unset.
3690
+ }
3691
+ }
3692
+ // Find typed I/O (flow-level, design §4.1). Both arrays validated
3693
+ // element-wise — only accept string[] payloads. A malformed literal
3694
+ // (`[null]`, `[42]`, non-array) leaves the field as its default
3695
+ // empty array rather than corrupting flow metadata.
3696
+ const inputTypesLink = links.find(l => l.source === flowUri && l.predicate === "ad4m://inputTypes");
3697
+ if (inputTypesLink) {
3698
+ try {
3699
+ const jsonStr = inputTypesLink.target.replace(/^literal:\/\/string:|^literal:string:/, "");
3700
+ const parsed = JSON.parse(decodeURIComponent(jsonStr));
3701
+ if (Array.isArray(parsed) && parsed.every(v => typeof v === "string" && v.length > 0)) {
3702
+ flow.inputTypes = parsed;
3269
3703
  }
3270
- catch {
3271
- flow.flowable = "any";
3704
+ }
3705
+ catch {
3706
+ // Ignore parse errors — leave as default empty array.
3707
+ }
3708
+ }
3709
+ const outputTypesLink = links.find(l => l.source === flowUri && l.predicate === "ad4m://outputTypes");
3710
+ if (outputTypesLink) {
3711
+ try {
3712
+ const jsonStr = outputTypesLink.target.replace(/^literal:\/\/string:|^literal:string:/, "");
3713
+ const parsed = JSON.parse(decodeURIComponent(jsonStr));
3714
+ if (Array.isArray(parsed) && parsed.every(v => typeof v === "string" && v.length > 0)) {
3715
+ flow.outputTypes = parsed;
3272
3716
  }
3273
3717
  }
3718
+ catch {
3719
+ // Ignore parse errors — leave as default empty array.
3720
+ }
3274
3721
  }
3275
- // Find start action
3276
- const startActionLink = links.find(l => l.source === flowUri && l.predicate === "ad4m://startAction");
3277
- if (startActionLink) {
3722
+ // Find flow-level `creationHint`. Non-empty-string guard — same
3723
+ // rationale as `interpretationHint`.
3724
+ const creationHintLink = links.find(l => l.source === flowUri && l.predicate === "ad4m://creationHint");
3725
+ if (creationHintLink) {
3278
3726
  try {
3279
- const jsonStr = startActionLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
3280
- flow.startAction = JSON.parse(decodeURIComponent(jsonStr));
3727
+ const decoded = Literal.fromUrl(creationHintLink.target).get();
3728
+ if (typeof decoded === "string" && decoded.length > 0) {
3729
+ flow.creationHint = decoded;
3730
+ }
3281
3731
  }
3282
3732
  catch {
3283
- // Ignore parse errors
3733
+ // Ignore parse errors — leave unset.
3734
+ }
3735
+ }
3736
+ // Find flow-level `context` — same ModelQuery-shape guard as
3737
+ // FlowState.requires (rejects `[null]`, `[{}]`, non-string
3738
+ // `className`).
3739
+ const contextLink = links.find(l => l.source === flowUri && l.predicate === "ad4m://context");
3740
+ if (contextLink) {
3741
+ try {
3742
+ const jsonStr = contextLink.target.replace(/^literal:\/\/string:|^literal:string:/, "");
3743
+ const parsed = JSON.parse(decodeURIComponent(jsonStr));
3744
+ if (Array.isArray(parsed) && parsed.every(isModelQueryShape)) {
3745
+ flow.context = parsed;
3746
+ }
3747
+ }
3748
+ catch {
3749
+ // Ignore parse errors — leave unset.
3750
+ }
3751
+ }
3752
+ // Find flow-level `consensusRule`. Reject malformed literals
3753
+ // (missing `n`, non-integer `n`, invalid `fromRole`) so the runtime
3754
+ // engine never has to defensively re-validate a stored rule.
3755
+ const consensusRuleLink = links.find(l => l.source === flowUri && l.predicate === "ad4m://consensusRule");
3756
+ if (consensusRuleLink) {
3757
+ try {
3758
+ const jsonStr = consensusRuleLink.target.replace(/^literal:\/\/string:|^literal:string:/, "");
3759
+ const parsed = JSON.parse(decodeURIComponent(jsonStr));
3760
+ if (isConsensusRuleShape(parsed)) {
3761
+ flow.consensusRule = parsed;
3762
+ }
3763
+ }
3764
+ catch {
3765
+ // Ignore parse errors — leave unset.
3284
3766
  }
3285
3767
  }
3286
3768
  // Find states
@@ -3297,20 +3779,85 @@ class SHACLFlow {
3297
3779
  // Get state value
3298
3780
  const valueLink = links.find(l => l.source === stateUri && l.predicate === "ad4m://stateValue");
3299
3781
  const stateValue = valueLink ? Literal.fromUrl(valueLink.target).get() : 0;
3300
- // Get state check
3301
- const checkLink = links.find(l => l.source === stateUri && l.predicate === "ad4m://stateCheck");
3302
- let stateCheck = { predicate: "", target: "" };
3303
- if (checkLink) {
3782
+ // Get per-state interpretation hint (optional). Same non-empty-string
3783
+ // guard as the flow-level hint.
3784
+ const hintLink = links.find(l => l.source === stateUri && l.predicate === "ad4m://interpretationHint");
3785
+ let interpretationHint;
3786
+ if (hintLink) {
3304
3787
  try {
3305
- const jsonStr = checkLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
3306
- stateCheck = JSON.parse(decodeURIComponent(jsonStr));
3788
+ const decoded = Literal.fromUrl(hintLink.target).get();
3789
+ if (typeof decoded === "string" && decoded.length > 0) {
3790
+ interpretationHint = decoded;
3791
+ }
3307
3792
  }
3308
3793
  catch {
3309
- // Ignore parse errors
3794
+ // Ignore parse errors — leave unset.
3795
+ }
3796
+ }
3797
+ // Get per-state `requires` guard (optional) — one link carrying a
3798
+ // JSON-encoded ModelQuery[]. Reject arrays whose entries are not
3799
+ // ModelQuery-shaped (missing/non-string `className`, `null`, primitives).
3800
+ const requiresLink = links.find(l => l.source === stateUri && l.predicate === "ad4m://requires");
3801
+ let requires;
3802
+ if (requiresLink) {
3803
+ try {
3804
+ const jsonStr = requiresLink.target.replace(/^literal:\/\/string:|^literal:string:/, "");
3805
+ const parsed = JSON.parse(decodeURIComponent(jsonStr));
3806
+ if (Array.isArray(parsed) && parsed.every(isModelQueryShape)) {
3807
+ requires = parsed;
3808
+ }
3809
+ }
3810
+ catch {
3811
+ // Ignore parse errors — leave requires unset rather than crash
3310
3812
  }
3311
3813
  }
3312
- flow.addState({ name: stateName, value: stateValue, stateCheck });
3814
+ // Get per-state `semanticCheck` hint (optional). Non-empty-string guard.
3815
+ const semanticCheckLink = links.find(l => l.source === stateUri && l.predicate === "ad4m://semanticCheck");
3816
+ let semanticCheck;
3817
+ if (semanticCheckLink) {
3818
+ try {
3819
+ const decoded = Literal.fromUrl(semanticCheckLink.target).get();
3820
+ if (typeof decoded === "string" && decoded.length > 0) {
3821
+ semanticCheck = decoded;
3822
+ }
3823
+ }
3824
+ catch {
3825
+ // Ignore parse errors — leave unset.
3826
+ }
3827
+ }
3828
+ // Get per-state `consensusRule` override (optional). Same shape
3829
+ // guard as the flow-level rule; a malformed literal (missing `n`,
3830
+ // non-integer, invalid `fromRole`) leaves the field unset.
3831
+ const stateConsensusLink = links.find(l => l.source === stateUri && l.predicate === "ad4m://consensusRule");
3832
+ let consensusRule;
3833
+ if (stateConsensusLink) {
3834
+ try {
3835
+ const jsonStr = stateConsensusLink.target.replace(/^literal:\/\/string:|^literal:string:/, "");
3836
+ const parsed = JSON.parse(decodeURIComponent(jsonStr));
3837
+ if (isConsensusRuleShape(parsed)) {
3838
+ consensusRule = parsed;
3839
+ }
3840
+ }
3841
+ catch {
3842
+ // Ignore parse errors — leave unset.
3843
+ }
3844
+ }
3845
+ flow.addState({
3846
+ name: stateName,
3847
+ value: stateValue,
3848
+ ...(interpretationHint !== undefined ? { interpretationHint } : {}),
3849
+ ...(requires !== undefined ? { requires } : {}),
3850
+ ...(semanticCheck !== undefined ? { semanticCheck } : {}),
3851
+ ...(consensusRule !== undefined ? { consensusRule } : {}),
3852
+ });
3313
3853
  }
3854
+ // Perspective link storage does not preserve insertion order — `hasState`
3855
+ // links come back in arbitrary order from the graph, so `flow.states[0]`
3856
+ // was randomly one of the round-tripped states. Sort by `value` ascending
3857
+ // so the "initial state = states[0]" convention (used by
3858
+ // `FlowInstance.start`) survives a fromGraph round trip.
3859
+ // The `states` getter returns a defensive copy, so mutate `_states` directly.
3860
+ flow._states.sort((a, b) => a.value - b.value);
3314
3861
  // Find transitions
3315
3862
  const transitionLinks = links.filter(l => l.source === flowUri && l.predicate === "ad4m://hasTransition");
3316
3863
  for (const transitionLink of transitionLinks) {
@@ -3346,13 +3893,31 @@ class SHACLFlow {
3346
3893
  * Convert to JSON representation
3347
3894
  */
3348
3895
  toJSON() {
3896
+ // Per-state metadata is optional; strip empty strings / empty arrays so
3897
+ // json.states[i] agrees with what toLinks() would materialise (a state
3898
+ // constructed with `interpretationHint: ""` produces no predicate, so
3899
+ // JSON must not carry the empty field either).
3900
+ const sanitizedStates = this._states.map(s => ({
3901
+ name: s.name,
3902
+ value: s.value,
3903
+ ...(s.interpretationHint ? { interpretationHint: s.interpretationHint } : {}),
3904
+ ...(s.requires && s.requires.length > 0 ? { requires: s.requires } : {}),
3905
+ ...(s.semanticCheck ? { semanticCheck: s.semanticCheck } : {}),
3906
+ ...(s.consensusRule ? { consensusRule: s.consensusRule } : {})
3907
+ }));
3349
3908
  return {
3350
3909
  name: this.name,
3351
3910
  namespace: this.namespace,
3352
- flowable: this.flowable,
3353
- startAction: this.startAction,
3354
- states: this._states,
3355
- transitions: this._transitions
3911
+ states: sanitizedStates,
3912
+ transitions: this._transitions,
3913
+ // Empty strings / empty arrays treated as unset — same semantics
3914
+ // as the toLinks path, so JSON <-> links round-trips agree.
3915
+ ...(this.interpretationHint ? { interpretationHint: this.interpretationHint } : {}),
3916
+ ...(this.inputTypes.length > 0 ? { inputTypes: this.inputTypes } : {}),
3917
+ ...(this.outputTypes.length > 0 ? { outputTypes: this.outputTypes } : {}),
3918
+ ...(this.creationHint ? { creationHint: this.creationHint } : {}),
3919
+ ...(this.context && this.context.length > 0 ? { context: this.context } : {}),
3920
+ ...(this.consensusRule ? { consensusRule: this.consensusRule } : {})
3356
3921
  };
3357
3922
  }
3358
3923
  /**
@@ -3360,10 +3925,49 @@ class SHACLFlow {
3360
3925
  */
3361
3926
  static fromJSON(json) {
3362
3927
  const flow = new SHACLFlow(json.name, json.namespace);
3363
- flow.flowable = json.flowable || "any";
3364
- flow.startAction = json.startAction || [];
3928
+ // Non-empty-string guard — mirrors the toLinks-side reader.
3929
+ if (typeof json.interpretationHint === "string" && json.interpretationHint.length > 0) {
3930
+ flow.interpretationHint = json.interpretationHint;
3931
+ }
3932
+ // Typed I/O (design §4.1). Same string[]/ModelQuery[] shape guards
3933
+ // as the fromLinks path — malformed payloads leave defaults untouched.
3934
+ if (Array.isArray(json.inputTypes) &&
3935
+ json.inputTypes.every((v) => typeof v === "string" && v.length > 0)) {
3936
+ flow.inputTypes = json.inputTypes;
3937
+ }
3938
+ if (Array.isArray(json.outputTypes) &&
3939
+ json.outputTypes.every((v) => typeof v === "string" && v.length > 0)) {
3940
+ flow.outputTypes = json.outputTypes;
3941
+ }
3942
+ if (typeof json.creationHint === "string" && json.creationHint.length > 0) {
3943
+ flow.creationHint = json.creationHint;
3944
+ }
3945
+ if (Array.isArray(json.context) && json.context.every(isModelQueryShape)) {
3946
+ flow.context = json.context;
3947
+ }
3948
+ if (isConsensusRuleShape(json.consensusRule)) {
3949
+ flow.consensusRule = json.consensusRule;
3950
+ }
3365
3951
  for (const state of json.states || []) {
3366
- flow.addState(state);
3952
+ // Same validation as the toLinks path: reject malformed optional fields
3953
+ // rather than let them poison downstream consumers.
3954
+ const sanitized = {
3955
+ name: state.name,
3956
+ value: state.value,
3957
+ };
3958
+ if (typeof state.interpretationHint === "string" && state.interpretationHint.length > 0) {
3959
+ sanitized.interpretationHint = state.interpretationHint;
3960
+ }
3961
+ if (Array.isArray(state.requires) && state.requires.every(isModelQueryShape)) {
3962
+ sanitized.requires = state.requires;
3963
+ }
3964
+ if (typeof state.semanticCheck === "string" && state.semanticCheck.length > 0) {
3965
+ sanitized.semanticCheck = state.semanticCheck;
3966
+ }
3967
+ if (isConsensusRuleShape(state.consensusRule)) {
3968
+ sanitized.consensusRule = state.consensusRule;
3969
+ }
3970
+ flow.addState(sanitized);
3367
3971
  }
3368
3972
  for (const transition of json.transitions || []) {
3369
3973
  flow.addTransition(transition);
@@ -3383,7 +3987,7 @@ var __classPrivateFieldGet$a = (undefined && undefined.__classPrivateFieldGet) |
3383
3987
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
3384
3988
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
3385
3989
  };
3386
- var _QuerySubscriptionProxy_instances, _QuerySubscriptionProxy_uuid, _QuerySubscriptionProxy_subscriptionId, _QuerySubscriptionProxy_client, _QuerySubscriptionProxy_callbacks, _QuerySubscriptionProxy_keepaliveTimer, _QuerySubscriptionProxy_unsubscribe, _QuerySubscriptionProxy_latestResult, _QuerySubscriptionProxy_disposed, _QuerySubscriptionProxy_initialized, _QuerySubscriptionProxy_initResolve, _QuerySubscriptionProxy_initReject, _QuerySubscriptionProxy_initTimeoutId, _QuerySubscriptionProxy_query, _QuerySubscriptionProxy_notifyCallbacks, _PerspectiveProxy_handle, _PerspectiveProxy_client, _PerspectiveProxy_perspectiveLinkAddedCallbacks, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, _PerspectiveProxy_perspectiveSyncStateChangeCallbacks, _PerspectiveProxy_ensuredSubjectClasses;
3990
+ var _QuerySubscriptionProxy_instances, _QuerySubscriptionProxy_uuid, _QuerySubscriptionProxy_subscriptionId, _QuerySubscriptionProxy_client, _QuerySubscriptionProxy_callbacks, _QuerySubscriptionProxy_keepaliveTimer, _QuerySubscriptionProxy_unsubscribe, _QuerySubscriptionProxy_reconnectUnsub, _QuerySubscriptionProxy_latestResult, _QuerySubscriptionProxy_disposed, _QuerySubscriptionProxy_initialized, _QuerySubscriptionProxy_initResolve, _QuerySubscriptionProxy_initReject, _QuerySubscriptionProxy_initTimeoutId, _QuerySubscriptionProxy_query, _QuerySubscriptionProxy_generation, _QuerySubscriptionProxy_deliverResult, _QuerySubscriptionProxy_startKeepalive, _QuerySubscriptionProxy_notifyCallbacks, _PerspectiveProxy_handle, _PerspectiveProxy_client, _PerspectiveProxy_perspectiveLinkAddedCallbacks, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, _PerspectiveProxy_perspectiveSyncStateChangeCallbacks, _PerspectiveProxy_ensuredSubjectClasses;
3387
3991
  /** Extract namespace prefix from a URI (everything up to and including the last / or #) */
3388
3992
  function extractNamespaceFromUri(uri) {
3389
3993
  const hashIdx = uri.lastIndexOf('#');
@@ -3444,6 +4048,7 @@ class QuerySubscriptionProxy {
3444
4048
  _QuerySubscriptionProxy_callbacks.set(this, void 0);
3445
4049
  _QuerySubscriptionProxy_keepaliveTimer.set(this, void 0);
3446
4050
  _QuerySubscriptionProxy_unsubscribe.set(this, void 0);
4051
+ _QuerySubscriptionProxy_reconnectUnsub.set(this, void 0);
3447
4052
  _QuerySubscriptionProxy_latestResult.set(this, void 0);
3448
4053
  _QuerySubscriptionProxy_disposed.set(this, false);
3449
4054
  _QuerySubscriptionProxy_initialized.set(this, void 0);
@@ -3451,6 +4056,15 @@ class QuerySubscriptionProxy {
3451
4056
  _QuerySubscriptionProxy_initReject.set(this, void 0);
3452
4057
  _QuerySubscriptionProxy_initTimeoutId.set(this, void 0);
3453
4058
  _QuerySubscriptionProxy_query.set(this, void 0);
4059
+ // Monotonic token guarding the three concurrent writers of
4060
+ // `#unsubscribe`/`#subscriptionId` (full subscribe() from the keepalive
4061
+ // and init-timeout retry paths, and the reconnect swap handler). Each
4062
+ // writer bumps it on entry and re-checks after every await; a mismatch
4063
+ // means a newer writer took over while we were suspended, so the stale
4064
+ // continuation must back out instead of clobbering the newer state
4065
+ // (worst case otherwise: an overwritten-but-never-called unsubscribe
4066
+ // leaks its callback in ApiClient._wsCallbacks for the client lifetime).
4067
+ _QuerySubscriptionProxy_generation.set(this, 0);
3454
4068
  __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_uuid, uuid, "f");
3455
4069
  __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_query, query, "f");
3456
4070
  __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_client, client, "f");
@@ -3463,6 +4077,26 @@ class QuerySubscriptionProxy {
3463
4077
  }), "f");
3464
4078
  }
3465
4079
  async subscribe() {
4080
+ var _a;
4081
+ // Invalidate any suspended writer (older subscribe() or reconnect
4082
+ // swap parked on an await) — see #generation.
4083
+ const generation = __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_generation, (_a = __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_generation, "f"), ++_a), "f");
4084
+ // Remove any prior reconnect listener FIRST — before we touch
4085
+ // `#unsubscribe`. Rationale: `#unsubscribe()` calls into
4086
+ // `ApiClient.subscribe()`'s deleter, which closes the WebSocket
4087
+ // whenever this query owned the last `_wsCallbacks` entry (and no
4088
+ // RPCs are pending). The subsequent `subscribeQuery()` below then
4089
+ // re-opens a fresh socket, and that fresh `onopen` fires the
4090
+ // reconnect callback set. If the OLD reconnect listener is still
4091
+ // in that set, it re-enters this method, closes the socket again,
4092
+ // reopens again … an endless resubscribe loop. Clearing the
4093
+ // listener up-front breaks the cycle; a fresh listener is
4094
+ // installed at the end of a successful subscribe(), and a
4095
+ // full-retry recovery listener in the catch block on failure.
4096
+ if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_reconnectUnsub, "f")) {
4097
+ __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_reconnectUnsub, "f").call(this);
4098
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_reconnectUnsub, undefined, "f");
4099
+ }
3466
4100
  // Clean up previous subscription attempt if retrying
3467
4101
  if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_unsubscribe, "f")) {
3468
4102
  __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_unsubscribe, "f").call(this);
@@ -3482,19 +4116,22 @@ class QuerySubscriptionProxy {
3482
4116
  // Initialize the query subscription
3483
4117
  let initialResult;
3484
4118
  initialResult = await __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, "f").subscribeQuery(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_query, "f"));
4119
+ // A newer writer (another subscribe() or a reconnect swap) took
4120
+ // over while we awaited — back out without touching shared state,
4121
+ // and release the now-orphaned server-side subscription so it
4122
+ // doesn't linger until its keepalive TTL expires.
4123
+ if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_disposed, "f") || __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_generation, "f") !== generation) {
4124
+ __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, "f").disposeQuerySubscription(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_uuid, "f"), initialResult.subscriptionId)
4125
+ .catch(e => console.error('Error disposing superseded query subscription:', e));
4126
+ return;
4127
+ }
3485
4128
  __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_subscriptionId, initialResult.subscriptionId, "f");
3486
4129
  // Process the initial result immediately for fast UX.
3487
4130
  // The subscribeQuery() RPC call already returns the initial result,
3488
4131
  // so treat that as successful initialization instead of waiting for a
3489
4132
  // follow-up WebSocket update that may never arrive until the query changes.
3490
4133
  if (initialResult.result !== undefined) {
3491
- __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_latestResult, initialResult.result, "f");
3492
- __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_instances, "m", _QuerySubscriptionProxy_notifyCallbacks).call(this, initialResult.result);
3493
- if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initResolve, "f")) {
3494
- __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initResolve, "f").call(this, true);
3495
- __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initResolve, undefined, "f");
3496
- __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initReject, undefined, "f");
3497
- }
4134
+ __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_instances, "m", _QuerySubscriptionProxy_deliverResult).call(this, initialResult.result);
3498
4135
  }
3499
4136
  else {
3500
4137
  console.warn('⚠️ No initial result returned from subscribeQuery!');
@@ -3509,21 +4146,7 @@ class QuerySubscriptionProxy {
3509
4146
  }, 30000), "f");
3510
4147
  }
3511
4148
  // Subscribe to query updates
3512
- __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_unsubscribe, __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, "f").subscribeToQueryUpdates(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_subscriptionId, "f"), (updateResult) => {
3513
- // Clear timeout on first message
3514
- if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initTimeoutId, "f")) {
3515
- clearTimeout(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initTimeoutId, "f"));
3516
- __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initTimeoutId, undefined, "f");
3517
- }
3518
- // Resolve the initialization promise (only resolves once)
3519
- if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initResolve, "f")) {
3520
- __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initResolve, "f").call(this, true);
3521
- __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initResolve, undefined, "f"); // Prevent double-resolve
3522
- __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initReject, undefined, "f");
3523
- }
3524
- __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_latestResult, updateResult, "f");
3525
- __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_instances, "m", _QuerySubscriptionProxy_notifyCallbacks).call(this, updateResult);
3526
- }), "f");
4149
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_unsubscribe, __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, "f").subscribeToQueryUpdates(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_subscriptionId, "f"), (updateResult) => __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_instances, "m", _QuerySubscriptionProxy_deliverResult).call(this, updateResult)), "f");
3527
4150
  }
3528
4151
  catch (error) {
3529
4152
  console.error('Error setting up subscription:', error);
@@ -3533,36 +4156,117 @@ class QuerySubscriptionProxy {
3533
4156
  __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initResolve, undefined, "f");
3534
4157
  __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initReject, undefined, "f");
3535
4158
  }
4159
+ // Restore reconnect recovery before rethrowing. The listener was
4160
+ // removed at the top of this method; without re-installing one
4161
+ // here, a single failed resubscribe (e.g. subscribeQuery timing
4162
+ // out during a network flap) would leave the proxy permanently
4163
+ // dead: the keepalive loop stops itself on resubscribe failure,
4164
+ // and nothing else retries. The recovery listener runs the FULL
4165
+ // subscribe() (not the swap-in-place handler) because after a
4166
+ // failed attempt there is no keepalive loop left to feed the new
4167
+ // server subscription — subscribe() restarts it. This is
4168
+ // loop-safe: in this failed state the proxy owns no
4169
+ // `_wsCallbacks` entry (the old one was unsubscribed at the top
4170
+ // of this method and no new one got registered), so the
4171
+ // subscribe() it triggers has nothing to unsubscribe → the
4172
+ // socket never closes/reopens under it → no re-entrant onopen.
4173
+ if (!__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_disposed, "f") && __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_generation, "f") === generation && __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, "f").onReconnect) {
4174
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_reconnectUnsub, __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, "f").onReconnect(() => {
4175
+ if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_disposed, "f"))
4176
+ return;
4177
+ console.log('WebSocket reconnected — retrying failed subscription for query:', __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_query, "f"));
4178
+ this.subscribe().catch(e => {
4179
+ console.error('Error during subscription retry after reconnect:', e);
4180
+ });
4181
+ }), "f");
4182
+ }
3536
4183
  throw error; // Re-throw so caller knows it failed
3537
4184
  }
3538
- // Start keepalive loop using platform-agnostic setTimeout
3539
- const keepaliveLoop = async () => {
3540
- if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_disposed, "f"))
3541
- return;
3542
- try {
3543
- await __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, "f").keepAliveQuery(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_subscriptionId, "f"));
3544
- }
3545
- catch (e) {
3546
- console.error('Error in keepalive:', e);
3547
- // try to reinitialize the subscription
3548
- console.log('Reinitializing subscription for query:', __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_query, "f"));
4185
+ // Start keepalive loop
4186
+ __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_instances, "m", _QuerySubscriptionProxy_startKeepalive).call(this, generation);
4187
+ // Register for reconnect notification — on WebSocket reconnect,
4188
+ // immediately re-establish a fresh server-side subscription instead
4189
+ // of waiting up to 30s for the keepalive to fail.
4190
+ //
4191
+ // We deliberately do NOT call `this.subscribe()` here. Full subscribe
4192
+ // runs `#unsubscribe` first, which delegates to `ApiClient.subscribe`'s
4193
+ // deleter — that closes the WebSocket when this query owned the LAST
4194
+ // `_wsCallbacks` entry. The subsequent `subscribeQuery` reopens the
4195
+ // socket, whose fresh `onopen` fires every registered reconnect
4196
+ // callback again → recursion (CodeRabbit's original finding). And
4197
+ // during that close→reopen gap, RPCs in flight from OTHER proxies
4198
+ // fail with `503 WebSocket not connected` (observed in
4199
+ // integration-tests-mcp `should fire onWake when mention uses agent DID`
4200
+ // after PR #899's initial fix — the WakerSubscriptionManager tests
4201
+ // share a wakerClient across cases, so any dying reconnect handler
4202
+ // interferes with sibling subscriptions).
4203
+ //
4204
+ // The correct shape is a swap-in-place: get a new server-side
4205
+ // subscription ID via `subscribeQuery`, register a new client-side
4206
+ // callback FIRST, and only then unsubscribe the old one. That way
4207
+ // `_wsCallbacks.size` never dips to 0 during the transition, so the
4208
+ // socket doesn't close, no reconnect loop, and no cross-proxy 503s.
4209
+ // Any prior listener was already removed at the top of this method
4210
+ // (see the note there for why cleanup must run before `#unsubscribe`,
4211
+ // not here).
4212
+ if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, "f").onReconnect) {
4213
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_reconnectUnsub, __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, "f").onReconnect(async () => {
4214
+ var _a;
4215
+ if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_disposed, "f"))
4216
+ return;
4217
+ // The handler is a writer of `#unsubscribe`/`#subscriptionId`
4218
+ // too, so it takes its own generation — see #generation.
4219
+ const swapGeneration = __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_generation, (_a = __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_generation, "f"), ++_a), "f");
4220
+ console.log('WebSocket reconnected — re-establishing server subscription for query:', __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_query, "f"));
3549
4221
  try {
3550
- await this.subscribe();
3551
- console.log('Subscription reinitialized');
4222
+ const newInitial = await __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, "f").subscribeQuery(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_query, "f"));
4223
+ if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_disposed, "f") || __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_generation, "f") !== swapGeneration) {
4224
+ // A newer writer took over while we awaited — back out
4225
+ // and release the orphaned server-side subscription.
4226
+ __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, "f").disposeQuerySubscription(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_uuid, "f"), newInitial.subscriptionId)
4227
+ .catch(e => console.error('Error disposing superseded query subscription:', e));
4228
+ return;
4229
+ }
4230
+ const newSubId = newInitial.subscriptionId;
4231
+ // Register the NEW client-side callback BEFORE removing the
4232
+ // old one — keeps `_wsCallbacks.size >= 1` across the swap.
4233
+ const newUnsub = __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, "f").subscribeToQueryUpdates(newSubId, (updateResult) => __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_instances, "m", _QuerySubscriptionProxy_deliverResult).call(this, updateResult));
4234
+ const oldUnsub = __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_unsubscribe, "f");
4235
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_unsubscribe, newUnsub, "f");
4236
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_subscriptionId, newSubId, "f");
4237
+ if (oldUnsub)
4238
+ oldUnsub();
4239
+ // Our generation bump invalidated the running keepalive
4240
+ // loop — restart it under our generation so the new
4241
+ // server subscription keeps receiving keepalives.
4242
+ clearTimeout(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_keepaliveTimer, "f"));
4243
+ __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_instances, "m", _QuerySubscriptionProxy_startKeepalive).call(this, swapGeneration);
4244
+ // Deliver the fresh initial result if the server included one
4245
+ // (matches the eager-delivery path in the main subscribe() body).
4246
+ // #deliverResult also clears a still-pending init timeout and
4247
+ // resolves #initialized, keeping this path symmetric with the
4248
+ // update callback in subscribe() — without it, a swap landing
4249
+ // while initialization was pending would leave the 30s init
4250
+ // timer armed and trigger a spurious full resubscribe.
4251
+ if (newInitial.result !== undefined) {
4252
+ __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_instances, "m", _QuerySubscriptionProxy_deliverResult).call(this, newInitial.result);
4253
+ }
3552
4254
  }
3553
- catch (resubscribeError) {
3554
- console.error('Error during resubscription from keepalive:', resubscribeError);
3555
- // Don't schedule another keepalive on resubscribe failure
3556
- return;
4255
+ catch (error) {
4256
+ console.error('Error re-establishing subscription after reconnect:', error);
4257
+ // Our generation bump invalidated the running keepalive
4258
+ // loop; if nothing newer superseded us, restart it so
4259
+ // liveness is preserved — its keepAliveQuery against the
4260
+ // dead old subscription will fail and fall back to a
4261
+ // full subscribe(). The reconnect listener also remains
4262
+ // installed, so a later reconnect retries this handler.
4263
+ if (!__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_disposed, "f") && __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_generation, "f") === swapGeneration) {
4264
+ clearTimeout(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_keepaliveTimer, "f"));
4265
+ __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_instances, "m", _QuerySubscriptionProxy_startKeepalive).call(this, swapGeneration);
4266
+ }
3557
4267
  }
3558
- }
3559
- // Schedule next keepalive if not disposed
3560
- if (!__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_disposed, "f")) {
3561
- __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_keepaliveTimer, setTimeout(keepaliveLoop, 30000), "f");
3562
- }
3563
- };
3564
- // Start the first keepalive loop
3565
- __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_keepaliveTimer, setTimeout(keepaliveLoop, 30000), "f");
4268
+ }), "f");
4269
+ }
3566
4270
  }
3567
4271
  /** Get the subscription ID for this query subscription
3568
4272
  *
@@ -3635,11 +4339,19 @@ class QuerySubscriptionProxy {
3635
4339
  * will not receive any more updates. The instance should be discarded.
3636
4340
  */
3637
4341
  dispose() {
4342
+ var _a;
3638
4343
  __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_disposed, true, "f");
4344
+ // Invalidate any suspended writer so a mid-flight subscribe() or
4345
+ // reconnect swap backs out instead of resurrecting state.
4346
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_generation, (_a = __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_generation, "f"), _a++, _a), "f");
3639
4347
  clearTimeout(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_keepaliveTimer, "f"));
3640
4348
  if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_unsubscribe, "f")) {
3641
4349
  __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_unsubscribe, "f").call(this);
3642
4350
  }
4351
+ if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_reconnectUnsub, "f")) {
4352
+ __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_reconnectUnsub, "f").call(this);
4353
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_reconnectUnsub, undefined, "f");
4354
+ }
3643
4355
  __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_callbacks, "f").clear();
3644
4356
  if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initTimeoutId, "f")) {
3645
4357
  clearTimeout(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initTimeoutId, "f"));
@@ -3652,7 +4364,58 @@ class QuerySubscriptionProxy {
3652
4364
  }
3653
4365
  }
3654
4366
  }
3655
- _QuerySubscriptionProxy_uuid = new WeakMap(), _QuerySubscriptionProxy_subscriptionId = new WeakMap(), _QuerySubscriptionProxy_client = new WeakMap(), _QuerySubscriptionProxy_callbacks = new WeakMap(), _QuerySubscriptionProxy_keepaliveTimer = new WeakMap(), _QuerySubscriptionProxy_unsubscribe = new WeakMap(), _QuerySubscriptionProxy_latestResult = new WeakMap(), _QuerySubscriptionProxy_disposed = new WeakMap(), _QuerySubscriptionProxy_initialized = new WeakMap(), _QuerySubscriptionProxy_initResolve = new WeakMap(), _QuerySubscriptionProxy_initReject = new WeakMap(), _QuerySubscriptionProxy_initTimeoutId = new WeakMap(), _QuerySubscriptionProxy_query = new WeakMap(), _QuerySubscriptionProxy_instances = new WeakSet(), _QuerySubscriptionProxy_notifyCallbacks = function _QuerySubscriptionProxy_notifyCallbacks(result) {
4367
+ _QuerySubscriptionProxy_uuid = new WeakMap(), _QuerySubscriptionProxy_subscriptionId = new WeakMap(), _QuerySubscriptionProxy_client = new WeakMap(), _QuerySubscriptionProxy_callbacks = new WeakMap(), _QuerySubscriptionProxy_keepaliveTimer = new WeakMap(), _QuerySubscriptionProxy_unsubscribe = new WeakMap(), _QuerySubscriptionProxy_reconnectUnsub = new WeakMap(), _QuerySubscriptionProxy_latestResult = new WeakMap(), _QuerySubscriptionProxy_disposed = new WeakMap(), _QuerySubscriptionProxy_initialized = new WeakMap(), _QuerySubscriptionProxy_initResolve = new WeakMap(), _QuerySubscriptionProxy_initReject = new WeakMap(), _QuerySubscriptionProxy_initTimeoutId = new WeakMap(), _QuerySubscriptionProxy_query = new WeakMap(), _QuerySubscriptionProxy_generation = new WeakMap(), _QuerySubscriptionProxy_instances = new WeakSet(), _QuerySubscriptionProxy_deliverResult = function _QuerySubscriptionProxy_deliverResult(result) {
4368
+ if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initTimeoutId, "f")) {
4369
+ clearTimeout(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initTimeoutId, "f"));
4370
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initTimeoutId, undefined, "f");
4371
+ }
4372
+ // Resolve the initialization promise (only resolves once)
4373
+ if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initResolve, "f")) {
4374
+ __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initResolve, "f").call(this, true);
4375
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initResolve, undefined, "f"); // Prevent double-resolve
4376
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initReject, undefined, "f");
4377
+ }
4378
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_latestResult, result, "f");
4379
+ __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_instances, "m", _QuerySubscriptionProxy_notifyCallbacks).call(this, result);
4380
+ }, _QuerySubscriptionProxy_startKeepalive = function _QuerySubscriptionProxy_startKeepalive(generation) {
4381
+ const keepaliveLoop = async () => {
4382
+ // Generation check kills orphaned loops: a loop whose
4383
+ // keepAliveQuery was in flight while a newer writer ran is not
4384
+ // cancelled by clearTimeout and would otherwise reschedule
4385
+ // itself alongside the newer loop.
4386
+ if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_disposed, "f") || __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_generation, "f") !== generation)
4387
+ return;
4388
+ try {
4389
+ await __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, "f").keepAliveQuery(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_subscriptionId, "f"));
4390
+ }
4391
+ catch (e) {
4392
+ if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_disposed, "f") || __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_generation, "f") !== generation)
4393
+ return;
4394
+ console.error('Error in keepalive:', e);
4395
+ // try to reinitialize the subscription
4396
+ console.log('Reinitializing subscription for query:', __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_query, "f"));
4397
+ try {
4398
+ await this.subscribe();
4399
+ console.log('Subscription reinitialized');
4400
+ }
4401
+ catch (resubscribeError) {
4402
+ console.error('Error during resubscription from keepalive:', resubscribeError);
4403
+ // Don't schedule another keepalive on resubscribe failure.
4404
+ // Recovery is not lost: the failed subscribe() installed a
4405
+ // reconnect listener that retries the full subscribe.
4406
+ return;
4407
+ }
4408
+ // subscribe() succeeded and started its own keepalive loop
4409
+ // under a new generation — this loop is done.
4410
+ return;
4411
+ }
4412
+ // Schedule next keepalive if still the active generation
4413
+ if (!__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_disposed, "f") && __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_generation, "f") === generation) {
4414
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_keepaliveTimer, setTimeout(keepaliveLoop, 30000), "f");
4415
+ }
4416
+ };
4417
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_keepaliveTimer, setTimeout(keepaliveLoop, 30000), "f");
4418
+ }, _QuerySubscriptionProxy_notifyCallbacks = function _QuerySubscriptionProxy_notifyCallbacks(result) {
3656
4419
  for (const callback of __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_callbacks, "f")) {
3657
4420
  try {
3658
4421
  callback(result);
@@ -3851,8 +4614,8 @@ class PerspectiveProxy {
3851
4614
  * });
3852
4615
  * ```
3853
4616
  */
3854
- async get(query) {
3855
- return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").queryLinks(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, query);
4617
+ async get(query, options) {
4618
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").queryLinks(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, query, options);
3856
4619
  }
3857
4620
  /**
3858
4621
  * Runs generic LLM interpretation over a conversation transcript, turning it
@@ -3867,8 +4630,38 @@ class PerspectiveProxy {
3867
4630
  * @param basePrefix URI namespace for new instance identities, e.g. `soa://ext/`
3868
4631
  * @param classes local names of the subject classes to extract into; omit for all
3869
4632
  */
3870
- async runInterpretation(transcript, basePrefix, classes) {
3871
- return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").runInterpretation(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, transcript, basePrefix, classes);
4633
+ async runInterpretation(transcript, basePrefix, classes, options) {
4634
+ // Grouped into an options bag rather than continuing the client's positional list.
4635
+ // The scopes were already unreachable from here for that reason, and a fourth, fifth and
4636
+ // sixth positional parameter would have made `undefined, undefined, { … }` the normal way
4637
+ // to ask for the only one of them most callers want.
4638
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").runInterpretation(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, transcript, basePrefix, classes, options?.existingScope, options?.mintScope, options?.observe);
4639
+ }
4640
+ /**
4641
+ * Harness-dispatched interpretation pass over this perspective (design v3
4642
+ * §6 — the tool-calling counterpart to {@link runInterpretation}). The LLM
4643
+ * sees a live per-class tool surface (`{Class}_query`, `{Class}_get`,
4644
+ * `{Class}_propose_create`, `{Class}_propose_link_child`, …) and drives
4645
+ * the extraction via tool calls; buffered proposals drain through the
4646
+ * same overlay gate the single-shot path uses.
4647
+ *
4648
+ * @param transcript ordered `{ speaker, text }` turns
4649
+ * @param basePrefix URI namespace new instance identities are minted under
4650
+ * @param maxToolCalls upper bound on tool calls the harness will make in
4651
+ * one pass (must be > 0 — use {@link runInterpretation} for the
4652
+ * classic single-shot path)
4653
+ * @param classes local names of the subject classes to extract into; omit for all
4654
+ * @param modelOverride optional model override; omit for the default LLM
4655
+ */
4656
+ async runInterpretationWithHarness(transcript, basePrefix, maxToolCalls, classes, modelOverride,
4657
+ // Optional live-debug observability. When both `observationId` and
4658
+ // `emitDebugEvents` are supplied, every dispatched tool call fires
4659
+ // `ToolCall` + `ToolResult` events on the `auto-processor-event`
4660
+ // topic keyed by `observationId`. Subscribe with
4661
+ // {@link addAutoProcessorEventListener} to render the harness loop
4662
+ // live in a UI. Absent = fast headless path (no telemetry cost).
4663
+ observationId, emitDebugEvents) {
4664
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").runInterpretationWithHarness(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, transcript, basePrefix, maxToolCalls, classes, modelOverride, undefined, observationId, emitDebugEvents);
3872
4665
  }
3873
4666
  /**
3874
4667
  * Register a neighbourhood auto-processor on this perspective. The executor
@@ -3879,6 +4672,24 @@ class PerspectiveProxy {
3879
4672
  async addAutoProcessor(config) {
3880
4673
  return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").addAutoProcessor(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, config);
3881
4674
  }
4675
+ /**
4676
+ * Stop an auto-processor by deleting its config.
4677
+ *
4678
+ * The registration is data — the watch loop reads the processor set back out of the
4679
+ * perspective's graph on every tick — so deleting the config is what stops it, and there is
4680
+ * nothing else to unregister. The config is `Shared`, so this stops the processor for the
4681
+ * neighbourhood rather than only for this peer.
4682
+ *
4683
+ * Resolves `true` when there was a processor to remove and `false` when there was not; a
4684
+ * processor another peer has already removed is not an error.
4685
+ *
4686
+ * The processor's `InterpretationRun` nodes stay: they are the record of what it did and the
4687
+ * processed-turn cursor, so a processor later registered under the same id resumes where this
4688
+ * one left off rather than re-reading every turn.
4689
+ */
4690
+ async removeAutoProcessor(processorId) {
4691
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").removeAutoProcessor(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, processorId);
4692
+ }
3882
4693
  /**
3883
4694
  * Pending interpretation overlays on this perspective — LLM suggestions the
3884
4695
  * §4 divergence gate staged rather than applied, awaiting human accept/reject.
@@ -3906,6 +4717,16 @@ class PerspectiveProxy {
3906
4717
  async addAutoProcessorEventListener(cb) {
3907
4718
  return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").addAutoProcessorEventListener(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, cb);
3908
4719
  }
4720
+ /**
4721
+ * Subscribe to this perspective's auto-processor neighbourhood-state
4722
+ * events — fires when this executor claims / finishes / abandons a
4723
+ * batch. Perspective-scoped, so a UI can render "someone is
4724
+ * auto-processing this" without receiving the batch payload. See
4725
+ * `AutoProcessorNeighbourhoodStateEvent`.
4726
+ */
4727
+ async addAutoProcessorNeighbourhoodStateListener(cb) {
4728
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").addAutoProcessorNeighbourhoodStateListener(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, cb);
4729
+ }
3909
4730
  /**
3910
4731
  * Executes a Prolog query against the perspective's knowledge base.
3911
4732
  * This is a powerful way to find complex patterns in the graph.
@@ -3929,8 +4750,8 @@ class PerspectiveProxy {
3929
4750
  * `);
3930
4751
  * ```
3931
4752
  */
3932
- async infer(query) {
3933
- return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").queryProlog(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, query);
4753
+ async infer(query, options) {
4754
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").queryProlog(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, query, options);
3934
4755
  }
3935
4756
  /**
3936
4757
  * Executes a SPARQL query against the perspective's link cache.
@@ -3940,19 +4761,25 @@ class PerspectiveProxy {
3940
4761
  * Mutating operations (DELETE, UPDATE, INSERT, CREATE, DROP, DEFINE, etc.) are
3941
4762
  * blocked for security reasons. Use the perspective's add/remove methods to modify links.
3942
4763
  *
3943
- * @param query - SPARQL query string (read-only operations only)
3944
- * @returns Query results as parsed JSON
3945
- *
3946
- * Executes a SPARQL query against the perspective's RDF (Oxigraph) store.
4764
+ * **Cancellation:** Pass `{ signal }` from an `AbortController` to abort
4765
+ * an in-flight query. The executor receives `request.cancel` over the
4766
+ * WebSocket and short-circuits the JSON reply. Caveat: Oxigraph itself
4767
+ * cannot be interrupted mid-evaluation, so an already-running scan will
4768
+ * keep its blocking thread busy until it completes; what's saved is the
4769
+ * serialise + network + client-deserialise tax on the result. Aborted
4770
+ * calls reject with `DOMException('Aborted', 'AbortError')` — match
4771
+ * `fetch()` for handling. Cached results bypass the round-trip entirely
4772
+ * and are returned synchronously, ignoring the signal.
3947
4773
  *
3948
- * @param query - SPARQL query string
4774
+ * @param query - SPARQL query string (read-only operations only)
4775
+ * @param options - Optional call options (e.g. AbortSignal for cancellation)
3949
4776
  * @returns Query results as parsed JSON
3950
4777
  */
3951
- async querySparql(query) {
4778
+ async querySparql(query, options) {
3952
4779
  const cached = getCachedResult(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, query);
3953
4780
  if (cached !== undefined)
3954
4781
  return cached;
3955
- const result = await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").querySparql(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, query);
4782
+ const result = await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").querySparql(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, query, options);
3956
4783
  setCachedResult(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, query, result);
3957
4784
  return result;
3958
4785
  }
@@ -3967,8 +4794,43 @@ class PerspectiveProxy {
3967
4794
  * @param queryJson - Structured query as JSON string
3968
4795
  * @returns Object with `instances` array and `totalCount`
3969
4796
  */
3970
- async modelQuery(className, queryJson) {
3971
- return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").modelQuery(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, className, queryJson);
4797
+ async modelQuery(className, queryJson, options) {
4798
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").modelQuery(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, className, queryJson, options);
4799
+ }
4800
+ /** Resolve each URI to the names of every subject class it is an instance of.
4801
+ *
4802
+ * The counterpart of {@link isSubjectInstance}, which asks the same question
4803
+ * one class at a time. Without this, finding the class of an arbitrary URI
4804
+ * meant looping over every registered class — a round trip each — and doing
4805
+ * it again for every URI.
4806
+ *
4807
+ * Class membership in AD4M is structural — a URI belongs to a class when it
4808
+ * carries that class's flags and required properties — so membership is **not
4809
+ * exclusive**: an instance conforms to its parent classes, and to any
4810
+ * unrelated class whose required set happens to be a subset of what it
4811
+ * carries. Every match is returned.
4812
+ *
4813
+ * The list is ordered **most specific first**, meaning by the number of
4814
+ * triples the class requires — a subclass requires everything its parent does
4815
+ * and more — with ties broken alphabetically so that every peer answers
4816
+ * identically. A caller that can only act on one class should take
4817
+ * `classes[0]`, but that head is only a heuristic: it is arbitrary between two
4818
+ * unrelated classes requiring the same number of triples, which is exactly
4819
+ * the case the full list exists to expose.
4820
+ *
4821
+ * A URI is **absent from the result** when no *registered* class matched it.
4822
+ * That covers two situations, and nothing here separates them: the URI may
4823
+ * not be a subject instance at all, or it may be an instance of a class this
4824
+ * perspective has not registered. Absence is used rather than an empty list
4825
+ * because an empty list would claim the stronger thing — that the URI belongs
4826
+ * to no class — which this cannot know.
4827
+ *
4828
+ * @param uris The expression URIs to classify.
4829
+ */
4830
+ async subjectClassesOf(uris) {
4831
+ if (uris.length === 0)
4832
+ return {};
4833
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").subjectClassesOf(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, uris);
3972
4834
  }
3973
4835
  /**
3974
4836
  * Evaluate property getters for a batch of instances in a single RPC call.
@@ -4304,116 +5166,48 @@ class PerspectiveProxy {
4304
5166
  }
4305
5167
  });
4306
5168
  }
4307
- /** Returns all Social DNA flows that can be started from the given expression */
5169
+ /**
5170
+ * Returns all Social DNA flows that can be started from the given expression.
5171
+ *
5172
+ * Post-`flowable` retirement: a flow is a candidate iff its `inputTypes`
5173
+ * declaration is compatible with the expression. Matching rules:
5174
+ * - Empty `inputTypes` or one containing the `"any"` wildcard → always
5175
+ * matches (same behaviour as the legacy `flowable === "any"` case).
5176
+ * - Otherwise, at least one of the expression's registered subject-class
5177
+ * URIs (resolved via {@link subjectClassesOf}) must appear in
5178
+ * `inputTypes`. This is the concrete-type match the design doc's §5
5179
+ * spawn engine calls for; without it, a flow declaring
5180
+ * `inputTypes: ["Task"]` was previously *never* returned by
5181
+ * `availableFlows("some-task-uri")` — the entire point of typed
5182
+ * flows was silently unreachable (James PR #929 J#3).
5183
+ *
5184
+ * The expression is classified against the perspective's registered
5185
+ * classes only. An expression whose class is not registered on this
5186
+ * perspective matches no typed flow (absence, not falsehood — same
5187
+ * discipline as {@link subjectClassesOf}); typed flows requiring
5188
+ * unknown classes are still returned to their untyped-caller peers.
5189
+ */
4308
5190
  async availableFlows(exprAddr) {
4309
5191
  const allFlowNames = await this.sdnaFlows();
5192
+ if (allFlowNames.length === 0)
5193
+ return [];
5194
+ const classesOf = await this.subjectClassesOf([exprAddr]);
5195
+ const exprClasses = classesOf[exprAddr] ?? [];
4310
5196
  const available = [];
4311
5197
  for (const name of allFlowNames) {
4312
5198
  const flow = await this.getFlow(name);
4313
5199
  if (!flow)
4314
5200
  continue;
4315
- if (flow.flowable === "any") {
5201
+ if (flow.inputTypes.length === 0 || flow.inputTypes.includes("any")) {
4316
5202
  available.push(name);
5203
+ continue;
4317
5204
  }
4318
- else {
4319
- // Check if the expression matches the flowable link pattern
4320
- const pattern = flow.flowable;
4321
- const source = pattern.source || exprAddr;
4322
- const links = await this.get(new LinkQuery({
4323
- source,
4324
- predicate: pattern.predicate,
4325
- target: pattern.target
4326
- }));
4327
- if (links.length > 0) {
4328
- available.push(name);
4329
- }
5205
+ if (exprClasses.some(cls => flow.inputTypes.includes(cls))) {
5206
+ available.push(name);
4330
5207
  }
4331
5208
  }
4332
5209
  return available;
4333
5210
  }
4334
- /** Starts the Social DNA flow @param flowName on the expression @param exprAddr */
4335
- async startFlow(flowName, exprAddr) {
4336
- const flow = await this.getFlow(flowName);
4337
- if (!flow)
4338
- throw `Flow "${flowName}" not found`;
4339
- if (flow.startAction.length === 0)
4340
- throw `Flow "${flowName}" has no start action`;
4341
- await this.executeAction(flow.startAction, exprAddr, undefined);
4342
- }
4343
- /** Returns all expressions in the given state of given Social DNA flow */
4344
- async expressionsInFlowState(flowName, flowState) {
4345
- const flow = await this.getFlow(flowName);
4346
- if (!flow)
4347
- return [];
4348
- // Find the state with the matching value
4349
- const state = flow.states.find(s => s.value === flowState);
4350
- if (!state)
4351
- return [];
4352
- // Query for expressions matching this state's check pattern
4353
- const pattern = state.stateCheck;
4354
- const links = await this.get(new LinkQuery({
4355
- predicate: pattern.predicate,
4356
- target: pattern.target
4357
- }));
4358
- // Return the sources (expression addresses) - use source if pattern has no explicit source
4359
- return links.map(l => pattern.source ? l.data.target : l.data.source);
4360
- }
4361
- /** Returns the given expression's flow state with regard to given Social DNA flow */
4362
- async flowState(flowName, exprAddr) {
4363
- const flow = await this.getFlow(flowName);
4364
- if (!flow)
4365
- throw `Flow "${flowName}" not found`;
4366
- // Check each state to find which one the expression is in
4367
- for (const state of flow.states) {
4368
- const pattern = state.stateCheck;
4369
- const source = pattern.source || exprAddr;
4370
- const links = await this.get(new LinkQuery({
4371
- source,
4372
- predicate: pattern.predicate,
4373
- target: pattern.target
4374
- }));
4375
- if (links.length > 0)
4376
- return state.value;
4377
- }
4378
- throw `Expression "${exprAddr}" is not in any state of flow "${flowName}"`;
4379
- }
4380
- /** Returns available action names, with regard to Social DNA flow and expression's flow state */
4381
- async flowActions(flowName, exprAddr) {
4382
- const flow = await this.getFlow(flowName);
4383
- if (!flow)
4384
- return [];
4385
- // Determine current state
4386
- let currentStateName = null;
4387
- for (const state of flow.states) {
4388
- const pattern = state.stateCheck;
4389
- const source = pattern.source || exprAddr;
4390
- const links = await this.get(new LinkQuery({
4391
- source,
4392
- predicate: pattern.predicate,
4393
- target: pattern.target
4394
- }));
4395
- if (links.length > 0) {
4396
- currentStateName = state.name;
4397
- break;
4398
- }
4399
- }
4400
- if (!currentStateName)
4401
- return [];
4402
- // Return transitions available from current state
4403
- return flow.transitions
4404
- .filter(t => t.fromState === currentStateName)
4405
- .map(t => t.actionName);
4406
- }
4407
- /** Runs given Social DNA flow action */
4408
- async runFlowAction(flowName, exprAddr, actionName) {
4409
- const flow = await this.getFlow(flowName);
4410
- if (!flow)
4411
- throw `Flow "${flowName}" not found`;
4412
- const transition = flow.transitions.find(t => t.actionName === actionName);
4413
- if (!transition)
4414
- throw `Action "${actionName}" not found in flow "${flowName}"`;
4415
- await this.executeAction(transition.actions, exprAddr, undefined);
4416
- }
4417
5211
  /** Returns the perspective's Social DNA code
4418
5212
  * This will return all SDNA code elements in an array.
4419
5213
  */
@@ -4593,111 +5387,45 @@ class PerspectiveProxy {
4593
5387
  await this.addLinks(allLinks);
4594
5388
  }
4595
5389
  /**
4596
- * Retrieve a SHACL shape by name from this Perspective
5390
+ * Retrieve a SHACL shape by name from this Perspective (one RPC call).
5391
+ * The executor resolves the full shape (including property sub-shapes)
5392
+ * in-process and returns link triples for client-side reconstruction.
4597
5393
  */
4598
5394
  async getShacl(name) {
4599
- // Find the shape URI from the name mapping
4600
- const nameMapping = Literal.fromUrl(`literal:string:shacl://${name}`);
4601
- const shapeUriLinks = await this.get(new LinkQuery({
4602
- source: nameMapping.toUrl(),
4603
- predicate: "ad4m://shacl_shape_uri"
4604
- }));
4605
- if (shapeUriLinks.length === 0) {
5395
+ const result = await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").getShacl(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, name);
5396
+ if (!result)
4606
5397
  return null;
4607
- }
4608
- const shapeUri = shapeUriLinks[0].data.target;
4609
- // First get property shape URIs so we can query everything in one go
4610
- const propertyLinks = await this.get(new LinkQuery({
4611
- source: shapeUri,
4612
- predicate: "sh://property"
4613
- }));
4614
- // Fetch all links from the shape and its property shapes. These reads are
4615
- // independent of each other, so fire them concurrently rather than one RPC
4616
- // round trip at a time — over a remote (non-loopback) connection, a shape with
4617
- // a dozen properties otherwise pays a dozen sequential round trips just to load.
4618
- const sourceUris = [shapeUri, ...propertyLinks.map(l => l.data.target)];
4619
- const linksByUri = await Promise.all(sourceUris.map(uri => this.get(new LinkQuery({ source: uri }))));
4620
- // Dedupe by (source, predicate, target): a perspective that's accumulated duplicate
4621
- // SDNA links (e.g. from repeated registration attempts, or executor-side sync bugs)
4622
- // would otherwise feed the same triple into SHACLShape.fromLinks more than once —
4623
- // harmless for scalar fields like targetClass (first match wins) but can surface as
4624
- // visibly duplicated properties for repeated sh://property links. Cheap: this is an
4625
- // in-memory pass over data already fetched, no extra round trips.
4626
- const seenLinks = new Set();
4627
- const allLinks = [];
4628
- for (const links of linksByUri) {
4629
- for (const l of links) {
4630
- const key = `${l.data.source} ${l.data.predicate} ${l.data.target}`;
4631
- if (seenLinks.has(key))
4632
- continue;
4633
- seenLinks.add(key);
4634
- allLinks.push({
4635
- source: l.data.source,
4636
- predicate: l.data.predicate,
4637
- target: l.data.target
4638
- });
4639
- }
4640
- }
4641
- const shapeLinks = allLinks;
4642
- return SHACLShape.fromLinks(shapeLinks, shapeUri);
5398
+ return SHACLShape.fromLinks(result.links, result.shapeUri);
4643
5399
  }
4644
5400
  /**
4645
- * List the names of every SHACL shape stored in this Perspective, without fetching
4646
- * each shape's full definition (properties, target class, etc.) — just the cheap
4647
- * `ad4m://has_shacl` enumeration, one round trip regardless of how many shapes exist.
4648
- * Use this to check which shapes are actually worth resolving via `getShacl()` before
4649
- * paying for each one's full (multi-round-trip) fetch.
5401
+ * List the names of every SHACL shape stored in this Perspective (one RPC call).
4650
5402
  */
4651
5403
  async getShaclNames() {
4652
- const nameLinks = await this.get(new LinkQuery({
4653
- source: "ad4m://self",
4654
- predicate: "ad4m://has_shacl"
4655
- }));
4656
- // Dedupe: a perspective with duplicate `has_shacl` links (see the dedup note in
4657
- // getShacl()) would otherwise report the same name more than once, causing callers
4658
- // to redundantly resolve (or redundantly disambiguate) it multiple times.
4659
- const names = nameLinks.map((nameLink) => {
4660
- const name = Literal.fromUrl(nameLink.data.target).get();
4661
- return name.replace('shacl://', '');
4662
- });
4663
- return [...new Set(names)];
5404
+ return __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").getShaclNames(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid);
4664
5405
  }
4665
5406
  /**
4666
- * Resolve just a shape's `sh:targetClass` by name, without fetching its properties —
4667
- * two round trips (name → shapeUri, then shapeUri's own direct triples) instead of
4668
- * `getShacl()`'s full walk (which also fetches every property sub-shape). Use this to
4669
- * disambiguate a shape name that collides with another app's `@Model({ name })` string
4670
- * (the bare `shacl://{name}` mapping ad4m-core uses is namespace-blind — see
4671
- * `getShaclNames()` callers for why that matters) before paying for a full fetch.
5407
+ * Resolve a shape's `sh:targetClass` by name (one RPC call).
5408
+ *
5409
+ * `PerspectiveClient.getShaclTargetClass` now returns `undefined` on
5410
+ * "not found" already (see review r3897752023 — the null→undefined
5411
+ * coercion used to happen here and be duplicated one layer down),
5412
+ * so this method is a pure passthrough.
4672
5413
  */
4673
5414
  async getShaclTargetClass(name) {
4674
- const nameMapping = Literal.fromUrl(`literal:string:shacl://${name}`);
4675
- const shapeUriLinks = await this.get(new LinkQuery({
4676
- source: nameMapping.toUrl(),
4677
- predicate: "ad4m://shacl_shape_uri"
4678
- }));
4679
- if (shapeUriLinks.length === 0) {
4680
- return undefined;
4681
- }
4682
- const shapeUri = shapeUriLinks[0].data.target;
4683
- const shapeOwnLinks = await this.get(new LinkQuery({ source: shapeUri }));
4684
- return shapeOwnLinks.find(l => l.data.predicate === "sh://targetClass")?.data.target;
5415
+ return __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").getShaclTargetClass(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, name);
4685
5416
  }
4686
5417
  /**
4687
- * Get all SHACL shapes stored in this Perspective
5418
+ * Get all SHACL shapes stored in this Perspective (one RPC call).
5419
+ * The executor resolves all shapes in-process and returns them in bulk.
4688
5420
  */
4689
5421
  async getAllShacl() {
4690
- const shapeNames = await this.getShaclNames();
4691
- // Each shape is fetched independently of the others — resolve them concurrently.
4692
- // Sequentially awaiting getShacl() per shape means a perspective with N SDNA
4693
- // models pays N times getShacl()'s own multi-round-trip cost one after another;
4694
- // over a remote connection with real per-call latency that compounds into the
4695
- // dominant cost of switching into a perspective at all.
4696
- const results = await Promise.all(shapeNames.map(async (shapeName) => {
4697
- const shape = await this.getShacl(shapeName);
4698
- return shape ? { name: shapeName, shape } : null;
4699
- }));
4700
- return results.filter((s) => s !== null);
5422
+ const entries = await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").getAllShacl(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid);
5423
+ return entries
5424
+ .map(({ name, shapeUri, links }) => {
5425
+ const shape = SHACLShape.fromLinks(links, shapeUri);
5426
+ return shape ? { name, shape } : null;
5427
+ })
5428
+ .filter((s) => s !== null);
4701
5429
  }
4702
5430
  /**
4703
5431
  * **Recommended way to add Flow definitions.**
@@ -4712,28 +5440,26 @@ class PerspectiveProxy {
4712
5440
  * ```typescript
4713
5441
  * import { SHACLFlow } from '@coasys/ad4m';
4714
5442
  *
4715
- * const todoFlow = new SHACLFlow('TODO', 'todo://');
4716
- * todoFlow.flowable = 'any';
4717
- *
4718
- * // Define states
4719
- * todoFlow.addState({ name: 'ready', value: 0, stateCheck: { predicate: 'todo://state', target: 'todo://ready' }});
4720
- * todoFlow.addState({ name: 'done', value: 1, stateCheck: { predicate: 'todo://state', target: 'todo://done' }});
4721
- *
4722
- * // Define start action
4723
- * todoFlow.startAction = [{ action: 'addLink', source: 'this', predicate: 'todo://state', target: 'todo://ready' }];
4724
- *
4725
- * // Define transitions
4726
- * todoFlow.addTransition({
4727
- * actionName: 'Complete',
4728
- * fromState: 'ready',
4729
- * toState: 'done',
4730
- * actions: [
4731
- * { action: 'addLink', source: 'this', predicate: 'todo://state', target: 'todo://done' },
4732
- * { action: 'removeLink', source: 'this', predicate: 'todo://state', target: 'todo://ready' }
4733
- * ]
4734
- * });
5443
+ * const deliveryFlow = new SHACLFlow('Delivery', 'delivery://');
5444
+ * deliveryFlow.inputTypes = ['Task'];
5445
+ * deliveryFlow.interpretationHint =
5446
+ * 'Advance a Task through delivery: Identified → Scoped → InProgress → Review → Done.';
4735
5447
  *
4736
- * await perspective.addFlow('TODO', todoFlow);
5448
+ * deliveryFlow.addState({ name: 'Identified', value: 0 });
5449
+ * deliveryFlow.addState({ name: 'Scoped', value: 1 });
5450
+ * deliveryFlow.addState({ name: 'InProgress', value: 2 });
5451
+ * deliveryFlow.addState({ name: 'Review', value: 3 });
5452
+ * deliveryFlow.addState({ name: 'Done', value: 4 });
5453
+ *
5454
+ * deliveryFlow.addTransition({ actionName: 'Scope', fromState: 'Identified', toState: 'Scoped', actions: [] });
5455
+ * deliveryFlow.addTransition({ actionName: 'Start', fromState: 'Scoped', toState: 'InProgress', actions: [] });
5456
+ * deliveryFlow.addTransition({ actionName: 'Submit', fromState: 'InProgress', toState: 'Review', actions: [] });
5457
+ * deliveryFlow.addTransition({ actionName: 'Accept', fromState: 'Review', toState: 'Done', actions: [] });
5458
+ *
5459
+ * // Optional: n distinct DIDs must co-sign a proposal before it fires.
5460
+ * deliveryFlow.consensusRule = { n: 2 };
5461
+ *
5462
+ * await perspective.addFlow('Delivery', deliveryFlow);
4737
5463
  * ```
4738
5464
  */
4739
5465
  async addFlow(name, flow) {
@@ -4778,20 +5504,20 @@ class PerspectiveProxy {
4778
5504
  return null;
4779
5505
  }
4780
5506
  const flowUri = flowUriLinks[0].data.target;
4781
- // Compute alternate prefix for state/transition URIs
4782
- const alternatePrefix = flowUri.endsWith('Flow')
4783
- ? flowUri.slice(0, -4) + '.'
4784
- : flowUri + '.';
4785
- // Fetch flow links using SPARQL to match flowUri source OR alternatePrefix sources
4786
- const sparqlQuery = `SELECT ?s ?p ?o WHERE {
4787
- ?s ?p ?o .
4788
- FILTER(?s = <${flowUri}> || STRSTARTS(STR(?s), "${alternatePrefix}"))
4789
- }`;
4790
- const sparqlResult = await this.querySparql(sparqlQuery);
4791
- const flowLinks = (sparqlResult || []).map((r) => ({
4792
- source: r.s,
4793
- predicate: r.p,
4794
- target: r.o
5507
+ // Fetch flow-level links (hasState, hasTransition, startAction, inputTypes/outputTypes/…)
5508
+ const flowLevelLinks = await this.get(new LinkQuery({ source: flowUri }));
5509
+ // Collect state and transition URIs, then fetch their child links
5510
+ const childUris = flowLevelLinks
5511
+ .filter(l => l.data.predicate === "ad4m://hasState"
5512
+ || l.data.predicate === "ad4m://hasTransition")
5513
+ .map(l => l.data.target);
5514
+ const childResults = await Promise.all(childUris.map(uri => this.get(new LinkQuery({ source: uri }))));
5515
+ // Flatten into the {source, predicate, target} shape fromLinks expects
5516
+ const allExprs = [...flowLevelLinks, ...childResults.flat()];
5517
+ const flowLinks = allExprs.map(l => ({
5518
+ source: l.data.source,
5519
+ predicate: l.data.predicate,
5520
+ target: l.data.target
4795
5521
  }));
4796
5522
  return SHACLFlow.fromLinks(flowLinks, flowUri);
4797
5523
  }
@@ -4844,7 +5570,9 @@ class PerspectiveProxy {
4844
5570
  * with the properties of the subject class.
4845
5571
  * @param exprAddr The address of the expression to be turned into a subject instance
4846
5572
  * @param initialValues Optional initial values for properties. If provided, these will be
4847
- * merged with constructor actions for better performance.
5573
+ * merged with constructor actions for better performance. A collection property accepts
5574
+ * an array value and stores one entry per element; scalar properties store arrays/objects
5575
+ * as a single JSON value.
4848
5576
  * @param batchId Optional batch ID for grouping operations. If provided, returns the expression address
4849
5577
  * instead of the subject proxy since the subject won't exist until the batch is committed.
4850
5578
  * @returns A proxy object for the created subject, or just the expression address if in batch mode
@@ -5631,7 +6359,7 @@ class PerspectiveClient {
5631
6359
  async publishSnapshotByUUID(uuid) {
5632
6360
  return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.publishSnapshot', { uuid });
5633
6361
  }
5634
- async queryLinks(uuid, query) {
6362
+ async queryLinks(uuid, query, options) {
5635
6363
  const params = { uuid };
5636
6364
  if (query.source)
5637
6365
  params.source = query.source;
@@ -5645,14 +6373,14 @@ class PerspectiveClient {
5645
6373
  params.untilDate = query.untilDate instanceof Date ? query.untilDate.toISOString() : String(query.untilDate);
5646
6374
  if (query.limit !== undefined)
5647
6375
  params.limit = query.limit;
5648
- return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.queryLinks', params);
6376
+ return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.queryLinks', params, options);
5649
6377
  }
5650
- async queryProlog(uuid, query) {
5651
- const result = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.queryProlog', { uuid, query });
6378
+ async queryProlog(uuid, query, options) {
6379
+ const result = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.queryProlog', { uuid, query }, options);
5652
6380
  return JSON.parse(result);
5653
6381
  }
5654
- async querySparql(uuid, query) {
5655
- const result = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.querySparql', { uuid, engine: 'sparql', query });
6382
+ async querySparql(uuid, query, options) {
6383
+ const result = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.querySparql', { uuid, engine: 'sparql', query }, options);
5656
6384
  return JSON.parse(result);
5657
6385
  }
5658
6386
  async subscribeQuery(uuid, query) {
@@ -5692,10 +6420,13 @@ class PerspectiveClient {
5692
6420
  }
5693
6421
  return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.disposeQuery', { uuid, subscriptionId });
5694
6422
  }
5695
- async modelQuery(uuid, className, queryJson) {
5696
- const resultJson = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.modelQuery', { uuid, class_name: className, query_json: queryJson });
6423
+ async modelQuery(uuid, className, queryJson, options) {
6424
+ const resultJson = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.modelQuery', { uuid, class_name: className, query_json: queryJson }, options);
5697
6425
  return JSON.parse(resultJson);
5698
6426
  }
6427
+ async subjectClassesOf(uuid, uris) {
6428
+ return await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.subjectClassesOf', { uuid, uris });
6429
+ }
5699
6430
  async evaluateGetters(uuid, className, instanceIds, propertyNames) {
5700
6431
  const resultJson = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.evaluateGetters', {
5701
6432
  uuid,
@@ -5746,10 +6477,62 @@ class PerspectiveClient {
5746
6477
  * retries on parse failure), so it can legitimately take minutes on slower
5747
6478
  * or CPU-only models. We raise the default 30s RPC timeout here to 20 min
5748
6479
  * (matches the CI `--timeout 1200000` for the interpretation tests).
6480
+ *
6481
+ * `existingScope` and `mintScope` match the AutoProcessor semantics:
6482
+ * `existingScope` constrains the dedup lookup to instances under a
6483
+ * subtree; `mintScope` links every FRESHLY-created base as a child of
6484
+ * `mintScope.id` via its predicate (upserts of pre-existing instances
6485
+ * are NOT re-parented — same rule as the watcher).
6486
+ */
6487
+ async runInterpretation(uuid, transcript, basePrefix, classes, existingScope, mintScope, observe) {
6488
+ const RUN_INTERPRETATION_TIMEOUT_MS = 20 * 60 * 1000;
6489
+ return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.runInterpretation', {
6490
+ uuid, transcript, basePrefix, classes, existingScope, mintScope,
6491
+ // Spread rather than always-present, so a client talking to a pre-#903
6492
+ // executor sends exactly the params it sent before. `serde` would ignore
6493
+ // the extra keys anyway; keeping the wire identical means a bug report
6494
+ // from an older node cannot be about these.
6495
+ ...(observe ? {
6496
+ observationId: observe.observationId,
6497
+ emitDebugEvents: observe.emitDebugEvents ?? false,
6498
+ } : {}),
6499
+ }, { timeoutMs: RUN_INTERPRETATION_TIMEOUT_MS });
6500
+ }
6501
+ /**
6502
+ * Tool-calling counterpart to {@link runInterpretation}. The LLM sees a
6503
+ * live per-class tool surface (`{Class}_query`, `{Class}_propose_create`,
6504
+ * `{Class}_propose_link_child`, …) and drives the extraction via tool
6505
+ * calls; buffered proposals drain through the same overlay gate the
6506
+ * single-shot path uses.
6507
+ *
6508
+ * `maxToolCalls` bounds the loop and MUST be > 0 — zero would collapse
6509
+ * the harness to a no-op final-answer step; use {@link runInterpretation}
6510
+ * for the classic single-shot path.
6511
+ *
6512
+ * Same 20-minute RPC timeout as the single-shot path — an LLM loop
6513
+ * that calls several tools can legitimately take longer than one plain
6514
+ * generation.
5749
6515
  */
5750
- async runInterpretation(uuid, transcript, basePrefix, classes) {
6516
+ async runInterpretationWithHarness(uuid, transcript, basePrefix, maxToolCalls, classes, modelOverride, existingScope,
6517
+ // Optional live-debug event surface — same shape/semantics as the
6518
+ // single-shot `runInterpretation`. `observationId` names the
6519
+ // `processor_id` + `batch_key` on emitted `ToolCall` / `ToolResult`
6520
+ // events so a subscribed UI can correlate them to this pass.
6521
+ // `emitDebugEvents` is a dead-letter without an observationId
6522
+ // (nothing to key against); the server gates on both.
6523
+ observationId, emitDebugEvents) {
5751
6524
  const RUN_INTERPRETATION_TIMEOUT_MS = 20 * 60 * 1000;
5752
- return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.runInterpretation', { uuid, transcript, basePrefix, classes }, RUN_INTERPRETATION_TIMEOUT_MS);
6525
+ return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.runInterpretationWithHarness', {
6526
+ uuid,
6527
+ transcript,
6528
+ basePrefix,
6529
+ maxToolCalls,
6530
+ classes,
6531
+ modelOverride,
6532
+ existingScope,
6533
+ observationId,
6534
+ emitDebugEvents,
6535
+ }, { timeoutMs: RUN_INTERPRETATION_TIMEOUT_MS });
5753
6536
  }
5754
6537
  /**
5755
6538
  * Register a neighbourhood auto-processor on this perspective. The executor's
@@ -5762,6 +6545,10 @@ class PerspectiveClient {
5762
6545
  async addAutoProcessor(uuid, config) {
5763
6546
  return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.addAutoProcessor', { uuid, ...config });
5764
6547
  }
6548
+ /** Delete an auto-processor's config. `false` when there was none to delete. */
6549
+ async removeAutoProcessor(uuid, processorId) {
6550
+ return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.removeAutoProcessor', { uuid, processorId });
6551
+ }
5765
6552
  /** Pending interpretation overlays (LLM suggestions awaiting human accept/reject). */
5766
6553
  async interpretationOverlays(uuid) {
5767
6554
  return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.interpretationOverlays', { uuid });
@@ -5780,6 +6567,11 @@ class PerspectiveClient {
5780
6567
  * Subscribe to auto-processor step signals. `cb` fires for every
5781
6568
  * `auto-processor-event` on `uuid` (BatchReady → Claimed/BackedOff/… →
5782
6569
  * Processed), letting a UI show progress and await the next batch.
6570
+ *
6571
+ * Registered on the per-uuid `#linkUnsubscribers` map so
6572
+ * `PerspectiveProxy.dispose()` → `removeAllListeners(uuid)` cleans the
6573
+ * subscription up; using the global `#unsubscribers` array would leak
6574
+ * callbacks across repeated view lifecycles (CodeRabbit #881 review).
5783
6575
  */
5784
6576
  async addAutoProcessorEventListener(uuid, cb) {
5785
6577
  const unsub = __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").subscribe((data) => {
@@ -5787,7 +6579,28 @@ class PerspectiveClient {
5787
6579
  cb(data);
5788
6580
  }
5789
6581
  });
5790
- __classPrivateFieldGet$9(this, _PerspectiveClient_unsubscribers, "f").push(unsub);
6582
+ let existing = __classPrivateFieldGet$9(this, _PerspectiveClient_linkUnsubscribers, "f").get(uuid) || [];
6583
+ existing.push(unsub);
6584
+ __classPrivateFieldGet$9(this, _PerspectiveClient_linkUnsubscribers, "f").set(uuid, existing);
6585
+ await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").waitForSubscription();
6586
+ }
6587
+ /**
6588
+ * Subscribe to neighbourhood-state events on a perspective. `cb` fires
6589
+ * when THIS executor claims / finishes / abandons a batch for any
6590
+ * processor on `uuid` — perspective-scoped observability so a UI can
6591
+ * render "someone is auto-processing this" without receiving the batch
6592
+ * payload or LLM I/O. Registered on the per-uuid `#linkUnsubscribers`
6593
+ * map so `PerspectiveProxy.dispose()` sweeps it up.
6594
+ */
6595
+ async addAutoProcessorNeighbourhoodStateListener(uuid, cb) {
6596
+ const unsub = __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").subscribe((data) => {
6597
+ if (data.type === 'auto-processor-neighbourhood-state' && data.perspectiveUuid === uuid) {
6598
+ cb(data);
6599
+ }
6600
+ });
6601
+ let existing = __classPrivateFieldGet$9(this, _PerspectiveClient_linkUnsubscribers, "f").get(uuid) || [];
6602
+ existing.push(unsub);
6603
+ __classPrivateFieldGet$9(this, _PerspectiveClient_linkUnsubscribers, "f").set(uuid, existing);
5791
6604
  await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").waitForSubscription();
5792
6605
  }
5793
6606
  async addLinkExpression(uuid, link, status = 'shared', batchId) {
@@ -5818,6 +6631,43 @@ class PerspectiveClient {
5818
6631
  async getSubjectData(uuid, subjectClass, expressionAddress) {
5819
6632
  return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.getSubjectData', { uuid, subjectClass, expressionAddress });
5820
6633
  }
6634
+ // ── SHACL resolution (server-side) ─────────────────────────────────────────
6635
+ // These methods delegate shape resolution to the executor, which reads links
6636
+ // from its local store in-process. Each call replaces the multi-round-trip
6637
+ // `queryLinks` sequences the old PerspectiveProxy methods performed.
6638
+ /** List the names of every SHACL shape stored in a perspective (one RPC call). */
6639
+ async getShaclNames(uuid) {
6640
+ return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.getShaclNames', { uuid });
6641
+ }
6642
+ /**
6643
+ * Resolve a shape's `sh:targetClass` by name (one RPC call).
6644
+ *
6645
+ * Returns `undefined` when the shape (or its `sh://targetClass` edge) is
6646
+ * absent — unified with `PerspectiveProxy.getShaclTargetClass` so callers
6647
+ * see a single "not found" representation across both layers. The
6648
+ * executor wire format is still `null` (see `perspective.getShaclTargetClass`
6649
+ * in `perspectives_ws.rs`); this method maps that at the boundary rather
6650
+ * than pushing the null one layer further up. PR #935 review r3897752023.
6651
+ */
6652
+ async getShaclTargetClass(uuid, name) {
6653
+ const result = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.getShaclTargetClass', { uuid, name });
6654
+ return result ?? undefined;
6655
+ }
6656
+ /**
6657
+ * Retrieve a single SHACL shape's link triples by name (one RPC call).
6658
+ * Returns `{shapeUri, links}` for reconstruction via `SHACLShape.fromLinks()`,
6659
+ * or `null` if no shape with that name exists.
6660
+ */
6661
+ async getShacl(uuid, name) {
6662
+ return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.getShacl', { uuid, name });
6663
+ }
6664
+ /**
6665
+ * Retrieve all SHACL shapes in one call. Returns an array of
6666
+ * `{name, shapeUri, links}` — one entry per shape (one RPC call).
6667
+ */
6668
+ async getAllShacl(uuid) {
6669
+ return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.getAllShacl', { uuid });
6670
+ }
5821
6671
  // ExpressionClient functions, needed for Subjects:
5822
6672
  async getExpression(expressionURI) {
5823
6673
  return await __classPrivateFieldGet$9(this, _PerspectiveClient_expressionClient, "f").get(expressionURI);
@@ -5939,6 +6789,11 @@ class PerspectiveClient {
5939
6789
  async commitBatch(uuid, batchId) {
5940
6790
  return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.commitBatch', { uuid, batchId });
5941
6791
  }
6792
+ /** Register a callback that fires after a successful WebSocket reconnect.
6793
+ * Passes through to ApiClient.onReconnect(). Returns an unsubscribe function. */
6794
+ onReconnect(callback) {
6795
+ return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").onReconnect(callback);
6796
+ }
5942
6797
  }
5943
6798
  _PerspectiveClient_apiClient = new WeakMap(), _PerspectiveClient_perspectiveAddedCallbacks = new WeakMap(), _PerspectiveClient_perspectiveUpdatedCallbacks = new WeakMap(), _PerspectiveClient_perspectiveRemovedCallbacks = new WeakMap(), _PerspectiveClient_perspectiveSyncStateChangeCallbacks = new WeakMap(), _PerspectiveClient_expressionClient = new WeakMap(), _PerspectiveClient_neighbourhoodClient = new WeakMap(), _PerspectiveClient_aiClient = new WeakMap(), _PerspectiveClient_unsubscribers = new WeakMap(), _PerspectiveClient_linkUnsubscribers = new WeakMap(), _PerspectiveClient_querySubscriptionUnsubscribers = new WeakMap();
5944
6799
 
@@ -14117,9 +14972,12 @@ class AIClient {
14117
14972
  async embed(modelId, text) {
14118
14973
  const aiEmbed = await __classPrivateFieldGet$2(this, _AIClient_apiClient, "f").call('ai.embed', { modelId, text });
14119
14974
  const compressed = base64Js.toByteArray(aiEmbed);
14120
- // Decode to a string via TextDecoder rather than pako's `{ to: 'string' }`
14121
- // option: newer @types/pako dropped that overload, which broke the build.
14122
- const decompressed = JSON.parse(new TextDecoder().decode(pako.inflate(compressed)));
14975
+ // NB: pako v1 accepts `{ to: 'string' }`, pako v2 wants `{ toText: true }`,
14976
+ // pako v3 also drops that overload from its bundled types. Call the
14977
+ // version-agnostic form (returns Uint8Array) and decode explicitly so
14978
+ // this works regardless of which pako major the lockfile pins.
14979
+ const inflated = pako.inflate(compressed);
14980
+ const decompressed = JSON.parse(new TextDecoder('utf-8').decode(inflated));
14123
14981
  return decompressed;
14124
14982
  }
14125
14983
  async openTranscriptionStream(modelId, streamCallback, params) {
@@ -14453,13 +15311,7 @@ function buildModelFromJSONSchema(BaseClass, schema, options) {
14453
15311
  }
14454
15312
  else {
14455
15313
  // Handle regular properties
14456
- let resolveLanguage = getPropertyOption(propertyName, propertySchema, options, 'resolveLanguage');
14457
- // If no specific resolveLanguage for this property, use the global one
14458
- if (!resolveLanguage && options.resolveLanguage) {
14459
- resolveLanguage = options.resolveLanguage;
14460
- }
14461
15314
  const local = getPropertyOption(propertyName, propertySchema, options, 'local');
14462
- // Determine readOnly: check PropertyOptions first, then x-ad4m.writable (inverted) for JSON Schema wire format
14463
15315
  let readOnly = getPropertyOption(propertyName, propertySchema, options, 'readOnly');
14464
15316
  if (readOnly === undefined) {
14465
15317
  const xWritable = propertySchema["x-ad4m"]?.writable;
@@ -14467,22 +15319,14 @@ function buildModelFromJSONSchema(BaseClass, schema, options) {
14467
15319
  }
14468
15320
  const writable = !readOnly;
14469
15321
  let initial = getPropertyOption(propertyName, propertySchema, options, 'initial');
14470
- // Handle nested objects by serializing to JSON
14471
- if (isObjectType(propertySchema) && !resolveLanguage) {
14472
- resolveLanguage = 'literal';
15322
+ // Not defaulted — absence means "deterministic typed literal" (the
15323
+ // perf default); an explicit `resolveLanguage: "literal"` selects the
15324
+ // signed-envelope path; any other value selects a custom language.
15325
+ // See effectiveLiteralStorage().
15326
+ const resolveLanguage = getPropertyOption(propertyName, propertySchema, options, 'resolveLanguage');
15327
+ if (isObjectType(propertySchema)) {
14473
15328
  console.warn(`Property "${propertyName}" is an object type. It will be stored as JSON. Consider flattening complex objects for better semantic querying.`);
14474
15329
  }
14475
- // Ensure numeric properties use literal language for correct typing
14476
- if ((resolveLanguage === undefined || resolveLanguage === null) && isNumericType(propertySchema)) {
14477
- resolveLanguage = 'literal';
14478
- }
14479
- // Default resolveLanguage to 'literal' for all remaining property types,
14480
- // matching the @Property decorator behaviour. Without this, string values
14481
- // stored as literal: URLs are returned unparsed.
14482
- if (resolveLanguage === undefined || resolveLanguage === null) {
14483
- resolveLanguage = 'literal';
14484
- }
14485
- // If property is required, ensure it has an initial value
14486
15330
  if (isRequired && !initial) {
14487
15331
  if (isObjectType(propertySchema)) {
14488
15332
  initial = 'literal:json:{}';
@@ -14495,7 +15339,7 @@ function buildModelFromJSONSchema(BaseClass, schema, options) {
14495
15339
  through: predicate,
14496
15340
  required: isRequired,
14497
15341
  writable: writable,
14498
- ...(resolveLanguage && { resolveLanguage }),
15342
+ ...(resolveLanguage !== undefined && { resolveLanguage }),
14499
15343
  ...(local !== undefined && { local }),
14500
15344
  ...(initial && { initial })
14501
15345
  };
@@ -14610,20 +15454,108 @@ function hasJsOnlyWhereFilters(metadata, allRelationsMetadata, where) {
14610
15454
  return false;
14611
15455
  }
14612
15456
  /**
14613
- * Determine if a property stores values as literal: IRIs (needs parse_literal for comparisons).
14614
- * Properties with resolveLanguage === "literal" AND properties without resolveLanguage
14615
- * both store values as literal: URIs. Only properties with a non-literal resolveLanguage
14616
- * (e.g. file storage) or flag properties store raw URIs.
15457
+ * Check whether a string value is a well-formed absolute IRI that can be
15458
+ * stored verbatim as a link target (raw `NamedNode`) instead of being
15459
+ * wrapped in a `literal:string:*` URI.
15460
+ *
15461
+ * This mirrors the Rust `is_safe_iri_target` /
15462
+ * `looks_like_absolute_iri` predicate in
15463
+ * `rust-executor/src/perspectives/model_query/utils.rs` and is
15464
+ * **load-bearing**: a value that returns `true` here MUST also be safely
15465
+ * queryable on the Rust side (`validate_iri` gate on the SPARQL
15466
+ * `UNION { ?s <pred> <val> }` IRI arm), otherwise scheme-lookalike prose
15467
+ * such as `"Note: buy milk"`, `"Re: standup"`, `"TODO: fix this"` slips
15468
+ * through the write regex, is stored as an invalid `NamedNode`, and
15469
+ * becomes a silent no-match on read.
15470
+ *
15471
+ * Fast-path scheme check (`^[a-zA-Z][a-zA-Z0-9+\-._]*:`) followed by the
15472
+ * same rejection set the Rust `validate_iri` applies: any Unicode
15473
+ * whitespace, C0/C1 control chars, and the SPARQL-breaking characters
15474
+ * `< > { } "`.
14617
15475
  */
14618
- function isLiteralStoredProperty(propMeta) {
14619
- if (propMeta.flag)
15476
+ function looksLikeUri(value) {
15477
+ if (!/^[a-zA-Z][a-zA-Z0-9+\-._]*:/.test(value))
14620
15478
  return false;
14621
- // If resolveLanguage is set to something other than "literal", it's a language expression URI
14622
- if (propMeta.resolveLanguage && propMeta.resolveLanguage !== "literal")
15479
+ // Reject anything the Rust-side `validate_iri` rejects so the two
15480
+ // predicates stay in sync. `\s` covers ASCII whitespace *and*
15481
+ // U+00A0/other Unicode whitespace under the default JS regex semantics.
15482
+ if (/[\s<>{}"\u0000-\u001F\u007F-\u009F]/.test(value))
14623
15483
  return false;
14624
- // Everything else (resolveLanguage === "literal" or undefined) stores as literal: URIs
14625
15484
  return true;
14626
15485
  }
15486
+ /**
15487
+ * Convert a JS value to its literal: IRI form, matching how the Rust executor
15488
+ * stores property values in the default deterministic-literal path
15489
+ * (`resolveLanguage` unset). Strings that already look like URIs are returned
15490
+ * as-is.
15491
+ *
15492
+ * Exported so write-side helpers (e.g. `Ad4mModel.setProperty`'s literal
15493
+ * resolve path) can keep their on-disk form aligned with what
15494
+ * `queryToSPARQL()` filters against — otherwise the same value can be
15495
+ * stored as `<literal:string:https%3A...>` from one path while WHERE
15496
+ * builders probe `<https://example.com>` from the other.
15497
+ *
15498
+ * The object/array arm mirrors Rust's `Literal::from_json` in
15499
+ * `perspective_instance.rs::resolve_property_value` (which routes
15500
+ * `Value::Object | Value::Array` through JSON encoding). Without it, JS
15501
+ * would fall through to `String(value)` and turn `{a: 1}` into
15502
+ * `"[object Object]"` and `[1, 2, 3]` into `"1,2,3"` before wrapping.
15503
+ */
15504
+ function valueToLiteralIri(value) {
15505
+ if (typeof value === 'string') {
15506
+ if (looksLikeUri(value))
15507
+ return value;
15508
+ return Literal.from(value).toUrl();
15509
+ }
15510
+ if (typeof value === 'number') {
15511
+ return Literal.from(value).toUrl();
15512
+ }
15513
+ if (typeof value === 'boolean') {
15514
+ return Literal.from(value).toUrl();
15515
+ }
15516
+ // Objects and arrays: route through Literal.from so we emit
15517
+ // `literal:json:*` (mirrors Rust `Literal::from_json`). Without this
15518
+ // arm we fall through to `String(value)` which turns objects into
15519
+ // `"[object Object]"` and arrays into `"1,2"` — silently storing the
15520
+ // wrong shape and breaking equality filters (`findAll({ where:
15521
+ // { config: {...} } })` would match against `"[object Object]"`).
15522
+ // The `value !== null` guard preserves the historical fallthrough for
15523
+ // `null` (→ `literal:string:null`), since `Literal.from(null).toUrl()`
15524
+ // throws on the empty-literal check.
15525
+ if (value !== null && typeof value === 'object') {
15526
+ return Literal.from(value).toUrl();
15527
+ }
15528
+ return Literal.from(String(value)).toUrl();
15529
+ }
15530
+ /**
15531
+ * Derive the effective storage mode from a property's explicit options.
15532
+ * `resolveLanguage` is the sole selector and is NOT defaulted at the
15533
+ * decorator level:
15534
+ * - unset → deterministic typed literal (the perf default
15535
+ * for a plain `@Property()`)
15536
+ * - `"literal"` → signed envelope on the built-in literal language
15537
+ * (per-value provenance, e.g. Flux message bodies)
15538
+ * - `<custom address>` → signed expression on that custom language
15539
+ */
15540
+ function effectiveLiteralStorage(meta) {
15541
+ const lang = meta.resolveLanguage;
15542
+ if (lang === undefined)
15543
+ return { kind: "deterministic" };
15544
+ if (lang === "literal")
15545
+ return { kind: "envelope" };
15546
+ return { kind: "custom", language: lang };
15547
+ }
15548
+ /**
15549
+ * Determine if a property stores values as deterministic literal: IRIs (so WHERE
15550
+ * filters can match typed literals directly). Envelope / custom-language
15551
+ * properties resolve through expressions, and flag properties store raw URIs —
15552
+ * none is a deterministic literal.
15553
+ */
15554
+ function isLiteralStoredProperty(propMeta) {
15555
+ if (propMeta.flag)
15556
+ return false;
15557
+ return effectiveLiteralStorage(propMeta).kind === "deterministic";
15558
+ }
14627
15559
  /**
14628
15560
  * Escape a string for use as a SPARQL string literal.
14629
15561
  */
@@ -15164,11 +16096,11 @@ class ModelQueryBuilder {
15164
16096
  }
15165
16097
  const field = options?.field;
15166
16098
  if (typeof modelOrPredicate === 'string') {
15167
- // Raw predicate string → raw form of ParentScope
16099
+ // Raw predicate string → raw form of Scope
15168
16100
  this.queryParams.parent = { id, predicate: modelOrPredicate };
15169
16101
  }
15170
16102
  else if (typeof modelOrPredicate === 'function') {
15171
- // Model class → model form of ParentScope
16103
+ // Model class → model form of Scope
15172
16104
  this.queryParams.parent = { id, model: modelOrPredicate, ...(field && { field }) };
15173
16105
  }
15174
16106
  else if (typeof idOrInstance !== 'string') {
@@ -15728,6 +16660,110 @@ function normalizeValue(value) {
15728
16660
  * Rust endpoint. Recursively converts included relation values (which come
15729
16661
  * back as plain JSON objects) into proper model class instances.
15730
16662
  */
16663
+ /**
16664
+ * Key under which the executor returns a polymorphically-hydrated instance's
16665
+ * concrete class.
16666
+ *
16667
+ * Half of a wire contract: the writer is `SUBJECT_CLASS_KEY` in
16668
+ * `rust-executor/src/perspectives/model_query/relations.rs`, and the two are
16669
+ * separate literals in separate languages. Renaming one alone does not fail to
16670
+ * compile — it degrades to every instance staying plain JSON, which looks
16671
+ * identical to a relation that declared no classes to build.
16672
+ * `tests/js/tests/model/model-polymorphic.test.ts` drives both ends against one
16673
+ * executor, so the drift fails a test rather than a user's query.
16674
+ *
16675
+ * The executor also returns `__subjectClasses`, the whole set this one names the
16676
+ * head of. Nothing here reads it — it rides onto the instance with every other
16677
+ * JSON key, for a caller that wants to know a choice was made.
16678
+ */
16679
+ const SUBJECT_CLASS_KEY = '__subjectClass';
16680
+ /**
16681
+ * Turn on `polymorphic` for every relation that declares it, at every depth of
16682
+ * an include map.
16683
+ *
16684
+ * A relation being heterogeneous is a fact about the data, not about one query,
16685
+ * so the declaration lives on the model and the call site writes
16686
+ * `include: { children: true }`. That has to hold just as much one level down:
16687
+ * in `include: { posts: { include: { children: true } } }`, `children` is a
16688
+ * relation on `Post`, so the walk carries the class it is reading against down
16689
+ * with it. Without that, a nested include of an untyped polymorphic relation
16690
+ * reaches the executor with no shape to resolve and fails the query outright.
16691
+ *
16692
+ * An explicit `polymorphic: false` at any level still wins — `undefined` is the
16693
+ * only state the default fills in.
16694
+ *
16695
+ * The walk stops descending *through* a polymorphic relation, because there is
16696
+ * nothing to descend into: its targets are of several classes by definition, so
16697
+ * no single class's metadata could say what a deeper include means. The
16698
+ * executor resolves those nested includes against each concrete class instead.
16699
+ */
16700
+ function applyPolymorphicIncludeDefaults(includes, ctor) {
16701
+ const relMeta = getRelationsMetadata(ctor);
16702
+ for (const [relName, val] of Object.entries(includes)) {
16703
+ // `$`-prefixed keys are projections, not relations.
16704
+ if (relName.startsWith('$'))
16705
+ continue;
16706
+ const meta = relMeta[relName];
16707
+ if (!meta)
16708
+ continue;
16709
+ let subQuery = val;
16710
+ if (meta.polymorphic) {
16711
+ if (val === true) {
16712
+ subQuery = { polymorphic: true };
16713
+ includes[relName] = subQuery;
16714
+ }
16715
+ else if (typeof val === 'object' && val !== null && subQuery.polymorphic === undefined) {
16716
+ subQuery.polymorphic = true;
16717
+ }
16718
+ // The classes this call site can build are also the classes it wants its
16719
+ // targets read as, so the declaration answers both questions and the call
16720
+ // site repeats neither. Sent as part of the query rather than applied to
16721
+ // the results: a preference in the request is reproducible by anyone who
16722
+ // sends it, where one applied afterwards would make the same data read
16723
+ // differently depending on which classes the caller happened to import.
16724
+ //
16725
+ // It ranks and does not narrow — a target matching none of them still
16726
+ // arrives — so declaring what you can construct never costs you a member
16727
+ // of a relation that is heterogeneous by definition.
16728
+ if (typeof subQuery === 'object' &&
16729
+ subQuery !== null &&
16730
+ subQuery.polymorphic &&
16731
+ subQuery.preferClasses === undefined &&
16732
+ meta.instantiateAs) {
16733
+ const names = (meta.instantiateAs() ?? [])
16734
+ .map((cls) => cls?.className)
16735
+ .filter((name) => typeof name === 'string');
16736
+ if (names.length)
16737
+ subQuery.preferClasses = names;
16738
+ }
16739
+ }
16740
+ if (typeof subQuery !== 'object' || subQuery === null)
16741
+ continue;
16742
+ const nested = subQuery.include;
16743
+ if (!nested || subQuery.polymorphic)
16744
+ continue;
16745
+ // The thunk is only evaluated here, at query time, so a self-referential or
16746
+ // circularly-imported target that is not yet defined costs the nested
16747
+ // default rather than the whole query.
16748
+ let TargetClass;
16749
+ try {
16750
+ TargetClass = meta.target?.();
16751
+ }
16752
+ catch (e) {
16753
+ // A class not yet initialised throws `ReferenceError` from the temporal
16754
+ // dead zone, which is the expected cost of an import cycle and not worth
16755
+ // saying anything about. Anything else — a thunk closing over nothing,
16756
+ // typically — is a broken declaration that would otherwise cost the nested
16757
+ // default in silence, so it gets said out loud.
16758
+ const circularImport = e instanceof ReferenceError;
16759
+ const say = circularImport ? console.debug : console.warn;
16760
+ say(`prepareModelQueryParams: target class unavailable for include '${relName}':`, e);
16761
+ continue;
16762
+ }
16763
+ if (TargetClass)
16764
+ applyPolymorphicIncludeDefaults(nested, TargetClass);
16765
+ }
16766
+ }
15731
16767
  function jsonToModelInstance(ModelClass, perspective, json, include, properties) {
15732
16768
  const instance = new ModelClass(perspective, json.id || json.baseExpression);
15733
16769
  // When a properties projection is active, remove own properties set by the
@@ -15774,9 +16810,62 @@ function jsonToModelInstance(ModelClass, perspective, json, include, properties)
15774
16810
  if (!includeVal)
15775
16811
  continue;
15776
16812
  const meta = relMeta[relName];
15777
- if (!meta?.target)
16813
+ // A polymorphic relation may legitimately declare no target at all —
16814
+ // that is the case it exists for — so it must not be gated on one.
16815
+ if (!meta)
15778
16816
  continue;
15779
- const TargetClass = meta.target();
16817
+ if (!meta.target && !meta.polymorphic)
16818
+ continue;
16819
+ const TargetClass = meta.target?.();
16820
+ // For a polymorphic relation the executor sends each child's concrete
16821
+ // class back on the instance, because it had to know it in order to
16822
+ // hydrate against the right shape at all. What it cannot send is the
16823
+ // constructor, so `instantiateAs` names the classes this side can build
16824
+ // and the name → class map is derived from them: `@Model` records each
16825
+ // class's name on the class itself, so listing the classes and listing
16826
+ // their names would be the same list written twice, free to disagree.
16827
+ //
16828
+ // Built on first use rather than at decoration time, because the thunk
16829
+ // exists to be called late: a class defined further round a circular
16830
+ // import graph is not there yet when the decorator runs.
16831
+ let byClassName;
16832
+ // May resolve to nothing: a polymorphic relation is allowed to declare no
16833
+ // target at all, and the list may not name the class that arrived — it
16834
+ // says what this call site can construct, not what the relation may hold.
16835
+ // The item then stays plain JSON — correct data, carrying its class name
16836
+ // for a caller that wants to dispatch on it — rather than being forced
16837
+ // through a constructor that does not exist.
16838
+ const resolveChildClass = (item) => {
16839
+ if (!meta.polymorphic)
16840
+ return TargetClass;
16841
+ const concrete = item?.[SUBJECT_CLASS_KEY];
16842
+ // No concrete class means this was not read polymorphically after all —
16843
+ // an explicit `polymorphic: false` at the call site — so the relation's
16844
+ // own declared target is the right shape.
16845
+ if (typeof concrete !== 'string')
16846
+ return TargetClass;
16847
+ if (meta.instantiateAs) {
16848
+ if (!byClassName) {
16849
+ byClassName = {};
16850
+ for (const cls of meta.instantiateAs() ?? []) {
16851
+ const name = cls?.className;
16852
+ if (typeof name === 'string')
16853
+ byClassName[name] = cls;
16854
+ }
16855
+ }
16856
+ if (byClassName[concrete])
16857
+ return byClassName[concrete];
16858
+ }
16859
+ // The declared target is not a fallback, and having named no classes to
16860
+ // build does not make it one. Where a relation both declares a target
16861
+ // and reads polymorphically, a child of some third class was hydrated
16862
+ // against *its own* shape, so constructing the declared class over that
16863
+ // JSON produces an instance that answers `instanceof` for a class it is
16864
+ // not, carrying fields that class never declared — the exact
16865
+ // mislabelling polymorphic reads exist to prevent. It fits only when it
16866
+ // is the class the executor named.
16867
+ return TargetClass?.className === concrete ? TargetClass : undefined;
16868
+ };
15780
16869
  const nestedInclude = typeof includeVal === 'object' && includeVal !== null
15781
16870
  ? includeVal.include
15782
16871
  : undefined;
@@ -15786,14 +16875,18 @@ function jsonToModelInstance(ModelClass, perspective, json, include, properties)
15786
16875
  const raw = instance[relName];
15787
16876
  if (Array.isArray(raw)) {
15788
16877
  instance[relName] = raw.map((item) => {
15789
- if (typeof item === 'object' && item !== null && item.id) {
15790
- return jsonToModelInstance(TargetClass, perspective, item, nestedInclude, nestedProperties);
16878
+ const ChildClass = resolveChildClass(item);
16879
+ if (ChildClass && typeof item === 'object' && item !== null && item.id) {
16880
+ return jsonToModelInstance(ChildClass, perspective, item, nestedInclude, nestedProperties);
15791
16881
  }
15792
16882
  return item;
15793
16883
  });
15794
16884
  }
15795
16885
  else if (typeof raw === 'object' && raw !== null && raw.id) {
15796
- instance[relName] = jsonToModelInstance(TargetClass, perspective, raw, nestedInclude, nestedProperties);
16886
+ const ChildClass = resolveChildClass(raw);
16887
+ if (ChildClass) {
16888
+ instance[relName] = jsonToModelInstance(ChildClass, perspective, raw, nestedInclude, nestedProperties);
16889
+ }
15797
16890
  }
15798
16891
  }
15799
16892
  }
@@ -15820,12 +16913,28 @@ function jsonToModelInstance(ModelClass, perspective, json, include, properties)
15820
16913
  * // Define a recipe model
15821
16914
  * @Model({ name: "Recipe" })
15822
16915
  * class Recipe extends Ad4mModel {
15823
- * // Required property with literal value
16916
+ * // Plain property — no `resolveLanguage` → deterministic typed literal
16917
+ * // storage (fast POS-index path). This is the perf default.
16918
+ * @Property({ through: "recipe://name" })
16919
+ * name: string = "";
16920
+ *
16921
+ * // Property that needs per-value provenance (e.g. a signed message body):
16922
+ * // `resolveLanguage: "literal"` routes values through expression_create on
16923
+ * // the built-in literal language, producing a signed envelope URI
16924
+ * // (author/timestamp/proof) instead of a bare typed literal.
15824
16925
  * @Property({
15825
- * through: "recipe://name",
16926
+ * through: "recipe://signed_note",
15826
16927
  * resolveLanguage: "literal"
15827
16928
  * })
15828
- * name: string = "";
16929
+ * signedNote: string = "";
16930
+ *
16931
+ * // Property resolved through a custom language: values are routed through
16932
+ * // expression_create on that language (signed expression URIs).
16933
+ * @Optional({
16934
+ * through: "recipe://photo",
16935
+ * resolveLanguage: "QmFileStorageLanguageAddress..."
16936
+ * })
16937
+ * photo: string = "";
15829
16938
  *
15830
16939
  * // Optional property with custom initial value
15831
16940
  * @Optional({
@@ -15965,7 +17074,7 @@ class Ad4mModel {
15965
17074
  * ```typescript
15966
17075
  * @Model({ name: "Recipe" })
15967
17076
  * class Recipe extends Ad4mModel {
15968
- * @Property({ through: "recipe://name", resolveLanguage: "literal" })
17077
+ * @Property({ through: "recipe://name" })
15969
17078
  * name: string = "";
15970
17079
  *
15971
17080
  * @HasMany({ through: "recipe://ingredient" })
@@ -16025,6 +17134,7 @@ class Ad4mModel {
16025
17134
  ...(options.target !== undefined && { target: options.target }),
16026
17135
  ...(options.filter !== undefined && { filter: options.filter }),
16027
17136
  ...(options.where !== undefined && { where: options.where }),
17137
+ ...(options.ordering !== undefined && { ordering: options.ordering }),
16028
17138
  };
16029
17139
  }
16030
17140
  // Fallback: If both structures are empty but a JSON schema is attached, derive from it
@@ -16054,7 +17164,7 @@ class Ad4mModel {
16054
17164
  predicate: predicate,
16055
17165
  required: isRequired,
16056
17166
  readOnly: propertySchema["x-ad4m"]?.writable === false,
16057
- ...(propertySchema["x-ad4m"]?.resolveLanguage && { resolveLanguage: propertySchema["x-ad4m"].resolveLanguage }),
17167
+ ...(propertySchema["x-ad4m"]?.resolveLanguage !== undefined && { resolveLanguage: propertySchema["x-ad4m"].resolveLanguage }),
16058
17168
  ...(propertySchema["x-ad4m"]?.initial && { initial: propertySchema["x-ad4m"].initial }),
16059
17169
  ...(propertySchema["x-ad4m"]?.local !== undefined && { local: propertySchema["x-ad4m"].local })
16060
17170
  };
@@ -16073,7 +17183,9 @@ class Ad4mModel {
16073
17183
  *
16074
17184
  * @param perspective - The perspective where this model will be stored
16075
17185
  * @param baseExpression - Optional expression URI for this instance.
16076
- * If omitted, a random Literal URL is generated.
17186
+ * If omitted, a random `ad4m://obj/<id>` IRI is generated,
17187
+ * independent of any property content — this is what keeps
17188
+ * two instances with identical property values distinct.
16077
17189
  * @param source - Optional source expression this instance is linked to
16078
17190
  *
16079
17191
  * @example
@@ -16082,12 +17194,21 @@ class Ad4mModel {
16082
17194
  * const recipe = new Recipe(perspective);
16083
17195
  *
16084
17196
  * // Create with specific base expression
16085
- * const recipe = new Recipe(perspective, "literal:...");
17197
+ * const recipe = new Recipe(perspective, "ad4m://obj/existing-id");
16086
17198
  * ```
16087
17199
  */
16088
17200
  constructor(perspective, baseExpression) {
16089
17201
  this._snapshot = null;
16090
- this._baseExpression = baseExpression ? baseExpression : Literal.from(makeRandomId(24)).toUrl();
17202
+ // Use a dedicated `ad4m://obj/<id>` scheme for auto-generated
17203
+ // baseExpressions instead of `Literal.from(...).toUrl()`'s
17204
+ // `literal:string:<id>`. After typed-literal storage lands, the storage
17205
+ // layer translates any `literal:string:X` target into a typed
17206
+ // `"X"^^xsd:string` literal — which is correct for property values but
17207
+ // wrong for relation targets (which must remain NamedNode IRIs). Using
17208
+ // a distinct scheme keeps auto-generated instance IDs unambiguously
17209
+ // IRIs, so relation links like `<post> --has_comment--> <comment-id>`
17210
+ // round-trip correctly through the SPARQL store.
17211
+ this._baseExpression = baseExpression ? baseExpression : `ad4m://obj/${makeRandomId(24)}`;
16091
17212
  this._perspective = perspective;
16092
17213
  }
16093
17214
  /**
@@ -16281,10 +17402,22 @@ class Ad4mModel {
16281
17402
  const current = normalizeValue(this[field]);
16282
17403
  const original = this._snapshot[field];
16283
17404
  if (Array.isArray(current) || Array.isArray(original)) {
16284
- // Order-insensitive comparison (sorted) so reordering alone
16285
- // doesn't mark a relation as dirty.
16286
- const a = Array.isArray(current) ? [...current].sort() : [];
16287
- const b = Array.isArray(original) ? [...original].sort() : [];
17405
+ // For an ordered relation the sequence *is* the state, so a reorder is
17406
+ // the whole change and must mark the field dirty — sorting first would
17407
+ // make `save()` a no-op for the one edit the ordering feature exists to
17408
+ // support.
17409
+ //
17410
+ // Everything else compares order-insensitively, because an unordered
17411
+ // relation is a set: the executor returns its members by link timestamp,
17412
+ // and a caller who assigned the same members in another order has not
17413
+ // changed anything.
17414
+ const ordered = !!metadata.relations[field]?.ordering;
17415
+ const a = Array.isArray(current) ? [...current] : [];
17416
+ const b = Array.isArray(original) ? [...original] : [];
17417
+ if (!ordered) {
17418
+ a.sort();
17419
+ b.sort();
17420
+ }
16288
17421
  if (a.length !== b.length || a.some((v, i) => v !== b[i])) {
16289
17422
  changed.push(field);
16290
17423
  }
@@ -16424,8 +17557,17 @@ class Ad4mModel {
16424
17557
  normalIncludes[key] = val;
16425
17558
  }
16426
17559
  }
16427
- if (Object.keys(normalIncludes).length > 0)
17560
+ // A relation declared `polymorphic` reads that way by default, so the
17561
+ // caller writes `include: { children: true }` and still gets each child
17562
+ // hydrated as the class it actually is. Declaring it on the model rather
17563
+ // than repeating it at every call site is the point — the relation being
17564
+ // heterogeneous is a fact about the data, not about one query — but an
17565
+ // explicit `polymorphic: false` at the call site still wins. Applied at
17566
+ // every depth, since a nested include is a fact about the data too.
17567
+ if (Object.keys(normalIncludes).length > 0) {
17568
+ applyPolymorphicIncludeDefaults(normalIncludes, this);
16428
17569
  queryInput.include = normalIncludes;
17570
+ }
16429
17571
  if (Object.keys(projections).length > 0) {
16430
17572
  // Tag each projection with its target class name so the executor can
16431
17573
  // resolve the target shape through its in-memory cache when applying
@@ -16491,11 +17633,11 @@ class Ad4mModel {
16491
17633
  *
16492
17634
  * @internal
16493
17635
  */
16494
- static async executeModelQuery(perspective, query = {}, classNameOverride) {
17636
+ static async executeModelQuery(perspective, query = {}, classNameOverride, options) {
16495
17637
  // Delegate query input building to the shared prepareModelQueryParams
16496
17638
  // helper. The executor resolves the shape from SHACL server-side.
16497
17639
  const { className, queryJson } = this.prepareModelQueryParams(query, classNameOverride);
16498
- const result = await perspective.modelQuery(className, queryJson);
17640
+ const result = await perspective.modelQuery(className, queryJson, options);
16499
17641
  // Convert JSON instances to model class instances, recursively constructing
16500
17642
  // class instances for any included relations resolved by Rust.
16501
17643
  const instances = result.instances.map((json) => {
@@ -16536,12 +17678,12 @@ class Ad4mModel {
16536
17678
  * });
16537
17679
  * ```
16538
17680
  */
16539
- static async findAll(perspective, query) {
17681
+ static async findAll(perspective, query, options) {
16540
17682
  const q = (query ?? {});
16541
17683
  if (q.properties && q.properties.length === 0) {
16542
17684
  throw new Error("properties[] must not be empty — omit the field to return all properties, or specify at least one field name");
16543
17685
  }
16544
- const { results } = await this.executeModelQuery(perspective, q);
17686
+ const { results } = await this.executeModelQuery(perspective, q, undefined, options);
16545
17687
  return results;
16546
17688
  }
16547
17689
  /**
@@ -16564,9 +17706,9 @@ class Ad4mModel {
16564
17706
  * }
16565
17707
  * ```
16566
17708
  */
16567
- static async findOne(perspective, query) {
17709
+ static async findOne(perspective, query, options) {
16568
17710
  const limitedQuery = { ...(query ?? {}), limit: 1 };
16569
- const results = await this.findAll(perspective, limitedQuery);
17711
+ const results = await this.findAll(perspective, limitedQuery, options);
16570
17712
  return results[0] ?? null;
16571
17713
  }
16572
17714
  /**
@@ -16586,8 +17728,8 @@ class Ad4mModel {
16586
17728
  * console.log(`Showing 10 of ${totalCount} dessert recipes`);
16587
17729
  * ```
16588
17730
  */
16589
- static async findAllAndCount(perspective, query) {
16590
- const out = await this.executeModelQuery(perspective, (query ?? {}));
17731
+ static async findAllAndCount(perspective, query, options) {
17732
+ const out = await this.executeModelQuery(perspective, (query ?? {}), undefined, options);
16591
17733
  return out;
16592
17734
  }
16593
17735
  /**
@@ -16607,9 +17749,9 @@ class Ad4mModel {
16607
17749
  * console.log(`Page ${page.pageNumber} of recipes, ${page.results.length} items`);
16608
17750
  * ```
16609
17751
  */
16610
- static async paginate(perspective, pageSize, pageNumber, query) {
17752
+ static async paginate(perspective, pageSize, pageNumber, query, options) {
16611
17753
  const paginationQuery = { ...(query ?? {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
16612
- const { results, totalCount } = await this.executeModelQuery(perspective, paginationQuery);
17754
+ const { results, totalCount } = await this.executeModelQuery(perspective, paginationQuery, undefined, options);
16613
17755
  return { results: results, totalCount, pageSize, pageNumber };
16614
17756
  }
16615
17757
  /**
@@ -16637,8 +17779,8 @@ class Ad4mModel {
16637
17779
  * });
16638
17780
  * ```
16639
17781
  */
16640
- static async count(perspective, query) {
16641
- const { totalCount } = await this.executeModelQuery(perspective, { ...(query ?? {}), limit: 0 });
17782
+ static async count(perspective, query, options) {
17783
+ const { totalCount } = await this.executeModelQuery(perspective, { ...(query ?? {}), limit: 0 }, undefined, options);
16642
17784
  return totalCount;
16643
17785
  }
16644
17786
  async setProperty(key, value, batchId) {
@@ -16649,14 +17791,22 @@ class Ad4mModel {
16649
17791
  }
16650
17792
  // Generate actions from metadata (replaces Prolog query)
16651
17793
  const actions = this.generatePropertySetterAction(key, metadata);
16652
- // Get resolve language from metadata (replaces Prolog query)
16653
- let resolveLanguage = metadata.resolveLanguage;
16654
17794
  // Skip storing empty/null/undefined values to avoid invalid empty literals (e.g. literal:string:)
16655
17795
  if (value === undefined || value === null || value === "") {
16656
17796
  return;
16657
17797
  }
16658
- if (resolveLanguage) {
16659
- value = await this._perspective.createExpression(value, resolveLanguage);
17798
+ const mode = effectiveLiteralStorage(metadata);
17799
+ if (mode.kind === "custom") {
17800
+ // Custom language: route through expression_create on that language.
17801
+ value = await this._perspective.createExpression(value, mode.language);
17802
+ }
17803
+ else if (mode.kind === "envelope") {
17804
+ // Built-in literal language: signed-envelope expression (provenance).
17805
+ value = await this._perspective.createExpression(value, "literal");
17806
+ }
17807
+ else {
17808
+ // Deterministic literal: IRI (POS-index friendly).
17809
+ value = valueToLiteralIri(value);
16660
17810
  }
16661
17811
  await this._perspective.executeAction(actions, this._baseExpression, [{ name: "value", value }], batchId);
16662
17812
  }
@@ -16775,41 +17925,41 @@ class Ad4mModel {
16775
17925
  // entirely and let innerUpdate write the links directly.
16776
17926
  const metadata = this.constructor.getModelMetadata();
16777
17927
  const hasConstructor = Object.values(metadata.properties).some((p) => p.required || p.flag || p.initial !== undefined);
16778
- // Track properties that have resolveLanguage (non-literal) so they can be
16779
- // set via setProperty after createSubject (which doesn't resolve languages).
16780
- const deferredResolveLanguageProps = [];
17928
+ // Track properties resolved through expression_create — a signed literal
17929
+ // envelope or a custom (non-"literal") resolveLanguage. These may fail
17930
+ // inside a batch context, so defer them to setProperty after createSubject.
17931
+ const deferredExpressionProps = [];
16781
17932
  if (hasConstructor) {
16782
- // First filter out the properties that are not relations (arrays)
16783
17933
  const initialValues = {};
16784
17934
  for (const [key, value] of Object.entries(this)) {
16785
17935
  if (value !== undefined && value !== null && !(Array.isArray(value) && value.length > 0) && !value?.action) {
16786
- // Check if this property requires language resolution (e.g. file storage).
16787
- // If so, resolve the expression *before* passing to createSubject so
16788
- // the constructor receives a valid URI instead of raw data.
16789
17936
  const propMeta = metadata.properties[key];
16790
- if (propMeta?.resolveLanguage && propMeta.resolveLanguage !== 'literal' && typeof value === 'object') {
16791
- // Defer these properties — they need createExpression which may
16792
- // fail inside a batch context on some languages. We'll set them
16793
- // via setProperty after createSubject.
16794
- deferredResolveLanguageProps.push(key);
17937
+ // Only offer keys with a declared, settable model property. This
17938
+ // excludes ORM bookkeeping fields (_baseExpression, _perspective —
17939
+ // enumerable instance fields, not model properties), HasMany
17940
+ // relations (tracked in a separate registry, never in
17941
+ // `metadata.properties`), and read-only properties/flags
17942
+ // (readOnly: true). None of these have an `ad4m://setter` on the
17943
+ // Rust side, which otherwise logs a "declares no setter" warning
17944
+ // per key on every save().
17945
+ if (!propMeta || propMeta.readOnly) {
17946
+ continue;
17947
+ }
17948
+ if (effectiveLiteralStorage(propMeta).kind !== "deterministic") {
17949
+ deferredExpressionProps.push(key);
16795
17950
  continue;
16796
17951
  }
16797
17952
  initialValues[key] = value;
16798
17953
  }
16799
17954
  }
16800
- // Get the class name instead of passing the instance to avoid Prolog query generation
16801
17955
  const className = await this.perspective.stringOrTemplateObjectToSubjectClassName(this);
16802
- // Create the subject with the initial values
16803
17956
  await this.perspective.createSubject(className, this._baseExpression, initialValues, batchId);
16804
17957
  }
16805
17958
  // Set properties and relations via innerUpdate.
16806
17959
  // When createSubject was skipped (no constructor actions), we must enable
16807
17960
  // property writing so that scalar values are persisted as links.
16808
17961
  await this.innerUpdate(!hasConstructor, batchId);
16809
- // Now handle any deferred resolveLanguage properties that were excluded
16810
- // from initialValues. setProperty will call createExpression to upload
16811
- // the data to the appropriate language and store the resulting URI.
16812
- for (const key of deferredResolveLanguageProps) {
17962
+ for (const key of deferredExpressionProps) {
16813
17963
  const value = this[key];
16814
17964
  if (value !== undefined && value !== null) {
16815
17965
  await this.setProperty(key, value, batchId);
@@ -16904,13 +18054,36 @@ class Ad4mModel {
16904
18054
  await this.setRelationValues(key, value, batchId);
16905
18055
  }
16906
18056
  else if (value !== undefined && value !== null && value !== "") {
18057
+ // A scalar handed to a relation field is a single-member relation.
18058
+ //
18059
+ // This used to `continue` — "Skip, it's a relation, not a regular
18060
+ // property" — so `Model.create(p, { source: 'uri://x' })` typechecked,
18061
+ // ran, resolved, and wrote no link. The record was created with the
18062
+ // relation empty and nothing anywhere said so, which surfaces later as
18063
+ // a *reader* complaining about a malformed instance: a Relationship
18064
+ // with no endpoints, a Placement pointing at nothing. Both look like
18065
+ // rendering bugs from the outside, because the record exists and the
18066
+ // thing that should reference it does not.
18067
+ //
18068
+ // The array form is the documented path and stays correct; the problem
18069
+ // is that the scalar form is plausible, typechecks against a field
18070
+ // declared `string`, and fails silently. Coercing matches what a caller
18071
+ // reaching for it meant. A value `setRelationValues` cannot use now
18072
+ // fails there, loudly, instead of vanishing here.
18073
+ //
18074
+ // Deliberately outside the `setProperties` gate, mirroring the array
18075
+ // branch above. `create` passes `setProperties: false` when the class
18076
+ // has a constructor, because `create_subject` writes the values map —
18077
+ // but a relation carries `ad4m://adder`, not `ad4m://setter`, so
18078
+ // `create_subject` drops it (see the warning added in 3ee2b5bc6).
18079
+ // Relations have to be written here in both cases or they are lost by
18080
+ // both paths at once.
18081
+ const relationMeta = this.getRelationOptions(key);
18082
+ if (relationMeta) {
18083
+ await this.setRelationValues(key, [value], batchId);
18084
+ continue;
18085
+ }
16907
18086
  if (setProperties) {
16908
- // Check if this is a relation property (has relation metadata)
16909
- const relationMeta = this.getRelationOptions(key);
16910
- if (relationMeta) {
16911
- // Skip - it's a relation, not a regular property
16912
- continue;
16913
- }
16914
18087
  // Skip flag properties — they are immutable after creation
16915
18088
  const propMeta = this.getPropertyMetadata(key);
16916
18089
  if (propMeta?.flag) {
@@ -17104,7 +18277,7 @@ class Ad4mModel {
17104
18277
  * @param perspective - The perspective to create the instance in
17105
18278
  * @param data - Property values to assign before saving
17106
18279
  * @param options - Optional settings:
17107
- * - `parent` — a `ParentScope` (model form or raw form) whose `id` will
18280
+ * - `parent` — a `Scope` (model form or raw form) whose `id` will
17108
18281
  * be used to create an incoming link from the parent to the new instance.
17109
18282
  * - `batchId` — an existing batch id; when provided the link write and
17110
18283
  * `save()` are added to the batch instead of committed immediately.
@@ -17336,8 +18509,7 @@ class Ad4mModel {
17336
18509
  * // With explicit configuration
17337
18510
  * const PersonClass = Ad4mModel.fromJSONSchema(schema, {
17338
18511
  * name: "Person",
17339
- * namespace: "person://",
17340
- * resolveLanguage: "literal"
18512
+ * namespace: "person://"
17341
18513
  * });
17342
18514
  *
17343
18515
  * // With property mapping
@@ -17741,24 +18913,33 @@ class PerspectiveHandle {
17741
18913
  * const runs = await InterpretationRun.findAll(perspective);
17742
18914
  * const configs = await AutoProcessorConfig.findAll(perspective);
17743
18915
  */
17744
- var __decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
18916
+ var __decorate$1 = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
17745
18917
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
17746
18918
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
17747
18919
  else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
17748
18920
  return c > 3 && r && Object.defineProperty(target, key, r), r;
17749
18921
  };
17750
- var __metadata = (undefined && undefined.__metadata) || function (k, v) {
18922
+ var __metadata$1 = (undefined && undefined.__metadata) || function (k, v) {
17751
18923
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
17752
18924
  };
17753
18925
  // ── AutoProcessorConfig ─────────────────────────────────────────────────────
17754
18926
  // Mirrors the Rust `auto_processor::config::AutoProcessorConfig` SDNA.
17755
18927
  // One node per registered processor; the node URI is
17756
18928
  // `ad4m://autoprocessor/<processorId>`.
18929
+ // Model name = "AutoProcessor" (NOT "AutoProcessorConfig") to match the Rust
18930
+ // hardwired subject class in `perspectives/auto_processor/config.rs` — that
18931
+ // alignment is what the SDNA parity test in
18932
+ // `tests/js/tests/model/interpretation-models.test.ts` guards. The TS class
18933
+ // symbol keeps the `Config` suffix for readability (`AutoProcessorConfig` reads
18934
+ // better than a bare `AutoProcessor` for an "instances of the config record"
18935
+ // query), but the on-graph subject class it registers is `AutoProcessor`.
17757
18936
  exports.AutoProcessorConfig = class AutoProcessorConfig extends Ad4mModel {
17758
18937
  constructor() {
17759
18938
  super(...arguments);
17760
- this.type = "ad4m://AutoProcessor";
17761
18939
  /** Unique processor id — the dedup key for auto-processor instances. */
18940
+ // First-declared property: `buildSHACL` derives the shape namespace from
18941
+ // its `through` prefix, so `ad4m://processor_id` → `ad4m://` → target_class
18942
+ // `ad4m://AutoProcessor` (matches Rust `AUTO_PROCESSOR_TARGET_CLASS`).
17762
18943
  this.processorId = "";
17763
18944
  /** SPARQL SELECT that gathers source items each pass. */
17764
18945
  this.sourceScopeQuery = "";
@@ -17770,105 +18951,130 @@ exports.AutoProcessorConfig = class AutoProcessorConfig extends Ad4mModel {
17770
18951
  this.batchMax = "32";
17771
18952
  /** How long a won claim is authoritative before peers may re-claim (ms). */
17772
18953
  this.claimTtlMs = "60000";
18954
+ // No `@Flag` type discriminator (Nico 2026-08-19: "type flags are an
18955
+ // anti-pattern for subject classes; match over all the properties
18956
+ // instead"). Conformance is by the presence of `processorId` +
18957
+ // `sourceScopeQuery` + `interpretationClasses` + `debounceMs` +
18958
+ // `batchMax` + `claimTtlMs` — the Rust SDNA takes the same shape.
17773
18959
  }
17774
18960
  };
17775
- __decorate([
17776
- Flag({ through: "rdf://type", value: "ad4m://AutoProcessor" }),
17777
- __metadata("design:type", String)
17778
- ], exports.AutoProcessorConfig.prototype, "type", void 0);
17779
- __decorate([
18961
+ __decorate$1([
17780
18962
  Property({ through: "ad4m://processor_id", required: true, identity: true }),
17781
- __metadata("design:type", String)
18963
+ __metadata$1("design:type", String)
17782
18964
  ], exports.AutoProcessorConfig.prototype, "processorId", void 0);
17783
- __decorate([
18965
+ __decorate$1([
17784
18966
  Property({ through: "ad4m://source_scope_query", required: true }),
17785
- __metadata("design:type", String)
18967
+ __metadata$1("design:type", String)
17786
18968
  ], exports.AutoProcessorConfig.prototype, "sourceScopeQuery", void 0);
17787
- __decorate([
17788
- Optional({ through: "ad4m://base_prefix", resolveLanguage: "literal" }),
17789
- __metadata("design:type", String)
18969
+ __decorate$1([
18970
+ Optional({ through: "ad4m://base_prefix" }),
18971
+ __metadata$1("design:type", String)
17790
18972
  ], exports.AutoProcessorConfig.prototype, "basePrefix", void 0);
17791
- __decorate([
17792
- HasMany({ through: "ad4m://interpretation_class" }),
17793
- __metadata("design:type", Array)
18973
+ __decorate$1([
18974
+ HasMany({ through: "ad4m://interpretation_class", datatype: "xsd:string" }),
18975
+ __metadata$1("design:type", Array)
17794
18976
  ], exports.AutoProcessorConfig.prototype, "interpretationClasses", void 0);
17795
- __decorate([
18977
+ __decorate$1([
17796
18978
  Property({ through: "ad4m://debounce_ms", required: true }),
17797
- __metadata("design:type", String)
18979
+ __metadata$1("design:type", String)
17798
18980
  ], exports.AutoProcessorConfig.prototype, "debounceMs", void 0);
17799
- __decorate([
17800
- Optional({ through: "ad4m://batch_min", resolveLanguage: "literal" }),
17801
- __metadata("design:type", String)
18981
+ __decorate$1([
18982
+ Optional({ through: "ad4m://batch_min" }),
18983
+ __metadata$1("design:type", String)
17802
18984
  ], exports.AutoProcessorConfig.prototype, "batchMin", void 0);
17803
- __decorate([
18985
+ __decorate$1([
17804
18986
  Property({ through: "ad4m://batch_max", required: true }),
17805
- __metadata("design:type", String)
18987
+ __metadata$1("design:type", String)
17806
18988
  ], exports.AutoProcessorConfig.prototype, "batchMax", void 0);
17807
- __decorate([
17808
- Optional({ through: "ad4m://max_wait_ms", resolveLanguage: "literal" }),
17809
- __metadata("design:type", String)
18989
+ __decorate$1([
18990
+ Optional({ through: "ad4m://max_wait_ms" }),
18991
+ __metadata$1("design:type", String)
17810
18992
  ], exports.AutoProcessorConfig.prototype, "maxWaitMs", void 0);
17811
- __decorate([
18993
+ __decorate$1([
17812
18994
  Property({ through: "ad4m://claim_ttl_ms", required: true }),
17813
- __metadata("design:type", String)
18995
+ __metadata$1("design:type", String)
17814
18996
  ], exports.AutoProcessorConfig.prototype, "claimTtlMs", void 0);
17815
- __decorate([
17816
- Optional({ through: "ad4m://source_window_ms", resolveLanguage: "literal" }),
17817
- __metadata("design:type", String)
18997
+ __decorate$1([
18998
+ Optional({ through: "ad4m://source_window_ms" }),
18999
+ __metadata$1("design:type", String)
17818
19000
  ], exports.AutoProcessorConfig.prototype, "sourceWindowMs", void 0);
17819
- __decorate([
17820
- Optional({ through: "ad4m://dedup_strategy", resolveLanguage: "literal" }),
17821
- __metadata("design:type", String)
19001
+ __decorate$1([
19002
+ Optional({ through: "ad4m://dedup_strategy" }),
19003
+ __metadata$1("design:type", String)
17822
19004
  ], exports.AutoProcessorConfig.prototype, "dedupStrategy", void 0);
17823
- exports.AutoProcessorConfig = __decorate([
17824
- Model$1({ name: "AutoProcessorConfig" })
19005
+ __decorate$1([
19006
+ Optional({ through: "ad4m://existing_scope" }),
19007
+ __metadata$1("design:type", String)
19008
+ ], exports.AutoProcessorConfig.prototype, "existingScope", void 0);
19009
+ __decorate$1([
19010
+ Optional({ through: "ad4m://mint_scope" }),
19011
+ __metadata$1("design:type", String)
19012
+ ], exports.AutoProcessorConfig.prototype, "mintScope", void 0);
19013
+ __decorate$1([
19014
+ Optional({ through: "ad4m://max_tool_calls" }),
19015
+ __metadata$1("design:type", String)
19016
+ ], exports.AutoProcessorConfig.prototype, "maxToolCalls", void 0);
19017
+ __decorate$1([
19018
+ Optional({ through: "ad4m://emit_debug_events", resolveLanguage: "literal" }),
19019
+ __metadata$1("design:type", String)
19020
+ ], exports.AutoProcessorConfig.prototype, "emitDebugEvents", void 0);
19021
+ exports.AutoProcessorConfig = __decorate$1([
19022
+ Model$1({ name: "AutoProcessor" })
17825
19023
  ], exports.AutoProcessorConfig);
17826
19024
  // ── InterpretationRun ───────────────────────────────────────────────────────
17827
19025
  // Mirrors the Rust `interpretation::overlay::InterpretationRun` SDNA.
17828
19026
  // One node per completed pass; the node URI is `ad4m://interp/run/<runId>`.
17829
19027
  exports.InterpretationRun = class InterpretationRun extends Ad4mModel {
17830
19028
  constructor() {
19029
+ // No `@Flag` type discriminator — Rust SDNA drops `ad4m://type` too.
19030
+ // Conformance is by `runId` (identity) — same pattern
19031
+ // `InterpretationOverlay` already uses (`kind` is its discriminator).
17831
19032
  super(...arguments);
17832
- this.type = "ad4m://interpretation-run";
17833
19033
  /** UUID for this run — the dedup key across run nodes. */
17834
19034
  this.runId = "";
17835
19035
  /**
17836
19036
  * Source item IDs consumed by this pass.
17837
19037
  * Stored as multiple links with the same predicate; the processed-turn
17838
- * cursor uses these to avoid re-interpreting a turn.
19038
+ * cursor uses these to avoid re-interpreting a turn. Values are plain
19039
+ * strings (turn hex), so the property opts into `sh:datatype`-gated
19040
+ * literal decoding on hydration.
17839
19041
  */
17840
19042
  this.sources = [];
17841
19043
  }
17842
19044
  };
17843
- __decorate([
17844
- Flag({ through: "ad4m://type", value: "ad4m://interpretation-run" }),
17845
- __metadata("design:type", String)
17846
- ], exports.InterpretationRun.prototype, "type", void 0);
17847
- __decorate([
19045
+ __decorate$1([
17848
19046
  Property({ through: "ad4m://interp/run_id", required: true, identity: true }),
17849
- __metadata("design:type", String)
19047
+ __metadata$1("design:type", String)
17850
19048
  ], exports.InterpretationRun.prototype, "runId", void 0);
17851
- __decorate([
17852
- Optional({ through: "ad4m://interp/model", resolveLanguage: "literal" }),
17853
- __metadata("design:type", String)
19049
+ __decorate$1([
19050
+ Optional({ through: "ad4m://interp/model" }),
19051
+ __metadata$1("design:type", String)
17854
19052
  ], exports.InterpretationRun.prototype, "model", void 0);
17855
- __decorate([
17856
- Optional({ through: "ad4m://interp/prompt_version", resolveLanguage: "literal" }),
17857
- __metadata("design:type", String)
19053
+ __decorate$1([
19054
+ Optional({ through: "ad4m://interp/prompt_version" }),
19055
+ __metadata$1("design:type", String)
17858
19056
  ], exports.InterpretationRun.prototype, "promptVersion", void 0);
17859
- __decorate([
17860
- Optional({ through: "ad4m://interp/ran_at", resolveLanguage: "literal" }),
17861
- __metadata("design:type", String)
19057
+ __decorate$1([
19058
+ Optional({ through: "ad4m://interp/ran_at" }),
19059
+ __metadata$1("design:type", String)
17862
19060
  ], exports.InterpretationRun.prototype, "ranAt", void 0);
17863
- __decorate([
17864
- Optional({ through: "ad4m://interp/processor", resolveLanguage: "literal" }),
17865
- __metadata("design:type", String)
19061
+ __decorate$1([
19062
+ Optional({ through: "ad4m://interp/processor" }),
19063
+ __metadata$1("design:type", String)
17866
19064
  ], exports.InterpretationRun.prototype, "processor", void 0);
17867
- __decorate([
17868
- HasMany({ through: "ad4m://interp/sources" }),
17869
- __metadata("design:type", Array)
19065
+ __decorate$1([
19066
+ HasMany({ through: "ad4m://interp/sources", datatype: "xsd:string" }),
19067
+ __metadata$1("design:type", Array)
17870
19068
  ], exports.InterpretationRun.prototype, "sources", void 0);
17871
- exports.InterpretationRun = __decorate([
19069
+ __decorate$1([
19070
+ Optional({ through: "ad4m://interp/debug_prompt", resolveLanguage: "literal" }),
19071
+ __metadata$1("design:type", String)
19072
+ ], exports.InterpretationRun.prototype, "debugPrompt", void 0);
19073
+ __decorate$1([
19074
+ Optional({ through: "ad4m://interp/debug_response", resolveLanguage: "literal" }),
19075
+ __metadata$1("design:type", String)
19076
+ ], exports.InterpretationRun.prototype, "debugResponse", void 0);
19077
+ exports.InterpretationRun = __decorate$1([
17872
19078
  Model$1({ name: "InterpretationRun" })
17873
19079
  ], exports.InterpretationRun);
17874
19080
  // ── InterpretationOverlay ───────────────────────────────────────────────────
@@ -17898,18 +19104,531 @@ exports.InterpretationOverlay = class InterpretationOverlay extends Ad4mModel {
17898
19104
  this.kind = "";
17899
19105
  }
17900
19106
  };
17901
- __decorate([
17902
- Property({ through: "ad4m://interp/kind", required: true, resolveLanguage: "literal" }),
17903
- __metadata("design:type", String)
19107
+ __decorate$1([
19108
+ Property({ through: "ad4m://interp/kind", required: true }),
19109
+ __metadata$1("design:type", String)
17904
19110
  ], exports.InterpretationOverlay.prototype, "kind", void 0);
17905
- __decorate([
17906
- Optional({ through: "ad4m://interp/run", resolveLanguage: "literal" }),
17907
- __metadata("design:type", String)
19111
+ __decorate$1([
19112
+ Optional({ through: "ad4m://interp/run" }),
19113
+ __metadata$1("design:type", String)
17908
19114
  ], exports.InterpretationOverlay.prototype, "run", void 0);
17909
- exports.InterpretationOverlay = __decorate([
19115
+ exports.InterpretationOverlay = __decorate$1([
17910
19116
  Model$1({ name: "InterpretationOverlay" })
17911
19117
  ], exports.InterpretationOverlay);
17912
19118
 
19119
+ /**
19120
+ * TypeScript @Model classes mirroring the Rust-side hardwired SDNA for the
19121
+ * flow runtime. Apps can import these to query the perspective graph for
19122
+ * pending flow-transition proposals without knowing the raw link predicates.
19123
+ *
19124
+ * Registration:
19125
+ * await FlowTransitionProposal.register(perspective);
19126
+ *
19127
+ * Querying:
19128
+ * const pending = await FlowTransitionProposal.findAll(perspective);
19129
+ *
19130
+ * Slice 5/7 of the flow-implementation arc (design doc §4.2). The Rust
19131
+ * engine does not yet mint these — that lands with the consensus firing
19132
+ * work in a later PR arc. This class defines the on-graph shape so:
19133
+ * - clients can build UI over proposals immediately (Deliberation demo);
19134
+ * - the SDNA-parity test locks TS/Rust drift the moment the JSON exists
19135
+ * (`rust-executor/src/perspectives/hardwired_sdna/flow_transition_proposal.json`);
19136
+ * - the engine can start writing into this shape when consensus lands
19137
+ * without touching the client-side surface.
19138
+ */
19139
+ var __decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
19140
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
19141
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
19142
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
19143
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
19144
+ };
19145
+ var __metadata = (undefined && undefined.__metadata) || function (k, v) {
19146
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
19147
+ };
19148
+ // ── FlowTransitionProposal ──────────────────────────────────────────────────
19149
+ // Mirrors the Rust hardwired `flow_transition_proposal.json` SDNA (once wired
19150
+ // on the engine side; see file header). One node per proposed transition; the
19151
+ // URI is `ad4m://flow/proposal/<uuid>` when the engine mints it, but the class
19152
+ // carries no URI-format constraint — apps constructing proposals directly may
19153
+ // choose any URI they can defend as unique.
19154
+ exports.FlowTransitionProposal = class FlowTransitionProposal extends Ad4mModel {
19155
+ constructor() {
19156
+ super(...arguments);
19157
+ /**
19158
+ * URI of the running `FlowInstance` this proposal targets. First-declared
19159
+ * property so `buildSHACL` derives the shape namespace from its `through`
19160
+ * prefix — `ad4m://flow/instance` → `ad4m://` → target_class
19161
+ * `ad4m://FlowTransitionProposal`. Also the identity predicate: the
19162
+ * discriminator `findAll` uses to isolate proposal nodes.
19163
+ */
19164
+ this.flowInstance = "";
19165
+ /** Name of the state the flow instance is currently in. */
19166
+ this.fromState = "";
19167
+ /** Name of the state the proposal wants to transition to. */
19168
+ this.toState = "";
19169
+ /** DID of the agent that issued the proposal. */
19170
+ this.proposer = "";
19171
+ /**
19172
+ * URIs of instances offered as evidence that `toState.requires` is now
19173
+ * satisfied. Multiple links, one per cited instance; ordering is not
19174
+ * significant.
19175
+ */
19176
+ this.evidence = [];
19177
+ /**
19178
+ * JSON blob: `{ [uri]: sha256_hex }` — one entry per evidence URI, hashing
19179
+ * the canonicalized graph-visible properties (sorted by property URI,
19180
+ * multi-values sorted lexicographically) at proposal time. Downstream
19181
+ * verifiers use it to detect edits to cited instances after the proposal
19182
+ * was written. Stored as an opaque string because SHACL properties carry
19183
+ * no rich-object type; the engine parses it back into a map.
19184
+ */
19185
+ this.evidenceHashes = "";
19186
+ // "When was this proposal written?" is answered by `Ad4mModel`'s built-in
19187
+ // `createdAt`, synthesized on hydration from the earliest link timestamp
19188
+ // of the proposal's own links (all written together during create_subject).
19189
+ }
19190
+ };
19191
+ __decorate([
19192
+ Property({ through: "ad4m://flow/instance", required: true, identity: true }),
19193
+ __metadata("design:type", String)
19194
+ ], exports.FlowTransitionProposal.prototype, "flowInstance", void 0);
19195
+ __decorate([
19196
+ Property({ through: "ad4m://flow/from_state", required: true }),
19197
+ __metadata("design:type", String)
19198
+ ], exports.FlowTransitionProposal.prototype, "fromState", void 0);
19199
+ __decorate([
19200
+ Property({ through: "ad4m://flow/to_state", required: true }),
19201
+ __metadata("design:type", String)
19202
+ ], exports.FlowTransitionProposal.prototype, "toState", void 0);
19203
+ __decorate([
19204
+ Property({ through: "ad4m://flow/proposer", required: true }),
19205
+ __metadata("design:type", String)
19206
+ ], exports.FlowTransitionProposal.prototype, "proposer", void 0);
19207
+ __decorate([
19208
+ HasMany({ through: "ad4m://flow/evidence", datatype: "xsd:string" }),
19209
+ __metadata("design:type", Array)
19210
+ ], exports.FlowTransitionProposal.prototype, "evidence", void 0);
19211
+ __decorate([
19212
+ Property({ through: "ad4m://flow/evidence_hashes", required: true }),
19213
+ __metadata("design:type", String)
19214
+ ], exports.FlowTransitionProposal.prototype, "evidenceHashes", void 0);
19215
+ __decorate([
19216
+ Optional({ through: "ad4m://flow/run_uri" }),
19217
+ __metadata("design:type", String)
19218
+ ], exports.FlowTransitionProposal.prototype, "runUri", void 0);
19219
+ __decorate([
19220
+ Optional({ through: "ad4m://flow/rationale" }),
19221
+ __metadata("design:type", String)
19222
+ ], exports.FlowTransitionProposal.prototype, "rationale", void 0);
19223
+ exports.FlowTransitionProposal = __decorate([
19224
+ Model$1({ name: "FlowTransitionProposal" })
19225
+ ], exports.FlowTransitionProposal);
19226
+ // ── FlowInstanceRecord ──────────────────────────────────────────────────────
19227
+ // On-graph node minted by the engine when a flow is started on a specific
19228
+ // base expression. Its URI is the value that `FlowTransitionProposal.flowInstance`
19229
+ // references. Mirrors `rust-executor/src/perspectives/hardwired_sdna/flow_instance.json`.
19230
+ //
19231
+ // Design authority: `docs/flow-interpretation-hints-design.md` §4.3.
19232
+ //
19233
+ // This class is the raw on-graph record (@Model over the SDNA shape). The
19234
+ // object-oriented handle callers work with is `FlowInstance` in
19235
+ // `./FlowInstance.ts` — it wraps `FlowInstanceRecord + SHACLFlow definition`
19236
+ // and exposes `currentState`, `availableTransitions`, `proposals`, etc.
19237
+ // Renamed from `FlowInstance` → `FlowInstanceRecord` on 2026-08-27 per
19238
+ // Nico's PR #929 review R2 (the `FlowInstance` name is reserved for the
19239
+ // wrapper the design has always specified in §4.3).
19240
+ //
19241
+ // The SDNA name (`@Model({ name: "FlowInstance" })`) stays unchanged — that
19242
+ // keys the on-graph class, not the TS export. Renaming the TS class only
19243
+ // changes the JS import surface; the graph shape is identical, and Rust
19244
+ // hardwired_sdna/flow_instance.json + all the parity tests still lock down
19245
+ // the same `ad4m://FlowInstance` target class.
19246
+ exports.FlowInstanceRecord = class FlowInstanceRecord extends Ad4mModel {
19247
+ constructor() {
19248
+ super(...arguments);
19249
+ /**
19250
+ * URI of the `SHACLFlow` this instance runs — the flow's canonical
19251
+ * identity, collision-free across social-DNA modules from different
19252
+ * communities (bare names WILL collide once shared flows are adopted
19253
+ * cross-team — James PR #929 R5). Sourced from `SHACLFlow.flowUri`
19254
+ * (which is `${namespace}${name}Flow`, e.g. `coasys://DeliveryFlow`).
19255
+ *
19256
+ * First-declared property so `buildSHACL` derives the shape namespace
19257
+ * from its `through` prefix — `ad4m://flow/flow_uri` → `ad4m://` →
19258
+ * target_class `ad4m://FlowInstance`. Also the discriminator predicate
19259
+ * `findAll` uses to isolate instance nodes.
19260
+ *
19261
+ * The human-readable flow name is still available on the paired
19262
+ * `SHACLFlow` (via `perspective.getFlow(record.flowUri.split('/').pop()!.replace(/Flow$/,''))`,
19263
+ * or more commonly via the `FlowInstance` wrapper's `flowName` getter).
19264
+ */
19265
+ this.flowUri = "";
19266
+ /**
19267
+ * URI of the subject expression this flow runs on.
19268
+ * Named `subject` (not `baseExpression`) because `Ad4mModel` reserves
19269
+ * `baseExpression` as a synthetic hydration field always set to the
19270
+ * instance's own URI — a subclass property with that name is shadowed
19271
+ * on read.
19272
+ */
19273
+ this.subject = "";
19274
+ /** Name of the state the flow is currently in. */
19275
+ this.currentState = "";
19276
+ // "When was this flow started?" is answered by `Ad4mModel`'s built-in
19277
+ // `createdAt`, synthesized on hydration from the earliest link timestamp
19278
+ // of the instance's own links (all written together during `mint_flow_instance`).
19279
+ }
19280
+ };
19281
+ __decorate([
19282
+ Property({ through: "ad4m://flow/flow_uri", required: true, identity: true }),
19283
+ __metadata("design:type", String)
19284
+ ], exports.FlowInstanceRecord.prototype, "flowUri", void 0);
19285
+ __decorate([
19286
+ Property({ through: "ad4m://flow/base", required: true }),
19287
+ __metadata("design:type", String)
19288
+ ], exports.FlowInstanceRecord.prototype, "subject", void 0);
19289
+ __decorate([
19290
+ Property({ through: "ad4m://flow/current_state", required: true }),
19291
+ __metadata("design:type", String)
19292
+ ], exports.FlowInstanceRecord.prototype, "currentState", void 0);
19293
+ exports.FlowInstanceRecord = __decorate([
19294
+ Model$1({ name: "FlowInstance" })
19295
+ ], exports.FlowInstanceRecord);
19296
+
19297
+ /**
19298
+ * `FlowInstance` — object-oriented wrapper for a running flow.
19299
+ *
19300
+ * Design authority: `docs/flow-interpretation-hints-design.md` §4.3.
19301
+ *
19302
+ * Wraps two on-graph objects:
19303
+ *
19304
+ * - `FlowInstanceRecord` — the raw @Model row minted by
19305
+ * {@link FlowInstance.start}; carries `flow`, `subject`, `currentState`,
19306
+ * and Ad4mModel's synthesised `createdAt`.
19307
+ * - `SHACLFlow` — the flow definition the record is bound to. Held so
19308
+ * `availableTransitions` / `currentState` object lookups don't require
19309
+ * a per-call round-trip.
19310
+ *
19311
+ * Construct via the class factories — {@link FlowInstance.start} for the
19312
+ * mint path and {@link FlowInstance.findAll} for the read path — rather
19313
+ * than the `wrap` escape hatch, which exists for tests that already own
19314
+ * a matched (record, shape) pair.
19315
+ *
19316
+ * # What's here vs. what's coming in §7 / slice 10.6
19317
+ *
19318
+ * Read surface (implemented today, PR #929):
19319
+ * - `uri`, `subject`, `flowName`, `currentStateName`, `startedAtMillis`
19320
+ * accessors.
19321
+ * - `currentState` — resolves the `FlowState` on the shape whose name
19322
+ * matches `record.currentState`.
19323
+ * - `availableTransitions` — filters `shape.transitions` by `fromState`.
19324
+ * - `proposals()` — queries `FlowTransitionProposal` records that
19325
+ * target this instance's URI.
19326
+ *
19327
+ * Mutations + subscriptions (`proposeTransition`, `accept`, `reject`,
19328
+ * `fireAction`, `onStateChange`, `onProposalAdded`, `onProposalResolved`)
19329
+ * land with the consensus-engine slice (§4.3 / slice 10.6). Rather than
19330
+ * ship them as `throw new Error("not yet")` stubs — which is a type-level
19331
+ * lie the caller only discovers at runtime — they are simply absent from
19332
+ * this class until the engine is wired.
19333
+ */
19334
+ /**
19335
+ * Extract the flow's human-readable name from its canonical URI.
19336
+ *
19337
+ * `SHACLFlow.flowUri` is `${namespace}${name}Flow` (e.g.
19338
+ * `coasys://DeliveryFlow`). This function strips the `Flow` suffix and
19339
+ * everything before the last URI-segment separator (`/` or `#`), leaving
19340
+ * the bare name. Returns `undefined` for URIs that don't match the
19341
+ * `…{name}Flow` shape — a stale FlowInstanceRecord whose flow URI came
19342
+ * from an older writer, for instance.
19343
+ */
19344
+ function flowNameFromUri(flowUri) {
19345
+ if (!flowUri.endsWith("Flow"))
19346
+ return undefined;
19347
+ const withoutSuffix = flowUri.slice(0, -"Flow".length);
19348
+ const sepIdx = Math.max(withoutSuffix.lastIndexOf("/"), withoutSuffix.lastIndexOf("#"));
19349
+ if (sepIdx < 0)
19350
+ return withoutSuffix || undefined;
19351
+ const name = withoutSuffix.slice(sepIdx + 1);
19352
+ return name || undefined;
19353
+ }
19354
+ class FlowInstance {
19355
+ /**
19356
+ * Private constructor — construct via {@link FlowInstance.start} or
19357
+ * {@link FlowInstance.findAll}. {@link FlowInstance.wrap} is the
19358
+ * escape hatch for tests / direct construction cases.
19359
+ */
19360
+ constructor(perspective,
19361
+ /** The flow definition this instance was minted against. */
19362
+ shape,
19363
+ /**
19364
+ * The on-graph record — carries `flow`, `subject`, `currentState`
19365
+ * and Ad4mModel's synthesised `createdAt`. Callers can reach into it
19366
+ * for anything the wrapper doesn't expose directly, but should prefer
19367
+ * the wrapper accessors so future refactors of the underlying shape
19368
+ * don't ripple through their code.
19369
+ */
19370
+ record) {
19371
+ this.perspective = perspective;
19372
+ this.shape = shape;
19373
+ this.record = record;
19374
+ }
19375
+ /**
19376
+ * Escape hatch used by {@link FlowInstance.start} and
19377
+ * {@link FlowInstance.findAll} — not meant for general use, but public
19378
+ * so tests that already own a `FlowInstanceRecord + SHACLFlow` pair
19379
+ * (e.g. from pre-populated fixtures) can build a wrapper without
19380
+ * going through the mint path.
19381
+ */
19382
+ static wrap(perspective, shape, record) {
19383
+ return new FlowInstance(perspective, shape, record);
19384
+ }
19385
+ /**
19386
+ * Mint a new `FlowInstance` on the given perspective (design doc §4.3).
19387
+ *
19388
+ * Idempotently registers the hardwired `FlowInstanceRecord` +
19389
+ * `FlowTransitionProposal` @Model classes on first call — the on-graph
19390
+ * shape matches the Rust-side hardwired SDNA (parity-locked in
19391
+ * `flow-instance.test.ts` / `flow-transition-proposal.test.ts`).
19392
+ *
19393
+ * The returned wrapper carries the parsed `SHACLFlow` alongside the
19394
+ * on-graph record, so `currentState` / `availableTransitions` /
19395
+ * `proposals` accessors work without further round-trips. The consensus
19396
+ * engine (slice 10.6) will read the record's `currentState` when it
19397
+ * fires transitions.
19398
+ *
19399
+ * @param perspective - The perspective the flow instance lives on
19400
+ * @param flowName - Name of a `SHACLFlow` already registered on the perspective
19401
+ * @param baseExpression - URI of the subject expression the flow runs on
19402
+ * @throws When the flow is unknown or has zero declared states (zero-state
19403
+ * flows fire via the forthcoming atomic-action path, §6.3).
19404
+ */
19405
+ static async start(perspective, flowName, baseExpression) {
19406
+ const flow = await perspective.getFlow(flowName);
19407
+ if (!flow)
19408
+ throw `Flow "${flowName}" not found`;
19409
+ if (flow.states.length === 0) {
19410
+ throw `Flow "${flowName}" has no states — FlowInstance.start is for stateful flows only; zero-state flows fire via the forthcoming atomic-action path (§6.3)`;
19411
+ }
19412
+ // Register the hardwired runtime classes if this is the first flow
19413
+ // instance on the perspective. registerAll is a single batched RPC and
19414
+ // no-ops when both classes are already present.
19415
+ await Ad4mModel.registerAll(perspective, [exports.FlowInstanceRecord, exports.FlowTransitionProposal]);
19416
+ // Property keys must be the FlowInstanceRecord @Model field names —
19417
+ // `subject` (not `baseExpression`, which collides with Ad4mModel's
19418
+ // synthetic hydration field and would be silently shadowed on read).
19419
+ // No explicit start-time field: Ad4mModel synthesises `createdAt` on
19420
+ // hydration from the earliest link timestamp on the instance's URI.
19421
+ // Convention: `SHACLFlow.states` is stored sorted ascending by `value`
19422
+ // (enforced by `fromLinks`), so `states[0]` is the initial state. A
19423
+ // flow author who wants a specific state as the entry point must give
19424
+ // it the lowest `value` in the set.
19425
+ //
19426
+ // Store the flow's URI, not the bare name — see FlowInstanceRecord's
19427
+ // docstring for the collision-across-modules argument (James PR #929 R5).
19428
+ const record = await exports.FlowInstanceRecord.create(perspective, {
19429
+ flowUri: flow.flowUri,
19430
+ subject: baseExpression,
19431
+ currentState: flow.states[0].name,
19432
+ });
19433
+ return FlowInstance.wrap(perspective, flow, record);
19434
+ }
19435
+ /**
19436
+ * Return every live `FlowInstance` on the perspective (design doc §4.3).
19437
+ *
19438
+ * Read-only path: never registers classes. On a perspective that has
19439
+ * never minted a flow instance, the `FlowInstanceRecord` SHACL shape
19440
+ * isn't installed yet — this returns `[]` in that case rather than
19441
+ * mutating the perspective. Registration is the responsibility of
19442
+ * {@link FlowInstance.start}, which is the write path. (Registering on
19443
+ * a read would sync a write to every peer in the neighbourhood —
19444
+ * exactly what a query must not do — James PR #929 R7.)
19445
+ *
19446
+ * Filter surface (all optional, all combinable):
19447
+ * - **`flowName`** — narrows by flow-name discriminator (e.g. "Delivery")
19448
+ * - **`subject`** — narrows by base-expression URI, i.e. "give me every
19449
+ * flow running on THIS expression"
19450
+ *
19451
+ * Both filters translate to a single SHACL `where`-filter round-trip
19452
+ * (no client-side filtering); combining them AND-joins server-side.
19453
+ * The string-arg shape (`FlowInstance.findAll(p, "Delivery")`) is
19454
+ * shorthand for `{ flowName: "Delivery" }`.
19455
+ *
19456
+ * Records whose `flow` value has no matching `SHACLFlow` on the
19457
+ * perspective (e.g. the flow was unregistered) are silently skipped —
19458
+ * the wrapper can't answer `currentState` / `availableTransitions`
19459
+ * without the shape, and callers routinely iterate the returned array
19460
+ * without null-checks.
19461
+ *
19462
+ * @example
19463
+ * ```typescript
19464
+ * const all = await FlowInstance.findAll(perspective);
19465
+ * const deliveries = await FlowInstance.findAll(perspective, "Delivery");
19466
+ * const onThisTask = await FlowInstance.findAll(perspective, {
19467
+ * subject: "ad4m://task/1",
19468
+ * });
19469
+ * const deliveriesOnTask = await FlowInstance.findAll(perspective, {
19470
+ * flowName: "Delivery",
19471
+ * subject: "ad4m://task/1",
19472
+ * });
19473
+ * ```
19474
+ */
19475
+ static async findAll(perspective, filter) {
19476
+ const { flowName, subject } = typeof filter === "string"
19477
+ ? { flowName: filter, subject: undefined }
19478
+ : { flowName: filter?.flowName, subject: filter?.subject };
19479
+ // Filter surface accepts a flow *name* for ergonomics — resolve it to
19480
+ // the canonical URI before the SHACL query, since the record stores
19481
+ // the URI (James PR #929 R5). Unknown name → no matches (short-circuit
19482
+ // with an empty result rather than issuing a bare-name query that
19483
+ // would silently return nothing anyway).
19484
+ const where = {};
19485
+ if (flowName !== undefined) {
19486
+ const flow = await perspective.getFlow(flowName);
19487
+ if (!flow)
19488
+ return [];
19489
+ where.flowUri = flow.flowUri;
19490
+ }
19491
+ if (subject !== undefined)
19492
+ where.subject = subject;
19493
+ // "Shape not found" on a perspective that has never minted a flow
19494
+ // instance is a no-op read, not an error — the executor throws for a
19495
+ // missing SHACL shape and there is no side-effect-free way to ask
19496
+ // "does this class exist". Return `[]` on that specific case; rethrow
19497
+ // anything else so real infra failures don't get swallowed.
19498
+ //
19499
+ // Regex covers every message the executor + client stack raises for
19500
+ // an unregistered class:
19501
+ // "No SHACL shape stored for class 'FlowInstance'." (executor RPC)
19502
+ // "Shape not found" (older Rust path)
19503
+ // "class not registered" / "not registered" (TS Ad4mModel guard)
19504
+ let records;
19505
+ try {
19506
+ records =
19507
+ Object.keys(where).length > 0
19508
+ ? await exports.FlowInstanceRecord.findAll(perspective, { where })
19509
+ : await exports.FlowInstanceRecord.findAll(perspective);
19510
+ }
19511
+ catch (e) {
19512
+ const msg = e instanceof Error ? e.message : String(e);
19513
+ if (/no shacl shape stored|shape not found|class not registered|not registered/i.test(msg)) {
19514
+ return [];
19515
+ }
19516
+ throw e;
19517
+ }
19518
+ // Pair each record with its parsed SHACLFlow. Cache lookups by
19519
+ // flow-URI so `getFlow` fires at most once per distinct flow —
19520
+ // matters when a perspective has hundreds of instances against
19521
+ // one shape.
19522
+ //
19523
+ // The URI stored on the record is `${namespace}${name}Flow`
19524
+ // (see SHACLFlow.flowUri) — recovering the name for `getFlow`
19525
+ // means stripping the namespace + the `Flow` suffix. Records that
19526
+ // don't parse this way are treated as stale and skipped.
19527
+ const shapesByUri = new Map();
19528
+ const wrappers = [];
19529
+ for (const record of records) {
19530
+ let shape = shapesByUri.get(record.flowUri);
19531
+ if (!shape) {
19532
+ const name = flowNameFromUri(record.flowUri);
19533
+ if (!name)
19534
+ continue;
19535
+ const loaded = await perspective.getFlow(name);
19536
+ if (!loaded || loaded.flowUri !== record.flowUri) {
19537
+ // Stale record — the flow it references was unregistered,
19538
+ // or a different flow now owns that name.
19539
+ continue;
19540
+ }
19541
+ shape = loaded;
19542
+ shapesByUri.set(record.flowUri, shape);
19543
+ }
19544
+ wrappers.push(FlowInstance.wrap(perspective, shape, record));
19545
+ }
19546
+ return wrappers;
19547
+ }
19548
+ // ── Read accessors ────────────────────────────────────────────────────
19549
+ /**
19550
+ * URI of the on-graph `FlowInstance` node — `ad4m://flow/instance/{id}`.
19551
+ *
19552
+ * Sourced from `Ad4mModel`'s synthesised `baseExpression`, which for
19553
+ * `FlowInstanceRecord` *is* the instance's own URI (the value
19554
+ * `FlowTransitionProposal.flowInstance` references).
19555
+ */
19556
+ get uri() {
19557
+ return this.record.baseExpression;
19558
+ }
19559
+ /**
19560
+ * URI of the base expression this flow runs on — matches the
19561
+ * `SHACLFlow.inputTypes` that {@link PerspectiveProxy.availableFlows}
19562
+ * would greenlight for this expression.
19563
+ */
19564
+ get subject() {
19565
+ return this.record.subject;
19566
+ }
19567
+ /**
19568
+ * Human-readable flow name — the display label. Sourced from the paired
19569
+ * `SHACLFlow.name`, not from the record (which stores the URI as its
19570
+ * canonical identity — see FlowInstanceRecord's docstring for why).
19571
+ */
19572
+ get flowName() {
19573
+ return this.shape.name;
19574
+ }
19575
+ /** Flow URI — the on-graph discriminator, collision-free across modules. */
19576
+ get flowUri() {
19577
+ return this.record.flowUri;
19578
+ }
19579
+ /** Name of the state this instance is currently in. */
19580
+ get currentStateName() {
19581
+ return this.record.currentState;
19582
+ }
19583
+ /**
19584
+ * ISO-8601 (epoch millis after Ad4mModel hydration) start time.
19585
+ * Returns `undefined` when hydration didn't produce a `createdAt`
19586
+ * — rare, but not fatal.
19587
+ */
19588
+ get startedAtMillis() {
19589
+ const v = this.record.createdAt;
19590
+ return typeof v === "number" ? v : undefined;
19591
+ }
19592
+ /**
19593
+ * The `FlowState` object on the shape matching `currentStateName`.
19594
+ * Throws when the record's state name is not declared on the flow —
19595
+ * that's a "stale FlowInstance whose flow was edited under it" bug,
19596
+ * not a silent-fail case.
19597
+ */
19598
+ get currentState() {
19599
+ const s = this.shape.states.find((x) => x.name === this.currentStateName);
19600
+ if (!s) {
19601
+ throw new Error(`FlowInstance ${this.uri}: currentState "${this.currentStateName}" is not declared on flow "${this.flowName}". ` +
19602
+ `Known states: ${this.shape.states.map((x) => x.name).join(", ") || "(none)"}`);
19603
+ }
19604
+ return s;
19605
+ }
19606
+ /**
19607
+ * Every `FlowTransition` on the shape whose `fromState` matches
19608
+ * `currentStateName`. Order preserved from the shape.
19609
+ *
19610
+ * Empty when the current state is terminal (no outgoing transitions).
19611
+ */
19612
+ get availableTransitions() {
19613
+ return this.shape.transitions.filter((t) => t.fromState === this.currentStateName);
19614
+ }
19615
+ /**
19616
+ * All `FlowTransitionProposal` records targeting this instance's URI.
19617
+ *
19618
+ * Uses the SDNA identity discriminator (`ad4m://flow/instance` predicate)
19619
+ * for the where-filter — one SPARQL round-trip, no client-side
19620
+ * filtering.
19621
+ *
19622
+ * Note: the consensus engine (slice 10.6) will start writing these; today
19623
+ * they only exist when a client wrote one directly (or a test seeded one).
19624
+ */
19625
+ async proposals() {
19626
+ return exports.FlowTransitionProposal.findAll(this.perspective, {
19627
+ where: { flowInstance: this.uri },
19628
+ });
19629
+ }
19630
+ }
19631
+
17913
19632
  /**
17914
19633
  * SPARQL binding helpers — typed shapes and parsers for `querySparql<T>()`.
17915
19634
  *
@@ -17942,23 +19661,74 @@ function parseSparqlCount(result) {
17942
19661
  /**
17943
19662
  * Decode a `Literal`-encoded SPARQL binding back to a plain string.
17944
19663
  *
17945
- * Mirrors Flux's local `parseLit` helper. Returns `''` for `undefined`/empty
17946
- * input. Falls through to the raw value if decoding fails (defensive — the
17947
- * binding may already be a plain string for unwrapped properties).
19664
+ * Returns `''` for `undefined`/empty input. Falls through to the raw value
19665
+ * if decoding fails — bindings against properties resolved through a custom
19666
+ * language are already raw URIs and should pass through unchanged.
19667
+ *
19668
+ * Signed-envelope literals
19669
+ * ------------------------
19670
+ * Properties declared with `resolveLanguage: 'literal'` are written through
19671
+ * the built-in `literal` language, which wraps the value in a signed
19672
+ * expression envelope (`{ author, timestamp, data, proof }`) and encodes
19673
+ * the whole envelope as a `literal:json:` URL — see
19674
+ * `rust-executor/src/languages/mod.rs::expression_create` (literal branch).
19675
+ * On read, `parseLit` unwraps `.data` from that envelope so callers get the
19676
+ * original scalar value instead of the envelope JSON.
19677
+ *
19678
+ * The Channel V refactor moved most scalar properties to deterministic
19679
+ * typed XSD literals which no longer round-trip through this envelope — for
19680
+ * those properties the SPARQL binding is already the lexical form and this
19681
+ * helper decodes to the primitive. Signed-envelope literals still exist
19682
+ * for any property that opts back into `resolveLanguage: 'literal'` (e.g.
19683
+ * per-message provenance for chat bodies), which is why the `.data` unwrap
19684
+ * is preserved here.
19685
+ *
19686
+ * Non-envelope JSON objects (`literal:json:` payloads that are not signed
19687
+ * envelopes) are JSON-stringified for display.
17948
19688
  */
17949
19689
  function parseLit(val) {
17950
19690
  if (val === undefined || val === null || val === '')
17951
19691
  return '';
19692
+ // Fast-path 1: `literal:*` URLs from properties written through the built-in
19693
+ // `literal` language. On Channel V typed-XSD-literal properties, these
19694
+ // decode straight to a primitive; on `resolveLanguage: 'literal'` properties
19695
+ // (per-message provenance in chat/synergy) they decode to a signed-envelope
19696
+ // object we unwrap via `.data`.
17952
19697
  try {
17953
19698
  const result = Literal.fromUrl(val).get();
17954
- if (result && typeof result === 'object') {
17955
- return result.data ?? JSON.stringify(result);
19699
+ if (typeof result === 'object' && result !== null) {
19700
+ const data = result.data;
19701
+ if (typeof data === 'string')
19702
+ return data;
19703
+ return JSON.stringify(result);
17956
19704
  }
17957
19705
  return String(result);
17958
19706
  }
17959
19707
  catch {
17960
- return val;
19708
+ // fall through to plain-JSON envelope detection
19709
+ }
19710
+ // Fast-path 2: envelope stored/returned as a bare JSON string rather than a
19711
+ // `literal:json:*` URL. Depending on the storage backend and query path,
19712
+ // SPARQL bindings for `resolveLanguage: 'literal'` properties can surface
19713
+ // the envelope object directly as its JSON serialisation (Oxigraph typed
19714
+ // xsd:string of the JSON, or a Channel V pass-through) instead of the URL
19715
+ // form. Detect that shape by parsing the string and unwrapping `.data`
19716
+ // when it looks like a signed envelope; anything else passes through
19717
+ // unchanged so plain text (e.g. "just a string") is not corrupted.
19718
+ if (val.length >= 2 && val.charCodeAt(0) === 0x7b /* '{' */) {
19719
+ try {
19720
+ const parsed = JSON.parse(val);
19721
+ if (parsed && typeof parsed === 'object') {
19722
+ const data = parsed.data;
19723
+ if (typeof data === 'string')
19724
+ return data;
19725
+ }
19726
+ }
19727
+ catch {
19728
+ // not JSON — fall through and return the raw value
19729
+ }
17961
19730
  }
19731
+ return val;
17962
19732
  }
17963
19733
  /** Decode a `Literal`-encoded binding to a number. Returns 0 on empty/invalid input. */
17964
19734
  function parseLitNumber(val) {
@@ -18308,16 +20078,21 @@ function formatQueryValue(value) {
18308
20078
  *
18309
20079
  * @param predicate - The predicate URI for the property
18310
20080
  * @param condition - The Where condition value
18311
- * @param opts - Optional settings (e.g. `resolveLanguage`)
20081
+ * @param opts - Optional settings. `isDeterministicLiteral` (default
20082
+ * `true`) selects the direct typed-literal WHERE path.
20083
+ * Set to `false` when the property stores a signed
20084
+ * envelope (`resolveLanguage: "literal"`) or a
20085
+ * custom-language expression — the envelope path unwraps
20086
+ * with `parse_literal` before comparing.
18312
20087
  * @returns A single SPARQL condition string
18313
20088
  */
18314
20089
  function buildWhereCondition(predicate, condition, opts) {
18315
20090
  const escapedPredicate = escapeQueryString(predicate);
18316
- // For literal-resolved properties, we match against the raw IRI (which is a literal: URI)
18317
- // For language-resolved properties, we match against the plain URI
18318
- // For literal-resolved properties, values are stored as IRIs like <literal:string:VALUE>
18319
- // For language-resolved properties, values are plain URIs
18320
- const isLiteral = !opts?.resolveLanguage || opts.resolveLanguage === 'literal';
20091
+ // For deterministic-literal properties, values are stored as typed
20092
+ // literals like `"X"^^xsd:string` (or the legacy `<literal:string:VALUE>`
20093
+ // IRI form). For envelope / custom-language properties the target is a
20094
+ // signed expression URI; comparisons need to unwrap via `parse_literal`.
20095
+ const isLiteral = opts?.isDeterministicLiteral !== false;
18321
20096
  const varSuffix = opts?.varIndex ?? 0;
18322
20097
  function formatValue(v) {
18323
20098
  if (typeof v === 'string') {
@@ -18426,23 +20201,28 @@ function compileWhereClause(where, metadata) {
18426
20201
  if (['id', 'author', 'timestamp'].includes(propertyName))
18427
20202
  continue;
18428
20203
  let predicate;
18429
- let resolveLanguage;
20204
+ // Storage mode is derived from `resolveLanguage` alone:
20205
+ // - undefined → deterministic typed literal (fast POS-index path)
20206
+ // - "literal" → signed envelope on the literal language
20207
+ // - custom address → expression on that custom language
20208
+ // Envelope and custom-language properties both need the `parse_literal`
20209
+ // unwrap path, so we treat any `resolveLanguage`-carrying property as
20210
+ // non-deterministic here.
20211
+ let isDeterministicLiteral;
18430
20212
  if (metadata) {
18431
20213
  const propMeta = metadata.properties[propertyName];
18432
20214
  if (propMeta) {
18433
20215
  predicate = propMeta.predicate;
18434
- resolveLanguage = propMeta.resolveLanguage;
20216
+ isDeterministicLiteral = propMeta.resolveLanguage === undefined;
18435
20217
  }
18436
20218
  else {
18437
- // Property not found in metadata — treat name as raw predicate URI
18438
20219
  predicate = propertyName;
18439
20220
  }
18440
20221
  }
18441
20222
  else {
18442
- // No metadata — treat name as raw predicate URI
18443
20223
  predicate = propertyName;
18444
20224
  }
18445
- const cond = buildWhereCondition(predicate, condition, { resolveLanguage, varIndex: conditions.length });
20225
+ const cond = buildWhereCondition(predicate, condition, { isDeterministicLiteral, varIndex: conditions.length });
18446
20226
  if (cond) {
18447
20227
  conditions.push(cond);
18448
20228
  }
@@ -18578,7 +20358,7 @@ function fn(iri, args = []) {
18578
20358
  * ```typescript
18579
20359
  * @Property({
18580
20360
  * through: 'we://image',
18581
- * resolveLanguage: FILE_STORAGE_LANGUAGE,
20361
+ * resolveLanguage: 'literal',
18582
20362
  * transform: fileToDataUri,
18583
20363
  * })
18584
20364
  * avatar?: string;
@@ -18621,6 +20401,7 @@ exports.ExpressionProofInput = ExpressionProofInput;
18621
20401
  exports.ExpressionRef = ExpressionRef;
18622
20402
  exports.ExpressionRendered = ExpressionRendered;
18623
20403
  exports.Flag = Flag;
20404
+ exports.FlowInstance = FlowInstance;
18624
20405
  exports.HasMany = HasMany;
18625
20406
  exports.HasOne = HasOne;
18626
20407
  exports.HostingUserInfo = HostingUserInfo;
@@ -18707,6 +20488,7 @@ exports.concat = concat;
18707
20488
  exports.createPersistentCache = createPersistentCache;
18708
20489
  exports.determineNamespace = determineNamespace;
18709
20490
  exports.determinePredicate = determinePredicate;
20491
+ exports.effectiveLiteralStorage = effectiveLiteralStorage;
18710
20492
  exports.escapeQueryString = escapeQueryString;
18711
20493
  exports.exists = exists;
18712
20494
  exports.exprRef2String = exprRef2String;
@@ -18735,6 +20517,7 @@ exports.isObjectType = isObjectType;
18735
20517
  exports.isSchemaType = isSchemaType;
18736
20518
  exports.linkEqual = linkEqual;
18737
20519
  exports.literal = literal;
20520
+ exports.looksLikeUri = looksLikeUri;
18738
20521
  exports.normalizeNamespaceString = normalizeNamespaceString;
18739
20522
  exports.normalizeSchemaType = normalizeSchemaType;
18740
20523
  exports.normalizeValue = normalizeValue;
@@ -18750,3 +20533,4 @@ exports.setCachedResult = setCachedResult;
18750
20533
  exports.setPropertyRegistryEntry = setPropertyRegistryEntry;
18751
20534
  exports.setRelationRegistryEntry = setRelationRegistryEntry;
18752
20535
  exports.typeDefsString = typeDefsString;
20536
+ exports.valueToLiteralIri = valueToLiteralIri;