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