@coasys/ad4m 0.13.0-test-interpretation-2 → 0.13.0-test-inverse-relations

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 (267) hide show
  1. package/lib/index.cjs +2399 -529
  2. package/lib/index.js +2396 -530
  3. package/lib/src/ai/AIClient.d.ts +13 -0
  4. package/lib/src/ai/AIClient.js +21 -3
  5. package/lib/src/apiClient.d.ts +40 -4
  6. package/lib/src/apiClient.js +149 -9
  7. package/lib/src/index.d.ts +3 -1
  8. package/lib/src/index.js +2 -0
  9. package/lib/src/model/Ad4mModel.d.ts +6 -5
  10. package/lib/src/model/Ad4mModel.js +260 -35
  11. package/lib/src/model/Ad4mModel.test.js +480 -735
  12. package/lib/src/model/ModelQueryBuilder.js +13 -3
  13. package/lib/src/model/decorators.d.ts +147 -4
  14. package/lib/src/model/decorators.js +70 -24
  15. package/lib/src/model/model-manifest.d.ts +41 -0
  16. package/lib/src/model/model-manifest.js +11 -0
  17. package/lib/src/model/query-common.d.ts +10 -1
  18. package/lib/src/model/query-common.js +16 -0
  19. package/lib/src/model/query-sparql.js +25 -1
  20. package/lib/src/model/query-sparql.test.js +92 -10
  21. package/lib/src/model/shacl-gen.js +45 -0
  22. package/lib/src/model/types.d.ts +100 -1
  23. package/lib/src/model/types.js +9 -0
  24. package/lib/src/neighbourhood/NeighbourhoodProxy.test.js +33 -33
  25. package/lib/src/perspectives/AutoProcessor.d.ts +98 -24
  26. package/lib/src/perspectives/FlowInstance.d.ts +205 -0
  27. package/lib/src/perspectives/FlowInstance.js +359 -0
  28. package/lib/src/perspectives/FlowModels.d.ts +100 -0
  29. package/lib/src/perspectives/FlowModels.js +188 -0
  30. package/lib/src/perspectives/InterpretationModels.d.ts +12 -22
  31. package/lib/src/perspectives/InterpretationModels.js +2 -6
  32. package/lib/src/perspectives/PerspectiveClient.d.ts +84 -7
  33. package/lib/src/perspectives/PerspectiveClient.js +117 -10
  34. package/lib/src/perspectives/PerspectiveProxy.d.ts +173 -60
  35. package/lib/src/perspectives/PerspectiveProxy.js +466 -276
  36. package/lib/src/perspectives/WakerSubscriptionManager.d.ts +55 -5
  37. package/lib/src/perspectives/WakerSubscriptionManager.js +183 -8
  38. package/lib/src/shacl/SHACLFlow.d.ts +273 -47
  39. package/lib/src/shacl/SHACLFlow.js +397 -88
  40. package/lib/src/shacl/SHACLShape.d.ts +8 -0
  41. package/lib/src/shacl/SHACLShape.js +17 -0
  42. package/lib/src/shacl/SHACLShape.test.js +82 -0
  43. package/package.json +2 -2
  44. package/src/ai/AIClient.ts +22 -3
  45. package/src/apiClient.test.ts +227 -0
  46. package/src/apiClient.ts +185 -9
  47. package/src/index.ts +3 -1
  48. package/src/model/Ad4mModel.test.ts +724 -0
  49. package/src/model/Ad4mModel.ts +259 -32
  50. package/src/model/ModelQueryBuilder.ts +13 -3
  51. package/src/model/decorators.ts +216 -35
  52. package/src/model/query-common.ts +20 -1
  53. package/src/model/query-sparql.ts +28 -1
  54. package/src/model/relation-filtering.test.ts +70 -20
  55. package/src/model/shacl-gen.ts +48 -0
  56. package/src/model/shacl-roundtrip.test.ts +201 -0
  57. package/src/model/types.ts +103 -1
  58. package/src/perspectives/AutoProcessor.ts +102 -24
  59. package/src/perspectives/FlowInstance.ts +395 -0
  60. package/src/perspectives/FlowModels.ts +163 -0
  61. package/src/perspectives/InterpretationModels.ts +13 -25
  62. package/src/perspectives/PerspectiveClient.test.ts +67 -6
  63. package/src/perspectives/PerspectiveClient.ts +170 -12
  64. package/src/perspectives/PerspectiveProxy.test.ts +560 -0
  65. package/src/perspectives/PerspectiveProxy.ts +543 -294
  66. package/src/perspectives/WakerSubscriptionManager.test.ts +199 -0
  67. package/src/perspectives/WakerSubscriptionManager.ts +197 -9
  68. package/src/perspectives/shacl-rpc.test.ts +258 -0
  69. package/src/shacl/SHACLFlow.test.ts +762 -35
  70. package/src/shacl/SHACLFlow.ts +680 -112
  71. package/src/shacl/SHACLShape.ts +31 -0
  72. package/lib/src/generated/rest/AIModelLoadingStatus.d.ts +0 -7
  73. package/lib/src/generated/rest/AIModelLoadingStatus.js +0 -2
  74. package/lib/src/generated/rest/AddAgentInfosRequest.d.ts +0 -3
  75. package/lib/src/generated/rest/AddAgentInfosRequest.js +0 -2
  76. package/lib/src/generated/rest/AddLinkExpressionRequest.d.ts +0 -6
  77. package/lib/src/generated/rest/AddLinkExpressionRequest.js +0 -1
  78. package/lib/src/generated/rest/AddLinkRequest.d.ts +0 -6
  79. package/lib/src/generated/rest/AddLinkRequest.js +0 -1
  80. package/lib/src/generated/rest/AddLinksBulkRequest.d.ts +0 -6
  81. package/lib/src/generated/rest/AddLinksBulkRequest.js +0 -1
  82. package/lib/src/generated/rest/AddSdnaRequest.d.ts +0 -6
  83. package/lib/src/generated/rest/AddSdnaRequest.js +0 -2
  84. package/lib/src/generated/rest/ApplyTemplateRequest.d.ts +0 -4
  85. package/lib/src/generated/rest/ApplyTemplateRequest.js +0 -2
  86. package/lib/src/generated/rest/AuthInfoInput.d.ts +0 -10
  87. package/lib/src/generated/rest/AuthInfoInput.js +0 -1
  88. package/lib/src/generated/rest/BroadcastRequest.d.ts +0 -6
  89. package/lib/src/generated/rest/BroadcastRequest.js +0 -1
  90. package/lib/src/generated/rest/CapabilityInput.d.ts +0 -5
  91. package/lib/src/generated/rest/CapabilityInput.js +0 -1
  92. package/lib/src/generated/rest/CommitBatchRequest.d.ts +0 -3
  93. package/lib/src/generated/rest/CommitBatchRequest.js +0 -2
  94. package/lib/src/generated/rest/ComputeLogEntry.d.ts +0 -9
  95. package/lib/src/generated/rest/ComputeLogEntry.js +0 -2
  96. package/lib/src/generated/rest/CreateExpressionRequest.d.ts +0 -4
  97. package/lib/src/generated/rest/CreateExpressionRequest.js +0 -2
  98. package/lib/src/generated/rest/CreatePerspectiveRequest.d.ts +0 -3
  99. package/lib/src/generated/rest/CreatePerspectiveRequest.js +0 -2
  100. package/lib/src/generated/rest/CreateSubjectRequest.d.ts +0 -6
  101. package/lib/src/generated/rest/CreateSubjectRequest.js +0 -2
  102. package/lib/src/generated/rest/CreateUserRequest.d.ts +0 -4
  103. package/lib/src/generated/rest/CreateUserRequest.js +0 -2
  104. package/lib/src/generated/rest/CreateUserResponse.d.ts +0 -5
  105. package/lib/src/generated/rest/CreateUserResponse.js +0 -2
  106. package/lib/src/generated/rest/DecoratedExpressionProof.d.ts +0 -6
  107. package/lib/src/generated/rest/DecoratedExpressionProof.js +0 -2
  108. package/lib/src/generated/rest/DecoratedLinkExpression.d.ts +0 -10
  109. package/lib/src/generated/rest/DecoratedLinkExpression.js +0 -1
  110. package/lib/src/generated/rest/DisposeQueryRequest.d.ts +0 -3
  111. package/lib/src/generated/rest/DisposeQueryRequest.js +0 -2
  112. package/lib/src/generated/rest/EmailTestRequest.d.ts +0 -6
  113. package/lib/src/generated/rest/EmailTestRequest.js +0 -2
  114. package/lib/src/generated/rest/EmbedRequest.d.ts +0 -4
  115. package/lib/src/generated/rest/EmbedRequest.js +0 -2
  116. package/lib/src/generated/rest/EntanglementProofInput.d.ts +0 -6
  117. package/lib/src/generated/rest/EntanglementProofInput.js +0 -2
  118. package/lib/src/generated/rest/EntanglementProofPreflightRequest.d.ts +0 -4
  119. package/lib/src/generated/rest/EntanglementProofPreflightRequest.js +0 -2
  120. package/lib/src/generated/rest/ExecuteCommandsRequest.d.ts +0 -4
  121. package/lib/src/generated/rest/ExecuteCommandsRequest.js +0 -2
  122. package/lib/src/generated/rest/ExportRequest.d.ts +0 -5
  123. package/lib/src/generated/rest/ExportRequest.js +0 -2
  124. package/lib/src/generated/rest/ExpressionManyRequest.d.ts +0 -3
  125. package/lib/src/generated/rest/ExpressionManyRequest.js +0 -2
  126. package/lib/src/generated/rest/ExpressionProof.d.ts +0 -4
  127. package/lib/src/generated/rest/ExpressionProof.js +0 -2
  128. package/lib/src/generated/rest/ExpressionProofInput.d.ts +0 -6
  129. package/lib/src/generated/rest/ExpressionProofInput.js +0 -2
  130. package/lib/src/generated/rest/FriendSendMessageRequest.d.ts +0 -3
  131. package/lib/src/generated/rest/FriendSendMessageRequest.js +0 -2
  132. package/lib/src/generated/rest/FriendsListRequest.d.ts +0 -3
  133. package/lib/src/generated/rest/FriendsListRequest.js +0 -2
  134. package/lib/src/generated/rest/GenerateAgentRequest.d.ts +0 -3
  135. package/lib/src/generated/rest/GenerateAgentRequest.js +0 -2
  136. package/lib/src/generated/rest/GenerateJwtRequest.d.ts +0 -4
  137. package/lib/src/generated/rest/GenerateJwtRequest.js +0 -2
  138. package/lib/src/generated/rest/GetSubjectDataRequest.d.ts +0 -4
  139. package/lib/src/generated/rest/GetSubjectDataRequest.js +0 -2
  140. package/lib/src/generated/rest/HostingInfoResponse.d.ts +0 -5
  141. package/lib/src/generated/rest/HostingInfoResponse.js +0 -2
  142. package/lib/src/generated/rest/HostingWalletResponse.d.ts +0 -4
  143. package/lib/src/generated/rest/HostingWalletResponse.js +0 -2
  144. package/lib/src/generated/rest/ImportAgentRequest.d.ts +0 -6
  145. package/lib/src/generated/rest/ImportAgentRequest.js +0 -2
  146. package/lib/src/generated/rest/ImportRequest.d.ts +0 -4
  147. package/lib/src/generated/rest/ImportRequest.js +0 -2
  148. package/lib/src/generated/rest/JoinNeighbourhoodRequest.d.ts +0 -3
  149. package/lib/src/generated/rest/JoinNeighbourhoodRequest.js +0 -2
  150. package/lib/src/generated/rest/KeepAliveQueryRequest.d.ts +0 -3
  151. package/lib/src/generated/rest/KeepAliveQueryRequest.js +0 -2
  152. package/lib/src/generated/rest/LanguageMetaInput.d.ts +0 -6
  153. package/lib/src/generated/rest/LanguageMetaInput.js +0 -2
  154. package/lib/src/generated/rest/Link.d.ts +0 -5
  155. package/lib/src/generated/rest/Link.js +0 -2
  156. package/lib/src/generated/rest/LinkExpression.d.ts +0 -10
  157. package/lib/src/generated/rest/LinkExpression.js +0 -1
  158. package/lib/src/generated/rest/LinkExpressionInput.d.ts +0 -10
  159. package/lib/src/generated/rest/LinkExpressionInput.js +0 -1
  160. package/lib/src/generated/rest/LinkInput.d.ts +0 -5
  161. package/lib/src/generated/rest/LinkInput.js +0 -2
  162. package/lib/src/generated/rest/LinkLanguageTemplatesRequest.d.ts +0 -3
  163. package/lib/src/generated/rest/LinkLanguageTemplatesRequest.js +0 -2
  164. package/lib/src/generated/rest/LinkMutationRequest.d.ts +0 -12
  165. package/lib/src/generated/rest/LinkMutationRequest.js +0 -1
  166. package/lib/src/generated/rest/LinkMutationResponse.d.ts +0 -9
  167. package/lib/src/generated/rest/LinkMutationResponse.js +0 -1
  168. package/lib/src/generated/rest/LinkMutations.d.ts +0 -6
  169. package/lib/src/generated/rest/LinkMutations.js +0 -1
  170. package/lib/src/generated/rest/LinkMutationsRequest.d.ts +0 -5
  171. package/lib/src/generated/rest/LinkMutationsRequest.js +0 -1
  172. package/lib/src/generated/rest/LinkStatus.d.ts +0 -1
  173. package/lib/src/generated/rest/LinkStatus.js +0 -2
  174. package/lib/src/generated/rest/LinkUpdateInput.d.ts +0 -5
  175. package/lib/src/generated/rest/LinkUpdateInput.js +0 -1
  176. package/lib/src/generated/rest/LockAgentRequest.d.ts +0 -3
  177. package/lib/src/generated/rest/LockAgentRequest.js +0 -2
  178. package/lib/src/generated/rest/LoginUserRequest.d.ts +0 -5
  179. package/lib/src/generated/rest/LoginUserRequest.js +0 -2
  180. package/lib/src/generated/rest/ModelType.d.ts +0 -1
  181. package/lib/src/generated/rest/ModelType.js +0 -2
  182. package/lib/src/generated/rest/NotificationGrantRequest.d.ts +0 -3
  183. package/lib/src/generated/rest/NotificationGrantRequest.js +0 -2
  184. package/lib/src/generated/rest/NotificationInput.d.ts +0 -10
  185. package/lib/src/generated/rest/NotificationInput.js +0 -2
  186. package/lib/src/generated/rest/OpenLinkRequest.d.ts +0 -3
  187. package/lib/src/generated/rest/OpenLinkRequest.js +0 -2
  188. package/lib/src/generated/rest/PermitCapabilityRequest.d.ts +0 -3
  189. package/lib/src/generated/rest/PermitCapabilityRequest.js +0 -2
  190. package/lib/src/generated/rest/PerspectiveInput.d.ts +0 -4
  191. package/lib/src/generated/rest/PerspectiveInput.js +0 -1
  192. package/lib/src/generated/rest/PromptRequest.d.ts +0 -4
  193. package/lib/src/generated/rest/PromptRequest.js +0 -2
  194. package/lib/src/generated/rest/PublicPerspectiveInput.d.ts +0 -4
  195. package/lib/src/generated/rest/PublicPerspectiveInput.js +0 -1
  196. package/lib/src/generated/rest/PublishLanguageRequest.d.ts +0 -5
  197. package/lib/src/generated/rest/PublishLanguageRequest.js +0 -1
  198. package/lib/src/generated/rest/PublishNeighbourhoodRequest.d.ts +0 -6
  199. package/lib/src/generated/rest/PublishNeighbourhoodRequest.js +0 -1
  200. package/lib/src/generated/rest/QueryRequest.d.ts +0 -7
  201. package/lib/src/generated/rest/QueryRequest.js +0 -2
  202. package/lib/src/generated/rest/RemoveLinkRequest.d.ts +0 -5
  203. package/lib/src/generated/rest/RemoveLinkRequest.js +0 -1
  204. package/lib/src/generated/rest/RemoveLinksBulkRequest.d.ts +0 -5
  205. package/lib/src/generated/rest/RemoveLinksBulkRequest.js +0 -1
  206. package/lib/src/generated/rest/RequestCapabilityRequest.d.ts +0 -4
  207. package/lib/src/generated/rest/RequestCapabilityRequest.js +0 -1
  208. package/lib/src/generated/rest/RequestPaymentRequest.d.ts +0 -3
  209. package/lib/src/generated/rest/RequestPaymentRequest.js +0 -2
  210. package/lib/src/generated/rest/RequestVerificationRequest.d.ts +0 -4
  211. package/lib/src/generated/rest/RequestVerificationRequest.js +0 -2
  212. package/lib/src/generated/rest/ResourceInput.d.ts +0 -4
  213. package/lib/src/generated/rest/ResourceInput.js +0 -2
  214. package/lib/src/generated/rest/SetDefaultModelRequest.d.ts +0 -4
  215. package/lib/src/generated/rest/SetDefaultModelRequest.js +0 -1
  216. package/lib/src/generated/rest/SetFreeHostingEnabledRequest.d.ts +0 -3
  217. package/lib/src/generated/rest/SetFreeHostingEnabledRequest.js +0 -2
  218. package/lib/src/generated/rest/SetHotWalletAddressRequest.d.ts +0 -3
  219. package/lib/src/generated/rest/SetHotWalletAddressRequest.js +0 -2
  220. package/lib/src/generated/rest/SetMultiUserRequest.d.ts +0 -3
  221. package/lib/src/generated/rest/SetMultiUserRequest.js +0 -2
  222. package/lib/src/generated/rest/SetOnlineStatusRequest.d.ts +0 -5
  223. package/lib/src/generated/rest/SetOnlineStatusRequest.js +0 -1
  224. package/lib/src/generated/rest/SetStatusRequest.d.ts +0 -3
  225. package/lib/src/generated/rest/SetStatusRequest.js +0 -2
  226. package/lib/src/generated/rest/SetUserFreeAccessRequest.d.ts +0 -4
  227. package/lib/src/generated/rest/SetUserFreeAccessRequest.js +0 -2
  228. package/lib/src/generated/rest/SignMessageRequest.d.ts +0 -3
  229. package/lib/src/generated/rest/SignMessageRequest.js +0 -2
  230. package/lib/src/generated/rest/SignalRequest.d.ts +0 -6
  231. package/lib/src/generated/rest/SignalRequest.js +0 -1
  232. package/lib/src/generated/rest/SubscribeQueryRequest.d.ts +0 -3
  233. package/lib/src/generated/rest/SubscribeQueryRequest.js +0 -2
  234. package/lib/src/generated/rest/SubscribeQueryResponse.d.ts +0 -4
  235. package/lib/src/generated/rest/SubscribeQueryResponse.js +0 -2
  236. package/lib/src/generated/rest/TrustedAgentsRequest.d.ts +0 -3
  237. package/lib/src/generated/rest/TrustedAgentsRequest.js +0 -2
  238. package/lib/src/generated/rest/UnlockAgentRequest.d.ts +0 -4
  239. package/lib/src/generated/rest/UnlockAgentRequest.js +0 -2
  240. package/lib/src/generated/rest/UpdateLinkRequest.d.ts +0 -7
  241. package/lib/src/generated/rest/UpdateLinkRequest.js +0 -1
  242. package/lib/src/generated/rest/UpdatePerspectiveRequest.d.ts +0 -3
  243. package/lib/src/generated/rest/UpdatePerspectiveRequest.js +0 -2
  244. package/lib/src/generated/rest/UpdateProfileRequest.d.ts +0 -5
  245. package/lib/src/generated/rest/UpdateProfileRequest.js +0 -1
  246. package/lib/src/generated/rest/UserStatistics.d.ts +0 -9
  247. package/lib/src/generated/rest/UserStatistics.js +0 -2
  248. package/lib/src/generated/rest/VerificationRequestResult.d.ts +0 -6
  249. package/lib/src/generated/rest/VerificationRequestResult.js +0 -2
  250. package/lib/src/generated/rest/VerifyEmailRequest.d.ts +0 -6
  251. package/lib/src/generated/rest/VerifyEmailRequest.js +0 -2
  252. package/lib/src/generated/rest/VerifySignatureRequest.d.ts +0 -5
  253. package/lib/src/generated/rest/VerifySignatureRequest.js +0 -2
  254. package/lib/src/generated/rest/WriteSettingsRequest.d.ts +0 -3
  255. package/lib/src/generated/rest/WriteSettingsRequest.js +0 -2
  256. package/lib/src/generated/rest/index.d.ts +0 -73
  257. package/lib/src/generated/rest/index.js +0 -8
  258. package/lib/src/generated/rest/routes.d.ts +0 -587
  259. package/lib/src/generated/rest/routes.js +0 -3
  260. package/lib/src/model/query-surreal.d.ts +0 -44
  261. package/lib/src/model/query-surreal.js +0 -249
  262. package/lib/src/model/surreal-utils.d.ts +0 -42
  263. package/lib/src/model/surreal-utils.js +0 -128
  264. package/lib/src/perspectives/PerspectiveProxy.test.d.ts +0 -1
  265. package/lib/src/perspectives/PerspectiveProxy.test.js +0 -34
  266. package/lib/src/restClient.d.ts +0 -52
  267. package/lib/src/restClient.js +0 -227
package/lib/index.cjs CHANGED
@@ -27,6 +27,8 @@ class ApiClient {
27
27
  // ── WebSocket RPC core ──────────────────────────────────────────────────
28
28
  this._ws = null;
29
29
  this._wsCallbacks = new Set();
30
+ this._reconnectCallbacks = new Set();
31
+ this._hasConnectedOnce = false;
30
32
  this._pendingCalls = new Map();
31
33
  this._wsReady = null;
32
34
  this._wsReadyResolve = null;
@@ -34,6 +36,7 @@ class ApiClient {
34
36
  this._wsReconnectDelay = INITIAL_RECONNECT_DELAY_MS;
35
37
  this._wsClosed = false;
36
38
  this._wsPingTimer = null;
39
+ this._ignoredResponseIds = new Set();
37
40
  this.baseUrl = baseUrl;
38
41
  this.token = token;
39
42
  this._webSocketImpl = webSocketImpl;
@@ -68,7 +71,22 @@ class ApiClient {
68
71
  this._wsReadyResolve = resolve;
69
72
  });
70
73
  const url = this._getWsUrl();
71
- const WsImpl = this._webSocketImpl ?? WebSocket;
74
+ // Fallback order: injected impl → globalThis.WebSocket (browsers, Node ≥ 22) → require('ws') (Node ≤ 20).
75
+ // globalThis lookup avoids a ReferenceError on Node 18 where `WebSocket` is not a global.
76
+ const globalWs = globalThis.WebSocket;
77
+ let WsImpl;
78
+ if (this._webSocketImpl) {
79
+ WsImpl = this._webSocketImpl;
80
+ }
81
+ else if (globalWs) {
82
+ WsImpl = globalWs;
83
+ }
84
+ else {
85
+ // Lazy CommonJS require so bundlers targeting browsers don't try to bundle `ws`.
86
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
87
+ const req = eval('require');
88
+ WsImpl = req('ws');
89
+ }
72
90
  const ws = new WsImpl(url);
73
91
  this._ws = ws;
74
92
  ws.onopen = () => {
@@ -78,6 +96,18 @@ class ApiClient {
78
96
  this._wsReadyResolve = null;
79
97
  }
80
98
  this._startPing();
99
+ // Fire reconnect callbacks only on reconnect (not first connect)
100
+ if (this._hasConnectedOnce) {
101
+ for (const cb of this._reconnectCallbacks) {
102
+ try {
103
+ cb();
104
+ }
105
+ catch (e) {
106
+ console.error('Error in reconnect callback:', e);
107
+ }
108
+ }
109
+ }
110
+ this._hasConnectedOnce = true;
81
111
  };
82
112
  ws.onmessage = (event) => {
83
113
  let parsed;
@@ -106,6 +136,13 @@ class ApiClient {
106
136
  }
107
137
  return;
108
138
  }
139
+ // Discard ack responses to cancel requests we sent — they have
140
+ // an id that was never in _pendingCalls, so without this guard
141
+ // they'd leak into subscriber callbacks as spurious events.
142
+ if (id && this._ignoredResponseIds.has(id)) {
143
+ this._ignoredResponseIds.delete(id);
144
+ return;
145
+ }
109
146
  // Server-push event (no id, or id not in pending) → route to subscribers
110
147
  for (const cb of this._wsCallbacks)
111
148
  cb(parsed);
@@ -162,40 +199,130 @@ class ApiClient {
162
199
  if (this._wsReady)
163
200
  await this._wsReady;
164
201
  }
202
+ /**
203
+ * Like `_ready()`, but races the connection against an AbortSignal so
204
+ * that callers don't hang if the signal fires while connecting.
205
+ */
206
+ async _readyOrAbort(signal) {
207
+ if (signal?.aborted) {
208
+ throw new DOMException('Aborted', 'AbortError');
209
+ }
210
+ await new Promise((resolve, reject) => {
211
+ let settled = false;
212
+ const finish = (fn) => {
213
+ if (settled)
214
+ return;
215
+ settled = true;
216
+ if (signal && onAbort) {
217
+ signal.removeEventListener('abort', onAbort);
218
+ }
219
+ fn();
220
+ };
221
+ const onAbort = signal
222
+ ? () => finish(() => reject(new DOMException('Aborted', 'AbortError')))
223
+ : null;
224
+ if (onAbort) {
225
+ signal.addEventListener('abort', onAbort, { once: true });
226
+ }
227
+ this._ready().then(() => finish(resolve), (error) => finish(() => reject(error)));
228
+ });
229
+ }
165
230
  // ── RPC call method ─────────────────────────────────────────────────────
166
231
  /**
167
232
  * Send an RPC call over the WebSocket connection.
168
233
  * @param type - The operation type (e.g. 'agent.get', 'perspective.all')
169
234
  * @param params - Optional parameters to include in the message
170
- * @param timeoutMs - Optional per-call timeout override in ms. Defaults to
171
- * [[DEFAULT_TIMEOUT_MS]]. Use for long-running calls (LLM prompts,
172
- * holochain ops) that legitimately exceed the default.
235
+ * @param options - Optional call options: `signal` (AbortSignal for
236
+ * cancellation) and/or `timeoutMs` (per-call timeout override,
237
+ * defaults to [[DEFAULT_TIMEOUT_MS]] — use for long-running calls
238
+ * like LLM prompts or holochain ops that legitimately exceed it).
173
239
  * @returns Promise that resolves with the result from the server
174
240
  */
175
- async call(type, params, timeoutMs) {
176
- await this._ready();
241
+ async call(type, params, options) {
242
+ // Fast-path: if the caller already aborted, bail out before
243
+ // opening the socket. Matches fetch()'s behaviour.
244
+ const signal = options?.signal;
245
+ if (signal?.aborted) {
246
+ throw new DOMException('Aborted', 'AbortError');
247
+ }
248
+ await this._readyOrAbort(signal);
177
249
  const id = nextId();
178
250
  // Put params under a "params" key to avoid collision with
179
251
  // protocol fields "id" and "type" (e.g. params might contain
180
252
  // { id: modelId } or { type: "db" }).
181
253
  const message = { id, type, params: params || {} };
182
- const effectiveTimeout = timeoutMs ?? DEFAULT_TIMEOUT_MS;
254
+ const effectiveTimeout = options?.timeoutMs ?? DEFAULT_TIMEOUT_MS;
183
255
  return new Promise((resolve, reject) => {
256
+ let abortHandler = null;
257
+ const cleanup = () => {
258
+ if (signal && abortHandler) {
259
+ signal.removeEventListener('abort', abortHandler);
260
+ abortHandler = null;
261
+ }
262
+ };
184
263
  const timer = setTimeout(() => {
185
264
  this._pendingCalls.delete(id);
265
+ cleanup();
186
266
  reject(new RpcError(408, `RPC call '${type}' timed out after ${effectiveTimeout}ms`));
187
267
  }, effectiveTimeout);
268
+ // Wrap resolve/reject so we always clean up the abort listener.
188
269
  this._pendingCalls.set(id, {
189
- resolve: resolve,
190
- reject,
270
+ resolve: (value) => { cleanup(); resolve(value); },
271
+ reject: (reason) => { cleanup(); reject(reason); },
191
272
  timer,
192
273
  });
274
+ if (signal) {
275
+ abortHandler = () => {
276
+ // Drop the pending entry first so the late server
277
+ // reply (if any) routes to the event subscribers,
278
+ // not to a stale resolver.
279
+ this._pendingCalls.delete(id);
280
+ clearTimeout(timer);
281
+ cleanup();
282
+ // Best-effort `request.cancel` — the executor will
283
+ // race the cancellation token against the in-flight
284
+ // handler. If the socket is already gone there's
285
+ // nothing useful we can send; the client side is
286
+ // still aborted either way.
287
+ if (this._ws && this._ws.readyState === 1 /* OPEN */) {
288
+ try {
289
+ const cancelId = nextId();
290
+ this._ignoredResponseIds.add(cancelId);
291
+ // Safety-net eviction: if the executor's ack never
292
+ // arrives (e.g. the socket drops right after we
293
+ // send request.cancel), the normal cleanup path
294
+ // (deleting the id when its response lands) never
295
+ // fires and the entry would live in this set for
296
+ // the lifetime of the client. Bound it instead —
297
+ // DEFAULT_TIMEOUT_MS is already the ceiling every
298
+ // other in-flight call uses, so an ack that hasn't
299
+ // shown up by then isn't coming.
300
+ setTimeout(() => {
301
+ this._ignoredResponseIds.delete(cancelId);
302
+ }, DEFAULT_TIMEOUT_MS);
303
+ this._ws.send(JSON.stringify({
304
+ id: cancelId,
305
+ type: 'request.cancel',
306
+ params: { targetId: id },
307
+ }));
308
+ }
309
+ catch (e) {
310
+ // Swallow — the user-visible failure mode is the
311
+ // AbortError below; a socket send failure here
312
+ // doesn't change client semantics.
313
+ }
314
+ }
315
+ reject(new DOMException('Aborted', 'AbortError'));
316
+ };
317
+ signal.addEventListener('abort', abortHandler, { once: true });
318
+ }
193
319
  if (this._ws && this._ws.readyState === 1 /* OPEN */) {
194
320
  this._ws.send(JSON.stringify(message));
195
321
  }
196
322
  else {
197
323
  this._pendingCalls.delete(id);
198
324
  clearTimeout(timer);
325
+ cleanup();
199
326
  reject(new RpcError(503, 'WebSocket not connected'));
200
327
  }
201
328
  });
@@ -233,6 +360,13 @@ class ApiClient {
233
360
  this._wsReady = null;
234
361
  }
235
362
  }
363
+ /** Register a callback that fires after a successful WebSocket reconnect.
364
+ * Does NOT fire on the initial connection — only on reconnects.
365
+ * Returns an unsubscribe function. */
366
+ onReconnect(callback) {
367
+ this._reconnectCallbacks.add(callback);
368
+ return () => { this._reconnectCallbacks.delete(callback); };
369
+ }
236
370
  /** Close all open WebSocket connections and reject pending calls. */
237
371
  closeAll() {
238
372
  // Reject pending calls
@@ -243,6 +377,12 @@ class ApiClient {
243
377
  this._pendingCalls.clear();
244
378
  this._closeWs();
245
379
  this._wsCallbacks.clear();
380
+ this._reconnectCallbacks.clear();
381
+ // Reset the first-connect gate so a reused client (closeAll() →
382
+ // later call()/subscribe() reopening via _ensureWs) does not fire
383
+ // freshly registered onReconnect callbacks on the initial open of
384
+ // the new connection — see the contract on onReconnect().
385
+ this._hasConnectedOnce = false;
246
386
  }
247
387
  }
248
388
 
@@ -1290,6 +1430,13 @@ class SHACLShape {
1290
1430
  target: prop.path
1291
1431
  });
1292
1432
  // Constraints
1433
+ if (prop.ordering) {
1434
+ links.push({
1435
+ source: propShapeId,
1436
+ predicate: "ad4m://ordering",
1437
+ target: `literal:string:${prop.ordering}`
1438
+ });
1439
+ }
1293
1440
  if (prop.datatype) {
1294
1441
  links.push({
1295
1442
  source: propShapeId,
@@ -1536,6 +1683,10 @@ class SHACLShape {
1536
1683
  const datatypeLink = links.find(l => l.source === propShapeId && l.predicate === "sh://datatype");
1537
1684
  if (datatypeLink)
1538
1685
  prop.datatype = datatypeLink.target;
1686
+ const orderingLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://ordering");
1687
+ if (orderingLink) {
1688
+ prop.ordering = orderingLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
1689
+ }
1539
1690
  const nodeKindLink = links.find(l => l.source === propShapeId && l.predicate === "sh://nodeKind");
1540
1691
  if (nodeKindLink) {
1541
1692
  prop.nodeKind = nodeKindLink.target.replace('sh://', '');
@@ -1773,6 +1924,11 @@ class SHACLShape {
1773
1924
  transform: p.transform,
1774
1925
  interpretation_hint: p.interpretationHint,
1775
1926
  identity: p.identity,
1927
+ // The backend reads the ordering declaration back from the
1928
+ // `ad4m://ordering` link that `parse_shacl_to_links` writes from this
1929
+ // field. `ensureSubjectClass` ships `toJSON()`, so omitting it here
1930
+ // leaves `@HasMany({ ordering })` inert no matter what `toLinks()` does.
1931
+ ordering: p.ordering,
1776
1932
  })),
1777
1933
  constructor_actions: this.constructor_actions,
1778
1934
  destructor_actions: this.destructor_actions,
@@ -1820,6 +1976,7 @@ class SHACLShape {
1820
1976
  transform: p.transform,
1821
1977
  interpretationHint: p.interpretation_hint,
1822
1978
  identity: p.identity,
1979
+ ordering: p.ordering,
1823
1980
  });
1824
1981
  }
1825
1982
  if (json.constructor_actions) {
@@ -1940,6 +2097,18 @@ interpretationHint) {
1940
2097
  const propMeta = properties[propName];
1941
2098
  if (!propMeta.through)
1942
2099
  continue; // Skip properties without predicates
2100
+ // `@BelongsToOne`/`@BelongsToMany` register in both maps: the relation
2101
+ // registry describes the edge, and `applyPropertyMetadata` marks the
2102
+ // accessor read-only so the non-owning side gets no setter. Both loops
2103
+ // then emitted a shape for it, so an inverse relation appeared twice in
2104
+ // the generated SHACL — once thinly, from here, and once with its target
2105
+ // class, polymorphism and ordering, from the relation loop below.
2106
+ //
2107
+ // The relation loop is the complete description, so this one stands
2108
+ // aside. Skipping by presence in the relation map rather than by kind
2109
+ // keeps it right for any future decorator that registers in both.
2110
+ if (allRelationsMeta[propName])
2111
+ continue;
1943
2112
  const propShape = {
1944
2113
  name: propName,
1945
2114
  path: propMeta.through,
@@ -2104,10 +2273,24 @@ interpretationHint) {
2104
2273
  if (relMeta.filter === false) {
2105
2274
  relShape.filter = false;
2106
2275
  }
2276
+ // Ordering is declared in the type system so the executor can act on it
2277
+ // for every writer, not just this client.
2278
+ if (relMeta.ordering) {
2279
+ relShape.ordering = relMeta.ordering.strategy;
2280
+ }
2107
2281
  // AD4M-specific metadata
2108
2282
  if (relMeta.local !== undefined) {
2109
2283
  relShape.local = relMeta.local;
2110
2284
  }
2285
+ // Per-relation interpretation hint — sentence-level meaning that
2286
+ // steers the harness LLM's `_propose_link_child` `predicate` field
2287
+ // description. Read back on the Rust side by
2288
+ // `ShaclProperty.interpretation_hint` and rendered into the tool
2289
+ // schema alongside the predicate URI enum (so `basedOn` reads
2290
+ // "prior beliefs this intention derives from", not just "some link").
2291
+ if (relMeta.interpretationHint) {
2292
+ relShape.interpretationHint = relMeta.interpretationHint;
2293
+ }
2111
2294
  // Adder / Remover actions — only meaningful for relations backed
2112
2295
  // by a real link predicate. Getter-only relations are read-only.
2113
2296
  if (relMeta.predicate) {
@@ -2244,6 +2427,25 @@ interpretationHint) {
2244
2427
  }
2245
2428
  shape.addProperty(relShape);
2246
2429
  }
2430
+ // ── Ordering links ─────────────────────────────────────────────────
2431
+ // Ordering entries are stored on the *parent*, under one shared predicate,
2432
+ // so that reconstruction needs no extra query: they arrive with the
2433
+ // instance's own links. That only works if the instance query asks for them,
2434
+ // and it builds its predicate filter from the shape's declared paths — so a
2435
+ // class owning any ordered collection has to declare the predicate, or the
2436
+ // very links the ordering depends on are filtered out of the read that needs
2437
+ // them.
2438
+ //
2439
+ // One entry covers every ordered relation on the class; each entry names the
2440
+ // relation it belongs to.
2441
+ const hasOrderedRelation = Object.values(allRelationsMeta).some((m) => m.ordering);
2442
+ if (hasOrderedRelation) {
2443
+ shape.addProperty({
2444
+ name: '_collectionOrder',
2445
+ path: 'ad4m://collection_order',
2446
+ nodeKind: 'IRI',
2447
+ });
2448
+ }
2247
2449
  // Always set constructor and destructor actions on the shape, even
2248
2450
  // when empty. An empty array serialises to `literal:string:[]`
2249
2451
  // which the Rust executor parses as a valid (no-op) command list,
@@ -2833,35 +3035,57 @@ function resolveRelationArgs(first, second) {
2833
3035
  const opts = typeof first === 'function'
2834
3036
  ? { ...(second || {}), target: first }
2835
3037
  : first;
2836
- // getter is mutually exclusive with through, target, and where
3038
+ // `where` and `filter: false` contradict each other on every relation,
3039
+ // getter-backed ones included — checked before the getter path returns.
3040
+ if (opts.where && opts.filter === false) {
3041
+ throw new Error('Relation decorator: `where` and `filter: false` are contradictory. ' +
3042
+ '`where` adds filtering constraints; `filter: false` disables filtering.');
3043
+ }
3044
+ // getter is mutually exclusive with through
2837
3045
  if (opts.getter) {
2838
3046
  if (opts.through) {
2839
3047
  throw new Error('Relation decorator: `getter` and `through` are mutually exclusive. ' +
2840
3048
  'Use `getter` alone for custom read-only relations, or `through` ' +
2841
3049
  '(with optional `target`) for standard link-based relations.');
2842
3050
  }
2843
- if (opts.target) {
2844
- throw new Error('Relation decorator: `getter` and `target` are mutually exclusive. ' +
2845
- '`target` auto-generates a conformance getter from the model shape; ' +
2846
- 'providing both is contradictory.');
2847
- }
2848
- if (opts.where) {
2849
- throw new Error('Relation decorator: `where` and `getter` are mutually exclusive. ' +
2850
- 'Use `where` for DSL-based filtering, or `getter` for raw getter expression.');
2851
- }
3051
+ // `target` and `where` are NOT mutually exclusive with `getter`.
3052
+ //
3053
+ // `target` does two separable jobs: it auto-derives a conformance
3054
+ // getter, and it names the class the relation's values hydrate into.
3055
+ // Only the first conflicts with an explicit getter, and `buildSHACL`
3056
+ // already resolves that on its own — an explicit getter wins the getter
3057
+ // slot, while `sh:class` / `ad4m:targetClassName` are emitted from
3058
+ // `target` independently.
3059
+ //
3060
+ // Refusing the pair cost the one thing a custom getter is for. A getter
3061
+ // expresses a traversal the link-shaped DSL cannot — most usefully
3062
+ // through a reified edge, where the connection is a record rather than
3063
+ // a predicate:
3064
+ //
3065
+ // @HasMany({
3066
+ // getter: "SELECT ?target WHERE { \
3067
+ // ?citation <paper://cites_from> <Base> . \
3068
+ // ?citation <paper://cites_to> ?target . }",
3069
+ // target: () => Paper,
3070
+ // })
3071
+ // cited: Paper[] = [];
3072
+ //
3073
+ // Without `target` the relation has no target class, so `include` on it
3074
+ // resolves a shape named "" and fails — leaving a traversal that can
3075
+ // only ever return bare URIs. With it, the values hydrate like any other
3076
+ // relation, because getters are evaluated before include resolution.
3077
+ //
3078
+ // `where` is the same story: the executor applies post-getter where
3079
+ // filters specifically to getter-backed relations
3080
+ // (`apply_where_filter_to_relation`), and emitting `wherePredicates`
3081
+ // needs `target` to resolve the target's metadata — so the runtime is
3082
+ // built for all three together and only this check said otherwise.
2852
3083
  return opts;
2853
3084
  }
2854
3085
  // Default predicate when not provided
2855
3086
  if (!opts.through) {
2856
3087
  opts.through = 'ad4m://has_child';
2857
3088
  }
2858
- // where validation
2859
- if (opts.where) {
2860
- if (opts.filter === false) {
2861
- throw new Error('Relation decorator: `where` and `filter: false` are contradictory. ' +
2862
- '`where` adds filtering constraints; `filter: false` disables filtering.');
2863
- }
2864
- }
2865
3089
  return opts;
2866
3090
  }
2867
3091
  function HasMany(first, second) {
@@ -2881,6 +3105,10 @@ function HasMany(first, second) {
2881
3105
  ...(opts.filter !== undefined && { filter: opts.filter }),
2882
3106
  ...(opts.where && { where: opts.where }),
2883
3107
  ...(opts.datatype && { datatype: opts.datatype }),
3108
+ ...(opts.polymorphic && { polymorphic: opts.polymorphic }),
3109
+ ...(opts.instantiateAs && { instantiateAs: opts.instantiateAs }),
3110
+ ...(opts.ordering && { ordering: opts.ordering }),
3111
+ ...(opts.interpretationHint && { interpretationHint: opts.interpretationHint }),
2884
3112
  };
2885
3113
  const relKey = key;
2886
3114
  // Only add mutation methods when a predicate is available
@@ -2915,6 +3143,10 @@ function HasOne(first, second) {
2915
3143
  ...(opts.filter !== undefined && { filter: opts.filter }),
2916
3144
  ...(opts.where && { where: opts.where }),
2917
3145
  ...(opts.datatype && { datatype: opts.datatype }),
3146
+ ...(opts.polymorphic && { polymorphic: opts.polymorphic }),
3147
+ ...(opts.instantiateAs && { instantiateAs: opts.instantiateAs }),
3148
+ ...(opts.ordering && { ordering: opts.ordering }),
3149
+ ...(opts.interpretationHint && { interpretationHint: opts.interpretationHint }),
2918
3150
  };
2919
3151
  const relKey = key;
2920
3152
  if (opts.through) {
@@ -2924,15 +3156,23 @@ function HasOne(first, second) {
2924
3156
  readOnly: false,
2925
3157
  local: opts.local,
2926
3158
  })(target, key);
2927
- // Add prototype methods for add/remove/set (mirroring @HasMany)
2928
- target[`add${capitalize(relKey)}`] = async function (arg) {
2929
- return this.addRelationValue(relKey, arg);
3159
+ // Add prototype methods for add/remove/set (mirroring @HasMany).
3160
+ //
3161
+ // `batchId` is part of that mirroring: without it a to-one link
3162
+ // cannot join a write group, so anything that creates a record and
3163
+ // then points it at something has to commit twice and every
3164
+ // subscriber sees the state in between — a record whose to-one
3165
+ // relation is still empty. Anything rendering from a subscription
3166
+ // therefore has a frame in which the record exists and points at
3167
+ // nothing.
3168
+ target[`add${capitalize(relKey)}`] = async function (arg, batchId) {
3169
+ return this.addRelationValue(relKey, arg, batchId);
2930
3170
  };
2931
- target[`remove${capitalize(relKey)}`] = async function (arg) {
2932
- return this.removeRelationValue(relKey, arg);
3171
+ target[`remove${capitalize(relKey)}`] = async function (arg, batchId) {
3172
+ return this.removeRelationValue(relKey, arg, batchId);
2933
3173
  };
2934
- target[`set${capitalize(relKey)}`] = async function (arg) {
2935
- return this.setRelationValues(relKey, arg);
3174
+ target[`set${capitalize(relKey)}`] = async function (arg, batchId) {
3175
+ return this.setRelationValues(relKey, arg, batchId);
2936
3176
  };
2937
3177
  }
2938
3178
  else {
@@ -2956,6 +3196,10 @@ function BelongsToOne(first, second) {
2956
3196
  ...(opts.filter !== undefined && { filter: opts.filter }),
2957
3197
  ...(opts.where && { where: opts.where }),
2958
3198
  ...(opts.datatype && { datatype: opts.datatype }),
3199
+ ...(opts.polymorphic && { polymorphic: opts.polymorphic }),
3200
+ ...(opts.instantiateAs && { instantiateAs: opts.instantiateAs }),
3201
+ ...(opts.ordering && { ordering: opts.ordering }),
3202
+ ...(opts.interpretationHint && { interpretationHint: opts.interpretationHint }),
2959
3203
  };
2960
3204
  if (opts.through) {
2961
3205
  // Read-only property (the owning side manages the link)
@@ -2986,6 +3230,10 @@ function BelongsToMany(first, second) {
2986
3230
  ...(opts.filter !== undefined && { filter: opts.filter }),
2987
3231
  ...(opts.where && { where: opts.where }),
2988
3232
  ...(opts.datatype && { datatype: opts.datatype }),
3233
+ ...(opts.polymorphic && { polymorphic: opts.polymorphic }),
3234
+ ...(opts.instantiateAs && { instantiateAs: opts.instantiateAs }),
3235
+ ...(opts.ordering && { ordering: opts.ordering }),
3236
+ ...(opts.interpretationHint && { interpretationHint: opts.interpretationHint }),
2989
3237
  };
2990
3238
  // @BelongsToMany is the inverse/read-only side — do NOT generate add*/remove*/set*
2991
3239
  // prototype methods. Mutation must go through the owning side's @HasMany decorator.
@@ -3061,59 +3309,82 @@ function queryCacheSize() {
3061
3309
  return cache.size;
3062
3310
  }
3063
3311
 
3312
+ /**
3313
+ * Runtime shape check for a decoded `ModelQuery`. Deserialization paths use
3314
+ * this to guard against malformed guard arrays leaking into flow metadata
3315
+ * (an untyped `Array.isArray` would happily accept `[null]` or `[{}]`).
3316
+ * Only the mandatory `className: string` field is enforced — richer
3317
+ * validation stays with the runtime engine that will actually execute the
3318
+ * query.
3319
+ */
3320
+ function isModelQueryShape(v) {
3321
+ if (typeof v !== "object" ||
3322
+ v === null ||
3323
+ typeof v.className !== "string" ||
3324
+ v.className.length === 0) {
3325
+ return false;
3326
+ }
3327
+ const or = v.or;
3328
+ if (or !== undefined) {
3329
+ if (!Array.isArray(or) || !or.every(isModelQueryShape))
3330
+ return false;
3331
+ }
3332
+ return true;
3333
+ }
3334
+ /**
3335
+ * Runtime shape check for a decoded `ConsensusRule`. Enforces the one
3336
+ * mandatory field (`n: number` with a sane range) and, when `fromRole`
3337
+ * is present, that it's a valid ModelQuery. A malformed literal (e.g.
3338
+ * `{ n: "many" }` or `{ n: 1, fromRole: null }`) leaves the field unset
3339
+ * rather than becoming corrupt flow metadata that downstream engines
3340
+ * would trip over.
3341
+ */
3342
+ function isConsensusRuleShape(v) {
3343
+ if (typeof v !== "object" || v === null)
3344
+ return false;
3345
+ const n = v.n;
3346
+ if (typeof n !== "number" || !Number.isFinite(n) || n < 1 || !Number.isInteger(n)) {
3347
+ return false;
3348
+ }
3349
+ const fromRole = v.fromRole;
3350
+ if (fromRole !== undefined && !isModelQueryShape(fromRole))
3351
+ return false;
3352
+ return true;
3353
+ }
3064
3354
  /**
3065
3355
  * SHACL Flow - represents a state machine for AD4M expressions
3066
3356
  *
3067
3357
  * Flows define:
3068
- * - Which expressions can enter the flow (flowable condition)
3069
- * - What states exist and how to detect them (via link patterns)
3070
- * - How to transition between states (via actions)
3358
+ * - Which expressions can enter the flow (via `inputTypes`)
3359
+ * - What states exist and their per-state guards (via `requires`)
3360
+ * - How to transition between states (via transitions + consensus rules)
3361
+ *
3362
+ * State lives on the on-graph `FlowInstanceRecord.currentState` and is
3363
+ * read/written through the `FlowInstance` wrapper class
3364
+ * ({@link FlowInstance.start} / {@link FlowInstance.findAll}) — see design
3365
+ * doc §4.3/§5.
3071
3366
  *
3072
3367
  * @example
3073
3368
  * ```typescript
3074
3369
  * const todoFlow = new SHACLFlow('todo://TODO', 'todo://');
3075
3370
  *
3076
3371
  * // Any expression can become a TODO
3077
- * todoFlow.flowable = 'any';
3078
- *
3079
- * // Define states
3080
- * todoFlow.addState({
3081
- * name: 'ready',
3082
- * value: 0,
3083
- * stateCheck: { predicate: 'todo://state', target: 'todo://ready' }
3084
- * });
3085
- * todoFlow.addState({
3086
- * name: 'doing',
3087
- * value: 0.5,
3088
- * stateCheck: { predicate: 'todo://state', target: 'todo://doing' }
3089
- * });
3090
- * todoFlow.addState({
3091
- * name: 'done',
3092
- * value: 1,
3093
- * stateCheck: { predicate: 'todo://state', target: 'todo://done' }
3094
- * });
3372
+ * todoFlow.inputTypes = ['any'];
3095
3373
  *
3096
- * // Define start action
3097
- * todoFlow.startAction = [{
3098
- * action: 'addLink',
3099
- * source: 'this',
3100
- * predicate: 'todo://state',
3101
- * target: 'todo://ready'
3102
- * }];
3374
+ * todoFlow.addState({ name: 'ready', value: 0 });
3375
+ * todoFlow.addState({ name: 'doing', value: 0.5 });
3376
+ * todoFlow.addState({ name: 'done', value: 1 });
3103
3377
  *
3104
- * // Define transitions
3105
3378
  * todoFlow.addTransition({
3106
3379
  * actionName: 'Start',
3107
3380
  * fromState: 'ready',
3108
3381
  * toState: 'doing',
3109
- * actions: [
3110
- * { action: 'addLink', source: 'this', predicate: 'todo://state', target: 'todo://doing' },
3111
- * { action: 'removeLink', source: 'this', predicate: 'todo://state', target: 'todo://ready' }
3112
- * ]
3382
+ * actions: [],
3113
3383
  * });
3114
3384
  *
3115
- * // Store in perspective
3385
+ * // Register on the perspective and mint an instance on a subject.
3116
3386
  * await perspective.addFlow('TODO', todoFlow);
3387
+ * const instance = await FlowInstance.start(perspective, 'TODO', 'expr://123');
3117
3388
  * ```
3118
3389
  */
3119
3390
  class SHACLFlow {
@@ -3123,11 +3394,41 @@ class SHACLFlow {
3123
3394
  * @param namespace - Namespace for URIs (e.g., "todo://")
3124
3395
  */
3125
3396
  constructor(name, namespace) {
3126
- /** Condition for which expressions can start this flow */
3127
- this.flowable = "any";
3128
- /** Actions to execute when starting the flow */
3129
- this.startAction = [];
3130
- /** States in this flow */
3397
+ /**
3398
+ * Subject-class URIs the flow accepts as its base expression.
3399
+ *
3400
+ * Design doc §4.1: a flow's *typed input*. When an
3401
+ * expression whose class matches any URI in this array enters scope,
3402
+ * the flow-spawn engine considers it a candidate base. Superseded
3403
+ * the older link-level `flowable: LinkPattern` primitive — model-level
3404
+ * matching by subject class instead of link matching. Empty array =
3405
+ * flow declares no typed input. The `"any"` sentinel is accepted as
3406
+ * a wildcard for tests and legacy flows.
3407
+ */
3408
+ this.inputTypes = [];
3409
+ /**
3410
+ * Subject-class URIs the flow must produce (linked to the base) for a
3411
+ * run to count as complete.
3412
+ *
3413
+ * Design doc §4.1: a flow's *typed output*. Two jobs:
3414
+ * (a) documentation for stateful flows — records what a completed run
3415
+ * leaves in the graph; (b) **terminal condition** for zero-state flows —
3416
+ * a flow with no `FlowState`s completes when at least one instance of
3417
+ * each `outputTypes` entry exists in scope and is linked to the base,
3418
+ * and `consensusRule` fires. This is what makes "Like" a first-class
3419
+ * flow with no state machine.
3420
+ */
3421
+ this.outputTypes = [];
3422
+ /**
3423
+ * States in this flow.
3424
+ *
3425
+ * **Ordering convention (James PR #929 R9):** the array is stored sorted
3426
+ * ascending by `value`. `states[0]` is the initial state — the one
3427
+ * {@link FlowInstance.start} mints a fresh instance into. A flow author
3428
+ * who wants a specific state as the entry point must give it the lowest
3429
+ * `value` in the set. `fromLinks` enforces this sort, so link-order on
3430
+ * the graph never dictates the initial state.
3431
+ */
3131
3432
  this._states = [];
3132
3433
  /** Transitions between states */
3133
3434
  this._transitions = [];
@@ -3195,27 +3496,63 @@ class SHACLFlow {
3195
3496
  predicate: "ad4m://flowName",
3196
3497
  target: Literal.from(this.name).toUrl()
3197
3498
  });
3198
- // Flowable condition
3199
- if (this.flowable === "any") {
3499
+ // Top-level interpretation hint (optional, drives AI state suggestion).
3500
+ // Empty strings are treated as "unset" so a round-trip through the graph
3501
+ // doesn't materialise an empty-hint predicate that consumers would then
3502
+ // read back as a meaningful value.
3503
+ if (this.interpretationHint) {
3200
3504
  links.push({
3201
3505
  source: flowUri,
3202
- predicate: "ad4m://flowable",
3203
- target: "ad4m://any"
3506
+ predicate: "ad4m://interpretationHint",
3507
+ target: Literal.from(this.interpretationHint).toUrl()
3204
3508
  });
3205
3509
  }
3206
- else {
3510
+ // Typed I/O (flow-level, design §4.1). Both arrays are only
3511
+ // serialized when non-empty — an empty list is indistinguishable
3512
+ // from "unset" for a round-trip, and emitting one would give
3513
+ // downstream consumers a meaningless predicate to interpret.
3514
+ if (this.inputTypes.length > 0) {
3515
+ links.push({
3516
+ source: flowUri,
3517
+ predicate: "ad4m://inputTypes",
3518
+ target: `literal:string:${encodeURIComponent(JSON.stringify(this.inputTypes))}`
3519
+ });
3520
+ }
3521
+ if (this.outputTypes.length > 0) {
3522
+ links.push({
3523
+ source: flowUri,
3524
+ predicate: "ad4m://outputTypes",
3525
+ target: `literal:string:${encodeURIComponent(JSON.stringify(this.outputTypes))}`
3526
+ });
3527
+ }
3528
+ // Flow-level `creationHint` — same empty-string-is-unset guard as
3529
+ // `interpretationHint`, same reason (round-trip fidelity).
3530
+ if (this.creationHint) {
3531
+ links.push({
3532
+ source: flowUri,
3533
+ predicate: "ad4m://creationHint",
3534
+ target: Literal.from(this.creationHint).toUrl()
3535
+ });
3536
+ }
3537
+ // Flow-level `context` — background queries the LLM sees but not
3538
+ // guard evidence. Single JSON literal, consumers parse back.
3539
+ if (this.context && this.context.length > 0) {
3207
3540
  links.push({
3208
3541
  source: flowUri,
3209
- predicate: "ad4m://flowable",
3210
- target: `literal:string:${encodeURIComponent(JSON.stringify(this.flowable))}`
3542
+ predicate: "ad4m://context",
3543
+ target: `literal:string:${encodeURIComponent(JSON.stringify(this.context))}`
3211
3544
  });
3212
3545
  }
3213
- // Start action
3214
- if (this.startAction.length > 0) {
3546
+ // Flow-level `consensusRule` — default for state transitions when a
3547
+ // FlowState omits its own rule; also the terminal-firing rule for
3548
+ // zero-state flows. Serialized as one JSON literal (the shape is
3549
+ // fixed and cheap to parse; consistent with `context` / `requires`
3550
+ // so consumers only need one parser).
3551
+ if (this.consensusRule) {
3215
3552
  links.push({
3216
3553
  source: flowUri,
3217
- predicate: "ad4m://startAction",
3218
- target: `literal:string:${encodeURIComponent(JSON.stringify(this.startAction))}`
3554
+ predicate: "ad4m://consensusRule",
3555
+ target: `literal:string:${encodeURIComponent(JSON.stringify(this.consensusRule))}`
3219
3556
  });
3220
3557
  }
3221
3558
  // States
@@ -3245,12 +3582,45 @@ class SHACLFlow {
3245
3582
  predicate: "ad4m://stateValue",
3246
3583
  target: Literal.from(state.value).toUrl()
3247
3584
  });
3248
- // State check pattern
3249
- links.push({
3250
- source: stateUri,
3251
- predicate: "ad4m://stateCheck",
3252
- target: `literal:string:${encodeURIComponent(JSON.stringify(state.stateCheck))}`
3253
- });
3585
+ // Per-state interpretation hint (optional, drives AI state suggestion).
3586
+ // Empty strings treated as unset — same rationale as the flow-level hint.
3587
+ if (state.interpretationHint) {
3588
+ links.push({
3589
+ source: stateUri,
3590
+ predicate: "ad4m://interpretationHint",
3591
+ target: Literal.from(state.interpretationHint).toUrl()
3592
+ });
3593
+ }
3594
+ // Per-state `requires` guard — array of ModelQueries, AND-combined.
3595
+ // Serialized as one JSON string on `ad4m://requires`. Consumers
3596
+ // (state-transition engine, `flow.availableActions`) parse back.
3597
+ if (state.requires && state.requires.length > 0) {
3598
+ links.push({
3599
+ source: stateUri,
3600
+ predicate: "ad4m://requires",
3601
+ target: `literal:string:${encodeURIComponent(JSON.stringify(state.requires))}`
3602
+ });
3603
+ }
3604
+ // Per-state `semanticCheck` hint — optional English confirmation
3605
+ // that runs after `requires` matches, for states where structural
3606
+ // presence isn't sufficient evidence. Empty string = unset.
3607
+ if (state.semanticCheck) {
3608
+ links.push({
3609
+ source: stateUri,
3610
+ predicate: "ad4m://semanticCheck",
3611
+ target: Literal.from(state.semanticCheck).toUrl()
3612
+ });
3613
+ }
3614
+ // Per-state `consensusRule` override — one JSON literal on the
3615
+ // state, same predicate name as the flow-level rule but scoped by
3616
+ // source URI so the reader can tell them apart.
3617
+ if (state.consensusRule) {
3618
+ links.push({
3619
+ source: stateUri,
3620
+ predicate: "ad4m://consensusRule",
3621
+ target: `literal:string:${encodeURIComponent(JSON.stringify(state.consensusRule))}`
3622
+ });
3623
+ }
3254
3624
  }
3255
3625
  // Transitions
3256
3626
  for (const transition of this._transitions) {
@@ -3315,31 +3685,96 @@ class SHACLFlow {
3315
3685
  const namespace = withoutSuffix.slice(0, lastSlashOrColon + 1);
3316
3686
  const name = withoutSuffix.slice(lastSlashOrColon + 1);
3317
3687
  const flow = new SHACLFlow(name, namespace);
3318
- // Find flowable condition
3319
- const flowableLink = links.find(l => l.source === flowUri && l.predicate === "ad4m://flowable");
3320
- if (flowableLink) {
3321
- if (flowableLink.target === "ad4m://any") {
3322
- flow.flowable = "any";
3688
+ // Find top-level interpretation hint. Only accept a decoded value that
3689
+ // is a non-empty string — malformed literals (Literal.get() can return
3690
+ // an object, number, etc.) leave the field unset rather than becoming
3691
+ // corrupt flow metadata.
3692
+ const flowHintLink = links.find(l => l.source === flowUri && l.predicate === "ad4m://interpretationHint");
3693
+ if (flowHintLink) {
3694
+ try {
3695
+ const decoded = Literal.fromUrl(flowHintLink.target).get();
3696
+ if (typeof decoded === "string" && decoded.length > 0) {
3697
+ flow.interpretationHint = decoded;
3698
+ }
3323
3699
  }
3324
- else {
3325
- try {
3326
- const jsonStr = flowableLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
3327
- flow.flowable = JSON.parse(decodeURIComponent(jsonStr));
3700
+ catch {
3701
+ // Ignore parse errors — leave unset.
3702
+ }
3703
+ }
3704
+ // Find typed I/O (flow-level, design §4.1). Both arrays validated
3705
+ // element-wise — only accept string[] payloads. A malformed literal
3706
+ // (`[null]`, `[42]`, non-array) leaves the field as its default
3707
+ // empty array rather than corrupting flow metadata.
3708
+ const inputTypesLink = links.find(l => l.source === flowUri && l.predicate === "ad4m://inputTypes");
3709
+ if (inputTypesLink) {
3710
+ try {
3711
+ const jsonStr = inputTypesLink.target.replace(/^literal:\/\/string:|^literal:string:/, "");
3712
+ const parsed = JSON.parse(decodeURIComponent(jsonStr));
3713
+ if (Array.isArray(parsed) && parsed.every(v => typeof v === "string" && v.length > 0)) {
3714
+ flow.inputTypes = parsed;
3328
3715
  }
3329
- catch {
3330
- flow.flowable = "any";
3716
+ }
3717
+ catch {
3718
+ // Ignore parse errors — leave as default empty array.
3719
+ }
3720
+ }
3721
+ const outputTypesLink = links.find(l => l.source === flowUri && l.predicate === "ad4m://outputTypes");
3722
+ if (outputTypesLink) {
3723
+ try {
3724
+ const jsonStr = outputTypesLink.target.replace(/^literal:\/\/string:|^literal:string:/, "");
3725
+ const parsed = JSON.parse(decodeURIComponent(jsonStr));
3726
+ if (Array.isArray(parsed) && parsed.every(v => typeof v === "string" && v.length > 0)) {
3727
+ flow.outputTypes = parsed;
3331
3728
  }
3332
3729
  }
3730
+ catch {
3731
+ // Ignore parse errors — leave as default empty array.
3732
+ }
3333
3733
  }
3334
- // Find start action
3335
- const startActionLink = links.find(l => l.source === flowUri && l.predicate === "ad4m://startAction");
3336
- if (startActionLink) {
3734
+ // Find flow-level `creationHint`. Non-empty-string guard — same
3735
+ // rationale as `interpretationHint`.
3736
+ const creationHintLink = links.find(l => l.source === flowUri && l.predicate === "ad4m://creationHint");
3737
+ if (creationHintLink) {
3337
3738
  try {
3338
- const jsonStr = startActionLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
3339
- flow.startAction = JSON.parse(decodeURIComponent(jsonStr));
3739
+ const decoded = Literal.fromUrl(creationHintLink.target).get();
3740
+ if (typeof decoded === "string" && decoded.length > 0) {
3741
+ flow.creationHint = decoded;
3742
+ }
3340
3743
  }
3341
3744
  catch {
3342
- // Ignore parse errors
3745
+ // Ignore parse errors — leave unset.
3746
+ }
3747
+ }
3748
+ // Find flow-level `context` — same ModelQuery-shape guard as
3749
+ // FlowState.requires (rejects `[null]`, `[{}]`, non-string
3750
+ // `className`).
3751
+ const contextLink = links.find(l => l.source === flowUri && l.predicate === "ad4m://context");
3752
+ if (contextLink) {
3753
+ try {
3754
+ const jsonStr = contextLink.target.replace(/^literal:\/\/string:|^literal:string:/, "");
3755
+ const parsed = JSON.parse(decodeURIComponent(jsonStr));
3756
+ if (Array.isArray(parsed) && parsed.every(isModelQueryShape)) {
3757
+ flow.context = parsed;
3758
+ }
3759
+ }
3760
+ catch {
3761
+ // Ignore parse errors — leave unset.
3762
+ }
3763
+ }
3764
+ // Find flow-level `consensusRule`. Reject malformed literals
3765
+ // (missing `n`, non-integer `n`, invalid `fromRole`) so the runtime
3766
+ // engine never has to defensively re-validate a stored rule.
3767
+ const consensusRuleLink = links.find(l => l.source === flowUri && l.predicate === "ad4m://consensusRule");
3768
+ if (consensusRuleLink) {
3769
+ try {
3770
+ const jsonStr = consensusRuleLink.target.replace(/^literal:\/\/string:|^literal:string:/, "");
3771
+ const parsed = JSON.parse(decodeURIComponent(jsonStr));
3772
+ if (isConsensusRuleShape(parsed)) {
3773
+ flow.consensusRule = parsed;
3774
+ }
3775
+ }
3776
+ catch {
3777
+ // Ignore parse errors — leave unset.
3343
3778
  }
3344
3779
  }
3345
3780
  // Find states
@@ -3356,20 +3791,85 @@ class SHACLFlow {
3356
3791
  // Get state value
3357
3792
  const valueLink = links.find(l => l.source === stateUri && l.predicate === "ad4m://stateValue");
3358
3793
  const stateValue = valueLink ? Literal.fromUrl(valueLink.target).get() : 0;
3359
- // Get state check
3360
- const checkLink = links.find(l => l.source === stateUri && l.predicate === "ad4m://stateCheck");
3361
- let stateCheck = { predicate: "", target: "" };
3362
- if (checkLink) {
3794
+ // Get per-state interpretation hint (optional). Same non-empty-string
3795
+ // guard as the flow-level hint.
3796
+ const hintLink = links.find(l => l.source === stateUri && l.predicate === "ad4m://interpretationHint");
3797
+ let interpretationHint;
3798
+ if (hintLink) {
3363
3799
  try {
3364
- const jsonStr = checkLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
3365
- stateCheck = JSON.parse(decodeURIComponent(jsonStr));
3800
+ const decoded = Literal.fromUrl(hintLink.target).get();
3801
+ if (typeof decoded === "string" && decoded.length > 0) {
3802
+ interpretationHint = decoded;
3803
+ }
3366
3804
  }
3367
3805
  catch {
3368
- // Ignore parse errors
3806
+ // Ignore parse errors — leave unset.
3807
+ }
3808
+ }
3809
+ // Get per-state `requires` guard (optional) — one link carrying a
3810
+ // JSON-encoded ModelQuery[]. Reject arrays whose entries are not
3811
+ // ModelQuery-shaped (missing/non-string `className`, `null`, primitives).
3812
+ const requiresLink = links.find(l => l.source === stateUri && l.predicate === "ad4m://requires");
3813
+ let requires;
3814
+ if (requiresLink) {
3815
+ try {
3816
+ const jsonStr = requiresLink.target.replace(/^literal:\/\/string:|^literal:string:/, "");
3817
+ const parsed = JSON.parse(decodeURIComponent(jsonStr));
3818
+ if (Array.isArray(parsed) && parsed.every(isModelQueryShape)) {
3819
+ requires = parsed;
3820
+ }
3821
+ }
3822
+ catch {
3823
+ // Ignore parse errors — leave requires unset rather than crash
3824
+ }
3825
+ }
3826
+ // Get per-state `semanticCheck` hint (optional). Non-empty-string guard.
3827
+ const semanticCheckLink = links.find(l => l.source === stateUri && l.predicate === "ad4m://semanticCheck");
3828
+ let semanticCheck;
3829
+ if (semanticCheckLink) {
3830
+ try {
3831
+ const decoded = Literal.fromUrl(semanticCheckLink.target).get();
3832
+ if (typeof decoded === "string" && decoded.length > 0) {
3833
+ semanticCheck = decoded;
3834
+ }
3835
+ }
3836
+ catch {
3837
+ // Ignore parse errors — leave unset.
3369
3838
  }
3370
3839
  }
3371
- flow.addState({ name: stateName, value: stateValue, stateCheck });
3840
+ // Get per-state `consensusRule` override (optional). Same shape
3841
+ // guard as the flow-level rule; a malformed literal (missing `n`,
3842
+ // non-integer, invalid `fromRole`) leaves the field unset.
3843
+ const stateConsensusLink = links.find(l => l.source === stateUri && l.predicate === "ad4m://consensusRule");
3844
+ let consensusRule;
3845
+ if (stateConsensusLink) {
3846
+ try {
3847
+ const jsonStr = stateConsensusLink.target.replace(/^literal:\/\/string:|^literal:string:/, "");
3848
+ const parsed = JSON.parse(decodeURIComponent(jsonStr));
3849
+ if (isConsensusRuleShape(parsed)) {
3850
+ consensusRule = parsed;
3851
+ }
3852
+ }
3853
+ catch {
3854
+ // Ignore parse errors — leave unset.
3855
+ }
3856
+ }
3857
+ flow.addState({
3858
+ name: stateName,
3859
+ value: stateValue,
3860
+ ...(interpretationHint !== undefined ? { interpretationHint } : {}),
3861
+ ...(requires !== undefined ? { requires } : {}),
3862
+ ...(semanticCheck !== undefined ? { semanticCheck } : {}),
3863
+ ...(consensusRule !== undefined ? { consensusRule } : {}),
3864
+ });
3372
3865
  }
3866
+ // Perspective link storage does not preserve insertion order — `hasState`
3867
+ // links come back in arbitrary order from the graph, so `flow.states[0]`
3868
+ // was randomly one of the round-tripped states. Sort by `value` ascending
3869
+ // so the "initial state = states[0]" convention (used by
3870
+ // `FlowInstance.start`) survives a fromGraph round trip.
3871
+ // The `states` getter returns a defensive copy, so mutate `_states` directly.
3872
+ flow._states.sort((a, b) => a.value - b.value);
3373
3873
  // Find transitions
3374
3874
  const transitionLinks = links.filter(l => l.source === flowUri && l.predicate === "ad4m://hasTransition");
3375
3875
  for (const transitionLink of transitionLinks) {
@@ -3405,13 +3905,31 @@ class SHACLFlow {
3405
3905
  * Convert to JSON representation
3406
3906
  */
3407
3907
  toJSON() {
3908
+ // Per-state metadata is optional; strip empty strings / empty arrays so
3909
+ // json.states[i] agrees with what toLinks() would materialise (a state
3910
+ // constructed with `interpretationHint: ""` produces no predicate, so
3911
+ // JSON must not carry the empty field either).
3912
+ const sanitizedStates = this._states.map(s => ({
3913
+ name: s.name,
3914
+ value: s.value,
3915
+ ...(s.interpretationHint ? { interpretationHint: s.interpretationHint } : {}),
3916
+ ...(s.requires && s.requires.length > 0 ? { requires: s.requires } : {}),
3917
+ ...(s.semanticCheck ? { semanticCheck: s.semanticCheck } : {}),
3918
+ ...(s.consensusRule ? { consensusRule: s.consensusRule } : {})
3919
+ }));
3408
3920
  return {
3409
3921
  name: this.name,
3410
3922
  namespace: this.namespace,
3411
- flowable: this.flowable,
3412
- startAction: this.startAction,
3413
- states: this._states,
3414
- transitions: this._transitions
3923
+ states: sanitizedStates,
3924
+ transitions: this._transitions,
3925
+ // Empty strings / empty arrays treated as unset — same semantics
3926
+ // as the toLinks path, so JSON <-> links round-trips agree.
3927
+ ...(this.interpretationHint ? { interpretationHint: this.interpretationHint } : {}),
3928
+ ...(this.inputTypes.length > 0 ? { inputTypes: this.inputTypes } : {}),
3929
+ ...(this.outputTypes.length > 0 ? { outputTypes: this.outputTypes } : {}),
3930
+ ...(this.creationHint ? { creationHint: this.creationHint } : {}),
3931
+ ...(this.context && this.context.length > 0 ? { context: this.context } : {}),
3932
+ ...(this.consensusRule ? { consensusRule: this.consensusRule } : {})
3415
3933
  };
3416
3934
  }
3417
3935
  /**
@@ -3419,10 +3937,49 @@ class SHACLFlow {
3419
3937
  */
3420
3938
  static fromJSON(json) {
3421
3939
  const flow = new SHACLFlow(json.name, json.namespace);
3422
- flow.flowable = json.flowable || "any";
3423
- flow.startAction = json.startAction || [];
3940
+ // Non-empty-string guard — mirrors the toLinks-side reader.
3941
+ if (typeof json.interpretationHint === "string" && json.interpretationHint.length > 0) {
3942
+ flow.interpretationHint = json.interpretationHint;
3943
+ }
3944
+ // Typed I/O (design §4.1). Same string[]/ModelQuery[] shape guards
3945
+ // as the fromLinks path — malformed payloads leave defaults untouched.
3946
+ if (Array.isArray(json.inputTypes) &&
3947
+ json.inputTypes.every((v) => typeof v === "string" && v.length > 0)) {
3948
+ flow.inputTypes = json.inputTypes;
3949
+ }
3950
+ if (Array.isArray(json.outputTypes) &&
3951
+ json.outputTypes.every((v) => typeof v === "string" && v.length > 0)) {
3952
+ flow.outputTypes = json.outputTypes;
3953
+ }
3954
+ if (typeof json.creationHint === "string" && json.creationHint.length > 0) {
3955
+ flow.creationHint = json.creationHint;
3956
+ }
3957
+ if (Array.isArray(json.context) && json.context.every(isModelQueryShape)) {
3958
+ flow.context = json.context;
3959
+ }
3960
+ if (isConsensusRuleShape(json.consensusRule)) {
3961
+ flow.consensusRule = json.consensusRule;
3962
+ }
3424
3963
  for (const state of json.states || []) {
3425
- flow.addState(state);
3964
+ // Same validation as the toLinks path: reject malformed optional fields
3965
+ // rather than let them poison downstream consumers.
3966
+ const sanitized = {
3967
+ name: state.name,
3968
+ value: state.value,
3969
+ };
3970
+ if (typeof state.interpretationHint === "string" && state.interpretationHint.length > 0) {
3971
+ sanitized.interpretationHint = state.interpretationHint;
3972
+ }
3973
+ if (Array.isArray(state.requires) && state.requires.every(isModelQueryShape)) {
3974
+ sanitized.requires = state.requires;
3975
+ }
3976
+ if (typeof state.semanticCheck === "string" && state.semanticCheck.length > 0) {
3977
+ sanitized.semanticCheck = state.semanticCheck;
3978
+ }
3979
+ if (isConsensusRuleShape(state.consensusRule)) {
3980
+ sanitized.consensusRule = state.consensusRule;
3981
+ }
3982
+ flow.addState(sanitized);
3426
3983
  }
3427
3984
  for (const transition of json.transitions || []) {
3428
3985
  flow.addTransition(transition);
@@ -3442,7 +3999,7 @@ var __classPrivateFieldGet$a = (undefined && undefined.__classPrivateFieldGet) |
3442
3999
  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");
3443
4000
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
3444
4001
  };
3445
- 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;
4002
+ 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;
3446
4003
  /** Extract namespace prefix from a URI (everything up to and including the last / or #) */
3447
4004
  function extractNamespaceFromUri(uri) {
3448
4005
  const hashIdx = uri.lastIndexOf('#');
@@ -3503,6 +4060,7 @@ class QuerySubscriptionProxy {
3503
4060
  _QuerySubscriptionProxy_callbacks.set(this, void 0);
3504
4061
  _QuerySubscriptionProxy_keepaliveTimer.set(this, void 0);
3505
4062
  _QuerySubscriptionProxy_unsubscribe.set(this, void 0);
4063
+ _QuerySubscriptionProxy_reconnectUnsub.set(this, void 0);
3506
4064
  _QuerySubscriptionProxy_latestResult.set(this, void 0);
3507
4065
  _QuerySubscriptionProxy_disposed.set(this, false);
3508
4066
  _QuerySubscriptionProxy_initialized.set(this, void 0);
@@ -3510,6 +4068,15 @@ class QuerySubscriptionProxy {
3510
4068
  _QuerySubscriptionProxy_initReject.set(this, void 0);
3511
4069
  _QuerySubscriptionProxy_initTimeoutId.set(this, void 0);
3512
4070
  _QuerySubscriptionProxy_query.set(this, void 0);
4071
+ // Monotonic token guarding the three concurrent writers of
4072
+ // `#unsubscribe`/`#subscriptionId` (full subscribe() from the keepalive
4073
+ // and init-timeout retry paths, and the reconnect swap handler). Each
4074
+ // writer bumps it on entry and re-checks after every await; a mismatch
4075
+ // means a newer writer took over while we were suspended, so the stale
4076
+ // continuation must back out instead of clobbering the newer state
4077
+ // (worst case otherwise: an overwritten-but-never-called unsubscribe
4078
+ // leaks its callback in ApiClient._wsCallbacks for the client lifetime).
4079
+ _QuerySubscriptionProxy_generation.set(this, 0);
3513
4080
  __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_uuid, uuid, "f");
3514
4081
  __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_query, query, "f");
3515
4082
  __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_client, client, "f");
@@ -3522,6 +4089,26 @@ class QuerySubscriptionProxy {
3522
4089
  }), "f");
3523
4090
  }
3524
4091
  async subscribe() {
4092
+ var _a;
4093
+ // Invalidate any suspended writer (older subscribe() or reconnect
4094
+ // swap parked on an await) — see #generation.
4095
+ const generation = __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_generation, (_a = __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_generation, "f"), ++_a), "f");
4096
+ // Remove any prior reconnect listener FIRST — before we touch
4097
+ // `#unsubscribe`. Rationale: `#unsubscribe()` calls into
4098
+ // `ApiClient.subscribe()`'s deleter, which closes the WebSocket
4099
+ // whenever this query owned the last `_wsCallbacks` entry (and no
4100
+ // RPCs are pending). The subsequent `subscribeQuery()` below then
4101
+ // re-opens a fresh socket, and that fresh `onopen` fires the
4102
+ // reconnect callback set. If the OLD reconnect listener is still
4103
+ // in that set, it re-enters this method, closes the socket again,
4104
+ // reopens again … an endless resubscribe loop. Clearing the
4105
+ // listener up-front breaks the cycle; a fresh listener is
4106
+ // installed at the end of a successful subscribe(), and a
4107
+ // full-retry recovery listener in the catch block on failure.
4108
+ if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_reconnectUnsub, "f")) {
4109
+ __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_reconnectUnsub, "f").call(this);
4110
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_reconnectUnsub, undefined, "f");
4111
+ }
3525
4112
  // Clean up previous subscription attempt if retrying
3526
4113
  if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_unsubscribe, "f")) {
3527
4114
  __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_unsubscribe, "f").call(this);
@@ -3541,19 +4128,22 @@ class QuerySubscriptionProxy {
3541
4128
  // Initialize the query subscription
3542
4129
  let initialResult;
3543
4130
  initialResult = await __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, "f").subscribeQuery(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_query, "f"));
4131
+ // A newer writer (another subscribe() or a reconnect swap) took
4132
+ // over while we awaited — back out without touching shared state,
4133
+ // and release the now-orphaned server-side subscription so it
4134
+ // doesn't linger until its keepalive TTL expires.
4135
+ if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_disposed, "f") || __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_generation, "f") !== generation) {
4136
+ __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, "f").disposeQuerySubscription(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_uuid, "f"), initialResult.subscriptionId)
4137
+ .catch(e => console.error('Error disposing superseded query subscription:', e));
4138
+ return;
4139
+ }
3544
4140
  __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_subscriptionId, initialResult.subscriptionId, "f");
3545
4141
  // Process the initial result immediately for fast UX.
3546
4142
  // The subscribeQuery() RPC call already returns the initial result,
3547
4143
  // so treat that as successful initialization instead of waiting for a
3548
4144
  // follow-up WebSocket update that may never arrive until the query changes.
3549
4145
  if (initialResult.result !== undefined) {
3550
- __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_latestResult, initialResult.result, "f");
3551
- __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_instances, "m", _QuerySubscriptionProxy_notifyCallbacks).call(this, initialResult.result);
3552
- if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initResolve, "f")) {
3553
- __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initResolve, "f").call(this, true);
3554
- __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initResolve, undefined, "f");
3555
- __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initReject, undefined, "f");
3556
- }
4146
+ __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_instances, "m", _QuerySubscriptionProxy_deliverResult).call(this, initialResult.result);
3557
4147
  }
3558
4148
  else {
3559
4149
  console.warn('⚠️ No initial result returned from subscribeQuery!');
@@ -3568,21 +4158,7 @@ class QuerySubscriptionProxy {
3568
4158
  }, 30000), "f");
3569
4159
  }
3570
4160
  // Subscribe to query updates
3571
- __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_unsubscribe, __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, "f").subscribeToQueryUpdates(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_subscriptionId, "f"), (updateResult) => {
3572
- // Clear timeout on first message
3573
- if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initTimeoutId, "f")) {
3574
- clearTimeout(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initTimeoutId, "f"));
3575
- __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initTimeoutId, undefined, "f");
3576
- }
3577
- // Resolve the initialization promise (only resolves once)
3578
- if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initResolve, "f")) {
3579
- __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initResolve, "f").call(this, true);
3580
- __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initResolve, undefined, "f"); // Prevent double-resolve
3581
- __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initReject, undefined, "f");
3582
- }
3583
- __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_latestResult, updateResult, "f");
3584
- __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_instances, "m", _QuerySubscriptionProxy_notifyCallbacks).call(this, updateResult);
3585
- }), "f");
4161
+ __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");
3586
4162
  }
3587
4163
  catch (error) {
3588
4164
  console.error('Error setting up subscription:', error);
@@ -3592,36 +4168,117 @@ class QuerySubscriptionProxy {
3592
4168
  __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initResolve, undefined, "f");
3593
4169
  __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initReject, undefined, "f");
3594
4170
  }
4171
+ // Restore reconnect recovery before rethrowing. The listener was
4172
+ // removed at the top of this method; without re-installing one
4173
+ // here, a single failed resubscribe (e.g. subscribeQuery timing
4174
+ // out during a network flap) would leave the proxy permanently
4175
+ // dead: the keepalive loop stops itself on resubscribe failure,
4176
+ // and nothing else retries. The recovery listener runs the FULL
4177
+ // subscribe() (not the swap-in-place handler) because after a
4178
+ // failed attempt there is no keepalive loop left to feed the new
4179
+ // server subscription — subscribe() restarts it. This is
4180
+ // loop-safe: in this failed state the proxy owns no
4181
+ // `_wsCallbacks` entry (the old one was unsubscribed at the top
4182
+ // of this method and no new one got registered), so the
4183
+ // subscribe() it triggers has nothing to unsubscribe → the
4184
+ // socket never closes/reopens under it → no re-entrant onopen.
4185
+ if (!__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_disposed, "f") && __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_generation, "f") === generation && __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, "f").onReconnect) {
4186
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_reconnectUnsub, __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, "f").onReconnect(() => {
4187
+ if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_disposed, "f"))
4188
+ return;
4189
+ console.log('WebSocket reconnected — retrying failed subscription for query:', __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_query, "f"));
4190
+ this.subscribe().catch(e => {
4191
+ console.error('Error during subscription retry after reconnect:', e);
4192
+ });
4193
+ }), "f");
4194
+ }
3595
4195
  throw error; // Re-throw so caller knows it failed
3596
4196
  }
3597
- // Start keepalive loop using platform-agnostic setTimeout
3598
- const keepaliveLoop = async () => {
3599
- if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_disposed, "f"))
3600
- return;
3601
- try {
3602
- await __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, "f").keepAliveQuery(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_subscriptionId, "f"));
3603
- }
3604
- catch (e) {
3605
- console.error('Error in keepalive:', e);
3606
- // try to reinitialize the subscription
3607
- console.log('Reinitializing subscription for query:', __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_query, "f"));
4197
+ // Start keepalive loop
4198
+ __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_instances, "m", _QuerySubscriptionProxy_startKeepalive).call(this, generation);
4199
+ // Register for reconnect notification — on WebSocket reconnect,
4200
+ // immediately re-establish a fresh server-side subscription instead
4201
+ // of waiting up to 30s for the keepalive to fail.
4202
+ //
4203
+ // We deliberately do NOT call `this.subscribe()` here. Full subscribe
4204
+ // runs `#unsubscribe` first, which delegates to `ApiClient.subscribe`'s
4205
+ // deleter — that closes the WebSocket when this query owned the LAST
4206
+ // `_wsCallbacks` entry. The subsequent `subscribeQuery` reopens the
4207
+ // socket, whose fresh `onopen` fires every registered reconnect
4208
+ // callback again → recursion (CodeRabbit's original finding). And
4209
+ // during that close→reopen gap, RPCs in flight from OTHER proxies
4210
+ // fail with `503 WebSocket not connected` (observed in
4211
+ // integration-tests-mcp `should fire onWake when mention uses agent DID`
4212
+ // after PR #899's initial fix — the WakerSubscriptionManager tests
4213
+ // share a wakerClient across cases, so any dying reconnect handler
4214
+ // interferes with sibling subscriptions).
4215
+ //
4216
+ // The correct shape is a swap-in-place: get a new server-side
4217
+ // subscription ID via `subscribeQuery`, register a new client-side
4218
+ // callback FIRST, and only then unsubscribe the old one. That way
4219
+ // `_wsCallbacks.size` never dips to 0 during the transition, so the
4220
+ // socket doesn't close, no reconnect loop, and no cross-proxy 503s.
4221
+ // Any prior listener was already removed at the top of this method
4222
+ // (see the note there for why cleanup must run before `#unsubscribe`,
4223
+ // not here).
4224
+ if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, "f").onReconnect) {
4225
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_reconnectUnsub, __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, "f").onReconnect(async () => {
4226
+ var _a;
4227
+ if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_disposed, "f"))
4228
+ return;
4229
+ // The handler is a writer of `#unsubscribe`/`#subscriptionId`
4230
+ // too, so it takes its own generation — see #generation.
4231
+ const swapGeneration = __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_generation, (_a = __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_generation, "f"), ++_a), "f");
4232
+ console.log('WebSocket reconnected — re-establishing server subscription for query:', __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_query, "f"));
3608
4233
  try {
3609
- await this.subscribe();
3610
- console.log('Subscription reinitialized');
4234
+ const newInitial = await __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, "f").subscribeQuery(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_query, "f"));
4235
+ if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_disposed, "f") || __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_generation, "f") !== swapGeneration) {
4236
+ // A newer writer took over while we awaited — back out
4237
+ // and release the orphaned server-side subscription.
4238
+ __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, "f").disposeQuerySubscription(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_uuid, "f"), newInitial.subscriptionId)
4239
+ .catch(e => console.error('Error disposing superseded query subscription:', e));
4240
+ return;
4241
+ }
4242
+ const newSubId = newInitial.subscriptionId;
4243
+ // Register the NEW client-side callback BEFORE removing the
4244
+ // old one — keeps `_wsCallbacks.size >= 1` across the swap.
4245
+ const newUnsub = __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, "f").subscribeToQueryUpdates(newSubId, (updateResult) => __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_instances, "m", _QuerySubscriptionProxy_deliverResult).call(this, updateResult));
4246
+ const oldUnsub = __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_unsubscribe, "f");
4247
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_unsubscribe, newUnsub, "f");
4248
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_subscriptionId, newSubId, "f");
4249
+ if (oldUnsub)
4250
+ oldUnsub();
4251
+ // Our generation bump invalidated the running keepalive
4252
+ // loop — restart it under our generation so the new
4253
+ // server subscription keeps receiving keepalives.
4254
+ clearTimeout(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_keepaliveTimer, "f"));
4255
+ __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_instances, "m", _QuerySubscriptionProxy_startKeepalive).call(this, swapGeneration);
4256
+ // Deliver the fresh initial result if the server included one
4257
+ // (matches the eager-delivery path in the main subscribe() body).
4258
+ // #deliverResult also clears a still-pending init timeout and
4259
+ // resolves #initialized, keeping this path symmetric with the
4260
+ // update callback in subscribe() — without it, a swap landing
4261
+ // while initialization was pending would leave the 30s init
4262
+ // timer armed and trigger a spurious full resubscribe.
4263
+ if (newInitial.result !== undefined) {
4264
+ __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_instances, "m", _QuerySubscriptionProxy_deliverResult).call(this, newInitial.result);
4265
+ }
3611
4266
  }
3612
- catch (resubscribeError) {
3613
- console.error('Error during resubscription from keepalive:', resubscribeError);
3614
- // Don't schedule another keepalive on resubscribe failure
3615
- return;
4267
+ catch (error) {
4268
+ console.error('Error re-establishing subscription after reconnect:', error);
4269
+ // Our generation bump invalidated the running keepalive
4270
+ // loop; if nothing newer superseded us, restart it so
4271
+ // liveness is preserved — its keepAliveQuery against the
4272
+ // dead old subscription will fail and fall back to a
4273
+ // full subscribe(). The reconnect listener also remains
4274
+ // installed, so a later reconnect retries this handler.
4275
+ if (!__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_disposed, "f") && __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_generation, "f") === swapGeneration) {
4276
+ clearTimeout(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_keepaliveTimer, "f"));
4277
+ __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_instances, "m", _QuerySubscriptionProxy_startKeepalive).call(this, swapGeneration);
4278
+ }
3616
4279
  }
3617
- }
3618
- // Schedule next keepalive if not disposed
3619
- if (!__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_disposed, "f")) {
3620
- __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_keepaliveTimer, setTimeout(keepaliveLoop, 30000), "f");
3621
- }
3622
- };
3623
- // Start the first keepalive loop
3624
- __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_keepaliveTimer, setTimeout(keepaliveLoop, 30000), "f");
4280
+ }), "f");
4281
+ }
3625
4282
  }
3626
4283
  /** Get the subscription ID for this query subscription
3627
4284
  *
@@ -3694,11 +4351,19 @@ class QuerySubscriptionProxy {
3694
4351
  * will not receive any more updates. The instance should be discarded.
3695
4352
  */
3696
4353
  dispose() {
4354
+ var _a;
3697
4355
  __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_disposed, true, "f");
4356
+ // Invalidate any suspended writer so a mid-flight subscribe() or
4357
+ // reconnect swap backs out instead of resurrecting state.
4358
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_generation, (_a = __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_generation, "f"), _a++, _a), "f");
3698
4359
  clearTimeout(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_keepaliveTimer, "f"));
3699
4360
  if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_unsubscribe, "f")) {
3700
4361
  __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_unsubscribe, "f").call(this);
3701
4362
  }
4363
+ if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_reconnectUnsub, "f")) {
4364
+ __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_reconnectUnsub, "f").call(this);
4365
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_reconnectUnsub, undefined, "f");
4366
+ }
3702
4367
  __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_callbacks, "f").clear();
3703
4368
  if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initTimeoutId, "f")) {
3704
4369
  clearTimeout(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initTimeoutId, "f"));
@@ -3711,7 +4376,58 @@ class QuerySubscriptionProxy {
3711
4376
  }
3712
4377
  }
3713
4378
  }
3714
- _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) {
4379
+ _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) {
4380
+ if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initTimeoutId, "f")) {
4381
+ clearTimeout(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initTimeoutId, "f"));
4382
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initTimeoutId, undefined, "f");
4383
+ }
4384
+ // Resolve the initialization promise (only resolves once)
4385
+ if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initResolve, "f")) {
4386
+ __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initResolve, "f").call(this, true);
4387
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initResolve, undefined, "f"); // Prevent double-resolve
4388
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initReject, undefined, "f");
4389
+ }
4390
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_latestResult, result, "f");
4391
+ __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_instances, "m", _QuerySubscriptionProxy_notifyCallbacks).call(this, result);
4392
+ }, _QuerySubscriptionProxy_startKeepalive = function _QuerySubscriptionProxy_startKeepalive(generation) {
4393
+ const keepaliveLoop = async () => {
4394
+ // Generation check kills orphaned loops: a loop whose
4395
+ // keepAliveQuery was in flight while a newer writer ran is not
4396
+ // cancelled by clearTimeout and would otherwise reschedule
4397
+ // itself alongside the newer loop.
4398
+ if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_disposed, "f") || __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_generation, "f") !== generation)
4399
+ return;
4400
+ try {
4401
+ await __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, "f").keepAliveQuery(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_subscriptionId, "f"));
4402
+ }
4403
+ catch (e) {
4404
+ if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_disposed, "f") || __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_generation, "f") !== generation)
4405
+ return;
4406
+ console.error('Error in keepalive:', e);
4407
+ // try to reinitialize the subscription
4408
+ console.log('Reinitializing subscription for query:', __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_query, "f"));
4409
+ try {
4410
+ await this.subscribe();
4411
+ console.log('Subscription reinitialized');
4412
+ }
4413
+ catch (resubscribeError) {
4414
+ console.error('Error during resubscription from keepalive:', resubscribeError);
4415
+ // Don't schedule another keepalive on resubscribe failure.
4416
+ // Recovery is not lost: the failed subscribe() installed a
4417
+ // reconnect listener that retries the full subscribe.
4418
+ return;
4419
+ }
4420
+ // subscribe() succeeded and started its own keepalive loop
4421
+ // under a new generation — this loop is done.
4422
+ return;
4423
+ }
4424
+ // Schedule next keepalive if still the active generation
4425
+ if (!__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_disposed, "f") && __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_generation, "f") === generation) {
4426
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_keepaliveTimer, setTimeout(keepaliveLoop, 30000), "f");
4427
+ }
4428
+ };
4429
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_keepaliveTimer, setTimeout(keepaliveLoop, 30000), "f");
4430
+ }, _QuerySubscriptionProxy_notifyCallbacks = function _QuerySubscriptionProxy_notifyCallbacks(result) {
3715
4431
  for (const callback of __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_callbacks, "f")) {
3716
4432
  try {
3717
4433
  callback(result);
@@ -3910,8 +4626,8 @@ class PerspectiveProxy {
3910
4626
  * });
3911
4627
  * ```
3912
4628
  */
3913
- async get(query) {
3914
- return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").queryLinks(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, query);
4629
+ async get(query, options) {
4630
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").queryLinks(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, query, options);
3915
4631
  }
3916
4632
  /**
3917
4633
  * Runs generic LLM interpretation over a conversation transcript, turning it
@@ -3926,8 +4642,38 @@ class PerspectiveProxy {
3926
4642
  * @param basePrefix URI namespace for new instance identities, e.g. `soa://ext/`
3927
4643
  * @param classes local names of the subject classes to extract into; omit for all
3928
4644
  */
3929
- async runInterpretation(transcript, basePrefix, classes) {
3930
- return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").runInterpretation(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, transcript, basePrefix, classes);
4645
+ async runInterpretation(transcript, basePrefix, classes, options) {
4646
+ // Grouped into an options bag rather than continuing the client's positional list.
4647
+ // The scopes were already unreachable from here for that reason, and a fourth, fifth and
4648
+ // sixth positional parameter would have made `undefined, undefined, { … }` the normal way
4649
+ // to ask for the only one of them most callers want.
4650
+ 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);
4651
+ }
4652
+ /**
4653
+ * Harness-dispatched interpretation pass over this perspective (design v3
4654
+ * §6 — the tool-calling counterpart to {@link runInterpretation}). The LLM
4655
+ * sees a live per-class tool surface (`{Class}_query`, `{Class}_get`,
4656
+ * `{Class}_propose_create`, `{Class}_propose_link_child`, …) and drives
4657
+ * the extraction via tool calls; buffered proposals drain through the
4658
+ * same overlay gate the single-shot path uses.
4659
+ *
4660
+ * @param transcript ordered `{ speaker, text }` turns
4661
+ * @param basePrefix URI namespace new instance identities are minted under
4662
+ * @param maxToolCalls upper bound on tool calls the harness will make in
4663
+ * one pass (must be > 0 — use {@link runInterpretation} for the
4664
+ * classic single-shot path)
4665
+ * @param classes local names of the subject classes to extract into; omit for all
4666
+ * @param modelOverride optional model override; omit for the default LLM
4667
+ */
4668
+ async runInterpretationWithHarness(transcript, basePrefix, maxToolCalls, classes, modelOverride,
4669
+ // Optional live-debug observability. When both `observationId` and
4670
+ // `emitDebugEvents` are supplied, every dispatched tool call fires
4671
+ // `ToolCall` + `ToolResult` events on the `auto-processor-event`
4672
+ // topic keyed by `observationId`. Subscribe with
4673
+ // {@link addAutoProcessorEventListener} to render the harness loop
4674
+ // live in a UI. Absent = fast headless path (no telemetry cost).
4675
+ observationId, emitDebugEvents) {
4676
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").runInterpretationWithHarness(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, transcript, basePrefix, maxToolCalls, classes, modelOverride, undefined, observationId, emitDebugEvents);
3931
4677
  }
3932
4678
  /**
3933
4679
  * Register a neighbourhood auto-processor on this perspective. The executor
@@ -3938,6 +4684,24 @@ class PerspectiveProxy {
3938
4684
  async addAutoProcessor(config) {
3939
4685
  return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").addAutoProcessor(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, config);
3940
4686
  }
4687
+ /**
4688
+ * Stop an auto-processor by deleting its config.
4689
+ *
4690
+ * The registration is data — the watch loop reads the processor set back out of the
4691
+ * perspective's graph on every tick — so deleting the config is what stops it, and there is
4692
+ * nothing else to unregister. The config is `Shared`, so this stops the processor for the
4693
+ * neighbourhood rather than only for this peer.
4694
+ *
4695
+ * Resolves `true` when there was a processor to remove and `false` when there was not; a
4696
+ * processor another peer has already removed is not an error.
4697
+ *
4698
+ * The processor's `InterpretationRun` nodes stay: they are the record of what it did and the
4699
+ * processed-turn cursor, so a processor later registered under the same id resumes where this
4700
+ * one left off rather than re-reading every turn.
4701
+ */
4702
+ async removeAutoProcessor(processorId) {
4703
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").removeAutoProcessor(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, processorId);
4704
+ }
3941
4705
  /**
3942
4706
  * Pending interpretation overlays on this perspective — LLM suggestions the
3943
4707
  * §4 divergence gate staged rather than applied, awaiting human accept/reject.
@@ -3961,6 +4725,13 @@ class PerspectiveProxy {
3961
4725
  async rejectInterpretation(base, property) {
3962
4726
  return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").rejectInterpretation(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, base, property);
3963
4727
  }
4728
+ async acceptFlowProposal(proposalUri) {
4729
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").acceptFlowProposal(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, proposalUri);
4730
+ }
4731
+ /** Withdraw our own links from a proposal; resolves to how many went. */
4732
+ async rejectFlowProposal(proposalUri) {
4733
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").rejectFlowProposal(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, proposalUri);
4734
+ }
3964
4735
  /** Subscribe to this perspective's auto-processor step signals. */
3965
4736
  async addAutoProcessorEventListener(cb) {
3966
4737
  return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").addAutoProcessorEventListener(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, cb);
@@ -3998,8 +4769,8 @@ class PerspectiveProxy {
3998
4769
  * `);
3999
4770
  * ```
4000
4771
  */
4001
- async infer(query) {
4002
- return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").queryProlog(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, query);
4772
+ async infer(query, options) {
4773
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").queryProlog(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, query, options);
4003
4774
  }
4004
4775
  /**
4005
4776
  * Executes a SPARQL query against the perspective's link cache.
@@ -4009,19 +4780,25 @@ class PerspectiveProxy {
4009
4780
  * Mutating operations (DELETE, UPDATE, INSERT, CREATE, DROP, DEFINE, etc.) are
4010
4781
  * blocked for security reasons. Use the perspective's add/remove methods to modify links.
4011
4782
  *
4012
- * @param query - SPARQL query string (read-only operations only)
4013
- * @returns Query results as parsed JSON
4783
+ * **Cancellation:** Pass `{ signal }` from an `AbortController` to abort
4784
+ * an in-flight query. The executor receives `request.cancel` over the
4785
+ * WebSocket and short-circuits the JSON reply. Caveat: Oxigraph itself
4786
+ * cannot be interrupted mid-evaluation, so an already-running scan will
4787
+ * keep its blocking thread busy until it completes; what's saved is the
4788
+ * serialise + network + client-deserialise tax on the result. Aborted
4789
+ * calls reject with `DOMException('Aborted', 'AbortError')` — match
4790
+ * `fetch()` for handling. Cached results bypass the round-trip entirely
4791
+ * and are returned synchronously, ignoring the signal.
4014
4792
  *
4015
- * Executes a SPARQL query against the perspective's RDF (Oxigraph) store.
4016
- *
4017
- * @param query - SPARQL query string
4793
+ * @param query - SPARQL query string (read-only operations only)
4794
+ * @param options - Optional call options (e.g. AbortSignal for cancellation)
4018
4795
  * @returns Query results as parsed JSON
4019
4796
  */
4020
- async querySparql(query) {
4797
+ async querySparql(query, options) {
4021
4798
  const cached = getCachedResult(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, query);
4022
4799
  if (cached !== undefined)
4023
4800
  return cached;
4024
- const result = await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").querySparql(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, query);
4801
+ const result = await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").querySparql(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, query, options);
4025
4802
  setCachedResult(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, query, result);
4026
4803
  return result;
4027
4804
  }
@@ -4036,8 +4813,43 @@ class PerspectiveProxy {
4036
4813
  * @param queryJson - Structured query as JSON string
4037
4814
  * @returns Object with `instances` array and `totalCount`
4038
4815
  */
4039
- async modelQuery(className, queryJson) {
4040
- return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").modelQuery(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, className, queryJson);
4816
+ async modelQuery(className, queryJson, options) {
4817
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").modelQuery(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, className, queryJson, options);
4818
+ }
4819
+ /** Resolve each URI to the names of every subject class it is an instance of.
4820
+ *
4821
+ * The counterpart of {@link isSubjectInstance}, which asks the same question
4822
+ * one class at a time. Without this, finding the class of an arbitrary URI
4823
+ * meant looping over every registered class — a round trip each — and doing
4824
+ * it again for every URI.
4825
+ *
4826
+ * Class membership in AD4M is structural — a URI belongs to a class when it
4827
+ * carries that class's flags and required properties — so membership is **not
4828
+ * exclusive**: an instance conforms to its parent classes, and to any
4829
+ * unrelated class whose required set happens to be a subset of what it
4830
+ * carries. Every match is returned.
4831
+ *
4832
+ * The list is ordered **most specific first**, meaning by the number of
4833
+ * triples the class requires — a subclass requires everything its parent does
4834
+ * and more — with ties broken alphabetically so that every peer answers
4835
+ * identically. A caller that can only act on one class should take
4836
+ * `classes[0]`, but that head is only a heuristic: it is arbitrary between two
4837
+ * unrelated classes requiring the same number of triples, which is exactly
4838
+ * the case the full list exists to expose.
4839
+ *
4840
+ * A URI is **absent from the result** when no *registered* class matched it.
4841
+ * That covers two situations, and nothing here separates them: the URI may
4842
+ * not be a subject instance at all, or it may be an instance of a class this
4843
+ * perspective has not registered. Absence is used rather than an empty list
4844
+ * because an empty list would claim the stronger thing — that the URI belongs
4845
+ * to no class — which this cannot know.
4846
+ *
4847
+ * @param uris The expression URIs to classify.
4848
+ */
4849
+ async subjectClassesOf(uris) {
4850
+ if (uris.length === 0)
4851
+ return {};
4852
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").subjectClassesOf(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, uris);
4041
4853
  }
4042
4854
  /**
4043
4855
  * Evaluate property getters for a batch of instances in a single RPC call.
@@ -4164,11 +4976,48 @@ class PerspectiveProxy {
4164
4976
  /**
4165
4977
  * Removes a link from the perspective.
4166
4978
  *
4167
- * @param link - The link to remove
4979
+ * Accepts either a full `LinkExpressionInput` (as returned by `add`) or a bare
4980
+ * `Link` (source/predicate/target only). When a bare Link is passed the method
4981
+ * resolves it to the first stored `LinkExpression` whose source, predicate, and
4982
+ * target match, then removes that expression. A bare Link without a predicate
4983
+ * (or with the constructor's `""` stand-in) matches only stored links that
4984
+ * themselves have no predicate. If no match is found an error is thrown
4985
+ * naming the link so the caller knows what was expected.
4986
+ *
4987
+ * @param link - The link to remove (LinkExpressionInput or bare Link)
4168
4988
  * @param batchId - Optional batch ID to group this operation with others
4169
4989
  */
4170
4990
  async remove(link, batchId) {
4171
- const result = await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").removeLink(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, link, batchId);
4991
+ let resolvedLink;
4992
+ if (!('data' in link) || link.data === undefined) {
4993
+ // bare Link — resolve to stored expression
4994
+ const bare = link;
4995
+ // The Link constructor coerces an absent predicate to "" and the
4996
+ // store reports predicate-less links as predicate null — so ""
4997
+ // and undefined both mean "no predicate" here, and neither may
4998
+ // widen the query: dropping the filter would resolve (and
4999
+ // remove!) an arbitrary source→target link under a *different*
5000
+ // predicate. LinkQuery cannot express "predicate is absent", so
5001
+ // in that case we query on source/target only and require the
5002
+ // absence ourselves.
5003
+ const predicateGiven = bare.predicate !== undefined && bare.predicate !== '';
5004
+ const candidates = await this.get(new LinkQuery({
5005
+ source: bare.source || undefined,
5006
+ predicate: predicateGiven ? bare.predicate : undefined,
5007
+ target: bare.target || undefined,
5008
+ }));
5009
+ const matches = predicateGiven
5010
+ ? candidates
5011
+ : candidates.filter(m => !m.data.predicate);
5012
+ if (matches.length === 0) {
5013
+ throw new Error(`PerspectiveProxy.remove: no stored LinkExpression matches Link { source: "${bare.source}", predicate: "${bare.predicate}", target: "${bare.target}" }`);
5014
+ }
5015
+ resolvedLink = matches[0];
5016
+ }
5017
+ else {
5018
+ resolvedLink = link;
5019
+ }
5020
+ const result = await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").removeLink(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, resolvedLink, batchId);
4172
5021
  invalidatePerspectiveCache(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid);
4173
5022
  return result;
4174
5023
  }
@@ -4373,116 +5222,48 @@ class PerspectiveProxy {
4373
5222
  }
4374
5223
  });
4375
5224
  }
4376
- /** Returns all Social DNA flows that can be started from the given expression */
5225
+ /**
5226
+ * Returns all Social DNA flows that can be started from the given expression.
5227
+ *
5228
+ * Post-`flowable` retirement: a flow is a candidate iff its `inputTypes`
5229
+ * declaration is compatible with the expression. Matching rules:
5230
+ * - Empty `inputTypes` or one containing the `"any"` wildcard → always
5231
+ * matches (same behaviour as the legacy `flowable === "any"` case).
5232
+ * - Otherwise, at least one of the expression's registered subject-class
5233
+ * URIs (resolved via {@link subjectClassesOf}) must appear in
5234
+ * `inputTypes`. This is the concrete-type match the design doc's §5
5235
+ * spawn engine calls for; without it, a flow declaring
5236
+ * `inputTypes: ["Task"]` was previously *never* returned by
5237
+ * `availableFlows("some-task-uri")` — the entire point of typed
5238
+ * flows was silently unreachable (James PR #929 J#3).
5239
+ *
5240
+ * The expression is classified against the perspective's registered
5241
+ * classes only. An expression whose class is not registered on this
5242
+ * perspective matches no typed flow (absence, not falsehood — same
5243
+ * discipline as {@link subjectClassesOf}); typed flows requiring
5244
+ * unknown classes are still returned to their untyped-caller peers.
5245
+ */
4377
5246
  async availableFlows(exprAddr) {
4378
5247
  const allFlowNames = await this.sdnaFlows();
5248
+ if (allFlowNames.length === 0)
5249
+ return [];
5250
+ const classesOf = await this.subjectClassesOf([exprAddr]);
5251
+ const exprClasses = classesOf[exprAddr] ?? [];
4379
5252
  const available = [];
4380
5253
  for (const name of allFlowNames) {
4381
5254
  const flow = await this.getFlow(name);
4382
5255
  if (!flow)
4383
5256
  continue;
4384
- if (flow.flowable === "any") {
5257
+ if (flow.inputTypes.length === 0 || flow.inputTypes.includes("any")) {
4385
5258
  available.push(name);
5259
+ continue;
4386
5260
  }
4387
- else {
4388
- // Check if the expression matches the flowable link pattern
4389
- const pattern = flow.flowable;
4390
- const source = pattern.source || exprAddr;
4391
- const links = await this.get(new LinkQuery({
4392
- source,
4393
- predicate: pattern.predicate,
4394
- target: pattern.target
4395
- }));
4396
- if (links.length > 0) {
4397
- available.push(name);
4398
- }
5261
+ if (exprClasses.some(cls => flow.inputTypes.includes(cls))) {
5262
+ available.push(name);
4399
5263
  }
4400
5264
  }
4401
5265
  return available;
4402
5266
  }
4403
- /** Starts the Social DNA flow @param flowName on the expression @param exprAddr */
4404
- async startFlow(flowName, exprAddr) {
4405
- const flow = await this.getFlow(flowName);
4406
- if (!flow)
4407
- throw `Flow "${flowName}" not found`;
4408
- if (flow.startAction.length === 0)
4409
- throw `Flow "${flowName}" has no start action`;
4410
- await this.executeAction(flow.startAction, exprAddr, undefined);
4411
- }
4412
- /** Returns all expressions in the given state of given Social DNA flow */
4413
- async expressionsInFlowState(flowName, flowState) {
4414
- const flow = await this.getFlow(flowName);
4415
- if (!flow)
4416
- return [];
4417
- // Find the state with the matching value
4418
- const state = flow.states.find(s => s.value === flowState);
4419
- if (!state)
4420
- return [];
4421
- // Query for expressions matching this state's check pattern
4422
- const pattern = state.stateCheck;
4423
- const links = await this.get(new LinkQuery({
4424
- predicate: pattern.predicate,
4425
- target: pattern.target
4426
- }));
4427
- // Return the sources (expression addresses) - use source if pattern has no explicit source
4428
- return links.map(l => pattern.source ? l.data.target : l.data.source);
4429
- }
4430
- /** Returns the given expression's flow state with regard to given Social DNA flow */
4431
- async flowState(flowName, exprAddr) {
4432
- const flow = await this.getFlow(flowName);
4433
- if (!flow)
4434
- throw `Flow "${flowName}" not found`;
4435
- // Check each state to find which one the expression is in
4436
- for (const state of flow.states) {
4437
- const pattern = state.stateCheck;
4438
- const source = pattern.source || exprAddr;
4439
- const links = await this.get(new LinkQuery({
4440
- source,
4441
- predicate: pattern.predicate,
4442
- target: pattern.target
4443
- }));
4444
- if (links.length > 0)
4445
- return state.value;
4446
- }
4447
- throw `Expression "${exprAddr}" is not in any state of flow "${flowName}"`;
4448
- }
4449
- /** Returns available action names, with regard to Social DNA flow and expression's flow state */
4450
- async flowActions(flowName, exprAddr) {
4451
- const flow = await this.getFlow(flowName);
4452
- if (!flow)
4453
- return [];
4454
- // Determine current state
4455
- let currentStateName = null;
4456
- for (const state of flow.states) {
4457
- const pattern = state.stateCheck;
4458
- const source = pattern.source || exprAddr;
4459
- const links = await this.get(new LinkQuery({
4460
- source,
4461
- predicate: pattern.predicate,
4462
- target: pattern.target
4463
- }));
4464
- if (links.length > 0) {
4465
- currentStateName = state.name;
4466
- break;
4467
- }
4468
- }
4469
- if (!currentStateName)
4470
- return [];
4471
- // Return transitions available from current state
4472
- return flow.transitions
4473
- .filter(t => t.fromState === currentStateName)
4474
- .map(t => t.actionName);
4475
- }
4476
- /** Runs given Social DNA flow action */
4477
- async runFlowAction(flowName, exprAddr, actionName) {
4478
- const flow = await this.getFlow(flowName);
4479
- if (!flow)
4480
- throw `Flow "${flowName}" not found`;
4481
- const transition = flow.transitions.find(t => t.actionName === actionName);
4482
- if (!transition)
4483
- throw `Action "${actionName}" not found in flow "${flowName}"`;
4484
- await this.executeAction(transition.actions, exprAddr, undefined);
4485
- }
4486
5267
  /** Returns the perspective's Social DNA code
4487
5268
  * This will return all SDNA code elements in an array.
4488
5269
  */
@@ -4662,111 +5443,45 @@ class PerspectiveProxy {
4662
5443
  await this.addLinks(allLinks);
4663
5444
  }
4664
5445
  /**
4665
- * Retrieve a SHACL shape by name from this Perspective
5446
+ * Retrieve a SHACL shape by name from this Perspective (one RPC call).
5447
+ * The executor resolves the full shape (including property sub-shapes)
5448
+ * in-process and returns link triples for client-side reconstruction.
4666
5449
  */
4667
5450
  async getShacl(name) {
4668
- // Find the shape URI from the name mapping
4669
- const nameMapping = Literal.fromUrl(`literal:string:shacl://${name}`);
4670
- const shapeUriLinks = await this.get(new LinkQuery({
4671
- source: nameMapping.toUrl(),
4672
- predicate: "ad4m://shacl_shape_uri"
4673
- }));
4674
- if (shapeUriLinks.length === 0) {
5451
+ const result = await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").getShacl(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, name);
5452
+ if (!result)
4675
5453
  return null;
4676
- }
4677
- const shapeUri = shapeUriLinks[0].data.target;
4678
- // First get property shape URIs so we can query everything in one go
4679
- const propertyLinks = await this.get(new LinkQuery({
4680
- source: shapeUri,
4681
- predicate: "sh://property"
4682
- }));
4683
- // Fetch all links from the shape and its property shapes. These reads are
4684
- // independent of each other, so fire them concurrently rather than one RPC
4685
- // round trip at a time — over a remote (non-loopback) connection, a shape with
4686
- // a dozen properties otherwise pays a dozen sequential round trips just to load.
4687
- const sourceUris = [shapeUri, ...propertyLinks.map(l => l.data.target)];
4688
- const linksByUri = await Promise.all(sourceUris.map(uri => this.get(new LinkQuery({ source: uri }))));
4689
- // Dedupe by (source, predicate, target): a perspective that's accumulated duplicate
4690
- // SDNA links (e.g. from repeated registration attempts, or executor-side sync bugs)
4691
- // would otherwise feed the same triple into SHACLShape.fromLinks more than once —
4692
- // harmless for scalar fields like targetClass (first match wins) but can surface as
4693
- // visibly duplicated properties for repeated sh://property links. Cheap: this is an
4694
- // in-memory pass over data already fetched, no extra round trips.
4695
- const seenLinks = new Set();
4696
- const allLinks = [];
4697
- for (const links of linksByUri) {
4698
- for (const l of links) {
4699
- const key = `${l.data.source} ${l.data.predicate} ${l.data.target}`;
4700
- if (seenLinks.has(key))
4701
- continue;
4702
- seenLinks.add(key);
4703
- allLinks.push({
4704
- source: l.data.source,
4705
- predicate: l.data.predicate,
4706
- target: l.data.target
4707
- });
4708
- }
4709
- }
4710
- const shapeLinks = allLinks;
4711
- return SHACLShape.fromLinks(shapeLinks, shapeUri);
5454
+ return SHACLShape.fromLinks(result.links, result.shapeUri);
4712
5455
  }
4713
5456
  /**
4714
- * List the names of every SHACL shape stored in this Perspective, without fetching
4715
- * each shape's full definition (properties, target class, etc.) — just the cheap
4716
- * `ad4m://has_shacl` enumeration, one round trip regardless of how many shapes exist.
4717
- * Use this to check which shapes are actually worth resolving via `getShacl()` before
4718
- * paying for each one's full (multi-round-trip) fetch.
5457
+ * List the names of every SHACL shape stored in this Perspective (one RPC call).
4719
5458
  */
4720
5459
  async getShaclNames() {
4721
- const nameLinks = await this.get(new LinkQuery({
4722
- source: "ad4m://self",
4723
- predicate: "ad4m://has_shacl"
4724
- }));
4725
- // Dedupe: a perspective with duplicate `has_shacl` links (see the dedup note in
4726
- // getShacl()) would otherwise report the same name more than once, causing callers
4727
- // to redundantly resolve (or redundantly disambiguate) it multiple times.
4728
- const names = nameLinks.map((nameLink) => {
4729
- const name = Literal.fromUrl(nameLink.data.target).get();
4730
- return name.replace('shacl://', '');
4731
- });
4732
- return [...new Set(names)];
5460
+ return __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").getShaclNames(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid);
4733
5461
  }
4734
5462
  /**
4735
- * Resolve just a shape's `sh:targetClass` by name, without fetching its properties —
4736
- * two round trips (name → shapeUri, then shapeUri's own direct triples) instead of
4737
- * `getShacl()`'s full walk (which also fetches every property sub-shape). Use this to
4738
- * disambiguate a shape name that collides with another app's `@Model({ name })` string
4739
- * (the bare `shacl://{name}` mapping ad4m-core uses is namespace-blind — see
4740
- * `getShaclNames()` callers for why that matters) before paying for a full fetch.
5463
+ * Resolve a shape's `sh:targetClass` by name (one RPC call).
5464
+ *
5465
+ * `PerspectiveClient.getShaclTargetClass` now returns `undefined` on
5466
+ * "not found" already (see review r3897752023 — the null→undefined
5467
+ * coercion used to happen here and be duplicated one layer down),
5468
+ * so this method is a pure passthrough.
4741
5469
  */
4742
5470
  async getShaclTargetClass(name) {
4743
- const nameMapping = Literal.fromUrl(`literal:string:shacl://${name}`);
4744
- const shapeUriLinks = await this.get(new LinkQuery({
4745
- source: nameMapping.toUrl(),
4746
- predicate: "ad4m://shacl_shape_uri"
4747
- }));
4748
- if (shapeUriLinks.length === 0) {
4749
- return undefined;
4750
- }
4751
- const shapeUri = shapeUriLinks[0].data.target;
4752
- const shapeOwnLinks = await this.get(new LinkQuery({ source: shapeUri }));
4753
- return shapeOwnLinks.find(l => l.data.predicate === "sh://targetClass")?.data.target;
5471
+ return __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").getShaclTargetClass(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, name);
4754
5472
  }
4755
5473
  /**
4756
- * Get all SHACL shapes stored in this Perspective
5474
+ * Get all SHACL shapes stored in this Perspective (one RPC call).
5475
+ * The executor resolves all shapes in-process and returns them in bulk.
4757
5476
  */
4758
5477
  async getAllShacl() {
4759
- const shapeNames = await this.getShaclNames();
4760
- // Each shape is fetched independently of the others — resolve them concurrently.
4761
- // Sequentially awaiting getShacl() per shape means a perspective with N SDNA
4762
- // models pays N times getShacl()'s own multi-round-trip cost one after another;
4763
- // over a remote connection with real per-call latency that compounds into the
4764
- // dominant cost of switching into a perspective at all.
4765
- const results = await Promise.all(shapeNames.map(async (shapeName) => {
4766
- const shape = await this.getShacl(shapeName);
4767
- return shape ? { name: shapeName, shape } : null;
4768
- }));
4769
- return results.filter((s) => s !== null);
5478
+ const entries = await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").getAllShacl(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid);
5479
+ return entries
5480
+ .map(({ name, shapeUri, links }) => {
5481
+ const shape = SHACLShape.fromLinks(links, shapeUri);
5482
+ return shape ? { name, shape } : null;
5483
+ })
5484
+ .filter((s) => s !== null);
4770
5485
  }
4771
5486
  /**
4772
5487
  * **Recommended way to add Flow definitions.**
@@ -4781,28 +5496,26 @@ class PerspectiveProxy {
4781
5496
  * ```typescript
4782
5497
  * import { SHACLFlow } from '@coasys/ad4m';
4783
5498
  *
4784
- * const todoFlow = new SHACLFlow('TODO', 'todo://');
4785
- * todoFlow.flowable = 'any';
4786
- *
4787
- * // Define states
4788
- * todoFlow.addState({ name: 'ready', value: 0, stateCheck: { predicate: 'todo://state', target: 'todo://ready' }});
4789
- * todoFlow.addState({ name: 'done', value: 1, stateCheck: { predicate: 'todo://state', target: 'todo://done' }});
4790
- *
4791
- * // Define start action
4792
- * todoFlow.startAction = [{ action: 'addLink', source: 'this', predicate: 'todo://state', target: 'todo://ready' }];
4793
- *
4794
- * // Define transitions
4795
- * todoFlow.addTransition({
4796
- * actionName: 'Complete',
4797
- * fromState: 'ready',
4798
- * toState: 'done',
4799
- * actions: [
4800
- * { action: 'addLink', source: 'this', predicate: 'todo://state', target: 'todo://done' },
4801
- * { action: 'removeLink', source: 'this', predicate: 'todo://state', target: 'todo://ready' }
4802
- * ]
4803
- * });
5499
+ * const deliveryFlow = new SHACLFlow('Delivery', 'delivery://');
5500
+ * deliveryFlow.inputTypes = ['Task'];
5501
+ * deliveryFlow.interpretationHint =
5502
+ * 'Advance a Task through delivery: Identified → Scoped → InProgress → Review → Done.';
5503
+ *
5504
+ * deliveryFlow.addState({ name: 'Identified', value: 0 });
5505
+ * deliveryFlow.addState({ name: 'Scoped', value: 1 });
5506
+ * deliveryFlow.addState({ name: 'InProgress', value: 2 });
5507
+ * deliveryFlow.addState({ name: 'Review', value: 3 });
5508
+ * deliveryFlow.addState({ name: 'Done', value: 4 });
5509
+ *
5510
+ * deliveryFlow.addTransition({ actionName: 'Scope', fromState: 'Identified', toState: 'Scoped', actions: [] });
5511
+ * deliveryFlow.addTransition({ actionName: 'Start', fromState: 'Scoped', toState: 'InProgress', actions: [] });
5512
+ * deliveryFlow.addTransition({ actionName: 'Submit', fromState: 'InProgress', toState: 'Review', actions: [] });
5513
+ * deliveryFlow.addTransition({ actionName: 'Accept', fromState: 'Review', toState: 'Done', actions: [] });
4804
5514
  *
4805
- * await perspective.addFlow('TODO', todoFlow);
5515
+ * // Optional: n distinct DIDs must co-sign a proposal before it fires.
5516
+ * deliveryFlow.consensusRule = { n: 2 };
5517
+ *
5518
+ * await perspective.addFlow('Delivery', deliveryFlow);
4806
5519
  * ```
4807
5520
  */
4808
5521
  async addFlow(name, flow) {
@@ -4847,7 +5560,7 @@ class PerspectiveProxy {
4847
5560
  return null;
4848
5561
  }
4849
5562
  const flowUri = flowUriLinks[0].data.target;
4850
- // Fetch flow-level links (hasState, hasTransition, flowable, startAction)
5563
+ // Fetch flow-level links (hasState, hasTransition, startAction, inputTypes/outputTypes/…)
4851
5564
  const flowLevelLinks = await this.get(new LinkQuery({ source: flowUri }));
4852
5565
  // Collect state and transition URIs, then fetch their child links
4853
5566
  const childUris = flowLevelLinks
@@ -4892,6 +5605,38 @@ class PerspectiveProxy {
4892
5605
  return [];
4893
5606
  }
4894
5607
  }
5608
+ /**
5609
+ * Return the full target-class URIs of every registered SubjectClass.
5610
+ *
5611
+ * Unlike {@link subjectClasses}, which strips the namespace and returns bare
5612
+ * names (`"Space"`, `"Channel"`), this method returns the complete URIs
5613
+ * (`"we://Space"`, `"flux://Channel"`). The full URI is the key that
5614
+ * `load_shape` resolves against, so it is the only collision-safe identifier
5615
+ * — two apps can both declare a class called `"Template"` under different
5616
+ * namespaces, and the bare name cannot distinguish them.
5617
+ *
5618
+ * Callers that need to check whether a *set* of models are already
5619
+ * registered should call this once and test membership against the returned
5620
+ * set, rather than issuing one `queryLinks` per model.
5621
+ *
5622
+ * One `queryLinks` round trip, no executor-side changes.
5623
+ */
5624
+ async subjectClassTargetClasses() {
5625
+ try {
5626
+ const classLinks = await this.get(new LinkQuery({
5627
+ predicate: "rdf://type",
5628
+ target: "ad4m://SubjectClass"
5629
+ }));
5630
+ const uris = classLinks
5631
+ .map(l => l.data.source)
5632
+ .filter(source => source.length > 0);
5633
+ return [...new Set(uris)];
5634
+ }
5635
+ catch (e) {
5636
+ console.warn('subjectClassTargetClasses: lookup failed:', e);
5637
+ return [];
5638
+ }
5639
+ }
4895
5640
  async stringOrTemplateObjectToSubjectClassName(subjectClass) {
4896
5641
  if (typeof subjectClass === "string")
4897
5642
  return subjectClass;
@@ -4913,7 +5658,9 @@ class PerspectiveProxy {
4913
5658
  * with the properties of the subject class.
4914
5659
  * @param exprAddr The address of the expression to be turned into a subject instance
4915
5660
  * @param initialValues Optional initial values for properties. If provided, these will be
4916
- * merged with constructor actions for better performance.
5661
+ * merged with constructor actions for better performance. A collection property accepts
5662
+ * an array value and stores one entry per element; scalar properties store arrays/objects
5663
+ * as a single JSON value.
4917
5664
  * @param batchId Optional batch ID for grouping operations. If provided, returns the expression address
4918
5665
  * instead of the subject proxy since the subject won't exist until the batch is committed.
4919
5666
  * @returns A proxy object for the created subject, or just the expression address if in batch mode
@@ -5700,7 +6447,7 @@ class PerspectiveClient {
5700
6447
  async publishSnapshotByUUID(uuid) {
5701
6448
  return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.publishSnapshot', { uuid });
5702
6449
  }
5703
- async queryLinks(uuid, query) {
6450
+ async queryLinks(uuid, query, options) {
5704
6451
  const params = { uuid };
5705
6452
  if (query.source)
5706
6453
  params.source = query.source;
@@ -5714,14 +6461,14 @@ class PerspectiveClient {
5714
6461
  params.untilDate = query.untilDate instanceof Date ? query.untilDate.toISOString() : String(query.untilDate);
5715
6462
  if (query.limit !== undefined)
5716
6463
  params.limit = query.limit;
5717
- return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.queryLinks', params);
6464
+ return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.queryLinks', params, options);
5718
6465
  }
5719
- async queryProlog(uuid, query) {
5720
- const result = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.queryProlog', { uuid, query });
6466
+ async queryProlog(uuid, query, options) {
6467
+ const result = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.queryProlog', { uuid, query }, options);
5721
6468
  return JSON.parse(result);
5722
6469
  }
5723
- async querySparql(uuid, query) {
5724
- const result = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.querySparql', { uuid, engine: 'sparql', query });
6470
+ async querySparql(uuid, query, options) {
6471
+ const result = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.querySparql', { uuid, engine: 'sparql', query }, options);
5725
6472
  return JSON.parse(result);
5726
6473
  }
5727
6474
  async subscribeQuery(uuid, query) {
@@ -5761,10 +6508,13 @@ class PerspectiveClient {
5761
6508
  }
5762
6509
  return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.disposeQuery', { uuid, subscriptionId });
5763
6510
  }
5764
- async modelQuery(uuid, className, queryJson) {
5765
- const resultJson = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.modelQuery', { uuid, class_name: className, query_json: queryJson });
6511
+ async modelQuery(uuid, className, queryJson, options) {
6512
+ const resultJson = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.modelQuery', { uuid, class_name: className, query_json: queryJson }, options);
5766
6513
  return JSON.parse(resultJson);
5767
6514
  }
6515
+ async subjectClassesOf(uuid, uris) {
6516
+ return await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.subjectClassesOf', { uuid, uris });
6517
+ }
5768
6518
  async evaluateGetters(uuid, className, instanceIds, propertyNames) {
5769
6519
  const resultJson = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.evaluateGetters', {
5770
6520
  uuid,
@@ -5822,9 +6572,55 @@ class PerspectiveClient {
5822
6572
  * `mintScope.id` via its predicate (upserts of pre-existing instances
5823
6573
  * are NOT re-parented — same rule as the watcher).
5824
6574
  */
5825
- async runInterpretation(uuid, transcript, basePrefix, classes, existingScope, mintScope) {
6575
+ async runInterpretation(uuid, transcript, basePrefix, classes, existingScope, mintScope, observe) {
5826
6576
  const RUN_INTERPRETATION_TIMEOUT_MS = 20 * 60 * 1000;
5827
- return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.runInterpretation', { uuid, transcript, basePrefix, classes, existingScope, mintScope }, RUN_INTERPRETATION_TIMEOUT_MS);
6577
+ return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.runInterpretation', {
6578
+ uuid, transcript, basePrefix, classes, existingScope, mintScope,
6579
+ // Spread rather than always-present, so a client talking to a pre-#903
6580
+ // executor sends exactly the params it sent before. `serde` would ignore
6581
+ // the extra keys anyway; keeping the wire identical means a bug report
6582
+ // from an older node cannot be about these.
6583
+ ...(observe ? {
6584
+ observationId: observe.observationId,
6585
+ emitDebugEvents: observe.emitDebugEvents ?? false,
6586
+ } : {}),
6587
+ }, { timeoutMs: RUN_INTERPRETATION_TIMEOUT_MS });
6588
+ }
6589
+ /**
6590
+ * Tool-calling counterpart to {@link runInterpretation}. The LLM sees a
6591
+ * live per-class tool surface (`{Class}_query`, `{Class}_propose_create`,
6592
+ * `{Class}_propose_link_child`, …) and drives the extraction via tool
6593
+ * calls; buffered proposals drain through the same overlay gate the
6594
+ * single-shot path uses.
6595
+ *
6596
+ * `maxToolCalls` bounds the loop and MUST be > 0 — zero would collapse
6597
+ * the harness to a no-op final-answer step; use {@link runInterpretation}
6598
+ * for the classic single-shot path.
6599
+ *
6600
+ * Same 20-minute RPC timeout as the single-shot path — an LLM loop
6601
+ * that calls several tools can legitimately take longer than one plain
6602
+ * generation.
6603
+ */
6604
+ async runInterpretationWithHarness(uuid, transcript, basePrefix, maxToolCalls, classes, modelOverride, existingScope,
6605
+ // Optional live-debug event surface — same shape/semantics as the
6606
+ // single-shot `runInterpretation`. `observationId` names the
6607
+ // `processor_id` + `batch_key` on emitted `ToolCall` / `ToolResult`
6608
+ // events so a subscribed UI can correlate them to this pass.
6609
+ // `emitDebugEvents` is a dead-letter without an observationId
6610
+ // (nothing to key against); the server gates on both.
6611
+ observationId, emitDebugEvents) {
6612
+ const RUN_INTERPRETATION_TIMEOUT_MS = 20 * 60 * 1000;
6613
+ return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.runInterpretationWithHarness', {
6614
+ uuid,
6615
+ transcript,
6616
+ basePrefix,
6617
+ maxToolCalls,
6618
+ classes,
6619
+ modelOverride,
6620
+ existingScope,
6621
+ observationId,
6622
+ emitDebugEvents,
6623
+ }, { timeoutMs: RUN_INTERPRETATION_TIMEOUT_MS });
5828
6624
  }
5829
6625
  /**
5830
6626
  * Register a neighbourhood auto-processor on this perspective. The executor's
@@ -5837,6 +6633,10 @@ class PerspectiveClient {
5837
6633
  async addAutoProcessor(uuid, config) {
5838
6634
  return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.addAutoProcessor', { uuid, ...config });
5839
6635
  }
6636
+ /** Delete an auto-processor's config. `false` when there was none to delete. */
6637
+ async removeAutoProcessor(uuid, processorId) {
6638
+ return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.removeAutoProcessor', { uuid, processorId });
6639
+ }
5840
6640
  /** Pending interpretation overlays (LLM suggestions awaiting human accept/reject). */
5841
6641
  async interpretationOverlays(uuid) {
5842
6642
  return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.interpretationOverlays', { uuid });
@@ -5851,6 +6651,18 @@ class PerspectiveClient {
5851
6651
  async rejectInterpretation(uuid, base, property) {
5852
6652
  return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.rejectInterpretation', { uuid, base, property });
5853
6653
  }
6654
+ async acceptFlowProposal(uuid, proposalUri) {
6655
+ return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.acceptFlowProposal', { uuid, proposalUri });
6656
+ }
6657
+ /**
6658
+ * Withdraw this agent's own links from a proposal. Resolves to how many
6659
+ * were retracted — one for a withdrawn vote, more when retracting a
6660
+ * proposal this agent opened.
6661
+ */
6662
+ async rejectFlowProposal(uuid, proposalUri) {
6663
+ const result = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.rejectFlowProposal', { uuid, proposalUri });
6664
+ return result.retractedLinks;
6665
+ }
5854
6666
  /**
5855
6667
  * Subscribe to auto-processor step signals. `cb` fires for every
5856
6668
  * `auto-processor-event` on `uuid` (BatchReady → Claimed/BackedOff/… →
@@ -5919,6 +6731,43 @@ class PerspectiveClient {
5919
6731
  async getSubjectData(uuid, subjectClass, expressionAddress) {
5920
6732
  return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.getSubjectData', { uuid, subjectClass, expressionAddress });
5921
6733
  }
6734
+ // ── SHACL resolution (server-side) ─────────────────────────────────────────
6735
+ // These methods delegate shape resolution to the executor, which reads links
6736
+ // from its local store in-process. Each call replaces the multi-round-trip
6737
+ // `queryLinks` sequences the old PerspectiveProxy methods performed.
6738
+ /** List the names of every SHACL shape stored in a perspective (one RPC call). */
6739
+ async getShaclNames(uuid) {
6740
+ return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.getShaclNames', { uuid });
6741
+ }
6742
+ /**
6743
+ * Resolve a shape's `sh:targetClass` by name (one RPC call).
6744
+ *
6745
+ * Returns `undefined` when the shape (or its `sh://targetClass` edge) is
6746
+ * absent — unified with `PerspectiveProxy.getShaclTargetClass` so callers
6747
+ * see a single "not found" representation across both layers. The
6748
+ * executor wire format is still `null` (see `perspective.getShaclTargetClass`
6749
+ * in `perspectives_ws.rs`); this method maps that at the boundary rather
6750
+ * than pushing the null one layer further up. PR #935 review r3897752023.
6751
+ */
6752
+ async getShaclTargetClass(uuid, name) {
6753
+ const result = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.getShaclTargetClass', { uuid, name });
6754
+ return result ?? undefined;
6755
+ }
6756
+ /**
6757
+ * Retrieve a single SHACL shape's link triples by name (one RPC call).
6758
+ * Returns `{shapeUri, links}` for reconstruction via `SHACLShape.fromLinks()`,
6759
+ * or `null` if no shape with that name exists.
6760
+ */
6761
+ async getShacl(uuid, name) {
6762
+ return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.getShacl', { uuid, name });
6763
+ }
6764
+ /**
6765
+ * Retrieve all SHACL shapes in one call. Returns an array of
6766
+ * `{name, shapeUri, links}` — one entry per shape (one RPC call).
6767
+ */
6768
+ async getAllShacl(uuid) {
6769
+ return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.getAllShacl', { uuid });
6770
+ }
5922
6771
  // ExpressionClient functions, needed for Subjects:
5923
6772
  async getExpression(expressionURI) {
5924
6773
  return await __classPrivateFieldGet$9(this, _PerspectiveClient_expressionClient, "f").get(expressionURI);
@@ -6040,6 +6889,11 @@ class PerspectiveClient {
6040
6889
  async commitBatch(uuid, batchId) {
6041
6890
  return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.commitBatch', { uuid, batchId });
6042
6891
  }
6892
+ /** Register a callback that fires after a successful WebSocket reconnect.
6893
+ * Passes through to ApiClient.onReconnect(). Returns an unsubscribe function. */
6894
+ onReconnect(callback) {
6895
+ return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").onReconnect(callback);
6896
+ }
6043
6897
  }
6044
6898
  _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();
6045
6899
 
@@ -14173,6 +15027,21 @@ class AIClient {
14173
15027
  async getModels() {
14174
15028
  return __classPrivateFieldGet$2(this, _AIClient_apiClient, "f").call('ai.models');
14175
15029
  }
15030
+ /**
15031
+ * Ask a remote endpoint which models it serves, before adding one.
15032
+ *
15033
+ * Takes the credentials of a model that does not exist yet — a settings
15034
+ * form is being filled in and wants the list to pick from. Rejects when
15035
+ * the endpoint is unreachable or the key is refused, which makes this the
15036
+ * credential check too: without it a bad key surfaces later as a failed
15037
+ * completion carrying an error from a different layer.
15038
+ *
15039
+ * `apiType` defaults to the OpenAI shape, which is what every endpoint
15040
+ * that is not Anthropic speaks.
15041
+ */
15042
+ async discoverModels(baseUrl, apiKey, apiType) {
15043
+ return __classPrivateFieldGet$2(this, _AIClient_apiClient, "f").call('ai.discoverModels', { baseUrl, apiKey, apiType });
15044
+ }
14176
15045
  async addModel(model) {
14177
15046
  return __classPrivateFieldGet$2(this, _AIClient_apiClient, "f").call('ai.addModel', { model: this.serializeModelInput(model) });
14178
15047
  }
@@ -14218,9 +15087,12 @@ class AIClient {
14218
15087
  async embed(modelId, text) {
14219
15088
  const aiEmbed = await __classPrivateFieldGet$2(this, _AIClient_apiClient, "f").call('ai.embed', { modelId, text });
14220
15089
  const compressed = base64Js.toByteArray(aiEmbed);
14221
- // Decode to a string via TextDecoder rather than pako's `{ to: 'string' }`
14222
- // option: newer @types/pako dropped that overload, which broke the build.
14223
- const decompressed = JSON.parse(new TextDecoder().decode(pako.inflate(compressed)));
15090
+ // NB: pako v1 accepts `{ to: 'string' }`, pako v2 wants `{ toText: true }`,
15091
+ // pako v3 also drops that overload from its bundled types. Call the
15092
+ // version-agnostic form (returns Uint8Array) and decode explicitly so
15093
+ // this works regardless of which pako major the lockfile pins.
15094
+ const inflated = pako.inflate(compressed);
15095
+ const decompressed = JSON.parse(new TextDecoder('utf-8').decode(inflated));
14224
15096
  return decompressed;
14225
15097
  }
14226
15098
  async openTranscriptionStream(modelId, streamCallback, params) {
@@ -14280,6 +15152,27 @@ class AIClient {
14280
15152
  }
14281
15153
  _AIClient_apiClient = new WeakMap(), _AIClient_transcriptionUnsubscribers = new WeakMap(), _AIClient_pendingStreamIds = new WeakMap();
14282
15154
 
15155
+ /**
15156
+ * Shared type definitions for the Ad4mModel system.
15157
+ *
15158
+ * Extracted into a standalone module so that utility files
15159
+ * (`query-utils.ts`, `decorators.ts`, etc.) can import types without
15160
+ * creating circular runtime dependencies on `Ad4mModel.ts`.
15161
+ */
15162
+ /**
15163
+ * Whether this scope is a traversal rather than a single named parent.
15164
+ *
15165
+ * The other two forms carry `id`; this one carries `ids` and may name several,
15166
+ * so anything reaching for one parent — every write path — has to ask first.
15167
+ */
15168
+ function isTraverseScope(scope) {
15169
+ return 'ids' in scope;
15170
+ }
15171
+ /** Type guard for IncludeProjection objects. */
15172
+ function isIncludeProjection(val) {
15173
+ return typeof val === 'object' && val !== null && 'from' in val;
15174
+ }
15175
+
14283
15176
  /**
14284
15177
  * Shared query helpers used by both the Prolog and SPARQL query pipelines.
14285
15178
  */
@@ -14292,6 +15185,21 @@ _AIClient_apiClient = new WeakMap(), _AIClient_transcriptionUnsubscribers = new
14292
15185
  * - With `field`: direct key lookup
14293
15186
  * - Without `field`: scan for a relation whose `target()` matches `childCtor`
14294
15187
  */
15188
+ /**
15189
+ * Narrow a scope to the one-parent forms, for the paths that write a link.
15190
+ *
15191
+ * A traversal describes a read outward from several anchors. Creating a record
15192
+ * "under" one would have to pick which, and nothing in the scope says — so this
15193
+ * refuses rather than guessing at the first of the list. The executor's write
15194
+ * scopes refuse it for the same reason.
15195
+ */
15196
+ function requireSingleParent(parent) {
15197
+ if (isTraverseScope(parent)) {
15198
+ throw new Error('parent(): a traverse scope describes a read and names no single parent to write under. ' +
15199
+ 'Use { id, predicate } or { model, id } when creating a record under a parent.');
15200
+ }
15201
+ return parent;
15202
+ }
14295
15203
  function resolveParentPredicate(parent, childCtor) {
14296
15204
  // Raw form — explicit predicate
14297
15205
  if ('predicate' in parent)
@@ -14872,8 +15780,31 @@ function buildSPARQLQuery(metadata, allRelationsMetadata, query, modelClass) {
14872
15780
  // Parent filter — direct triple pattern
14873
15781
  if (query.parent) {
14874
15782
  const parentPredicate = resolveParentPredicate(query.parent, modelClass);
14875
- joinPatterns.push(`
15783
+ if (isTraverseScope(query.parent)) {
15784
+ const { ids, transitive, direction, limitPerAnchor } = query.parent;
15785
+ // `limitPerAnchor` is applied by the executor between selecting ids and
15786
+ // hydrating them, which is a shape this path does not have — it builds one
15787
+ // query and reads the rows. Refused rather than ignored: quietly returning
15788
+ // every reply where five per parent were asked for is a wrong answer that
15789
+ // looks like a right one.
15790
+ if (limitPerAnchor !== undefined) {
15791
+ throw new Error('buildSPARQLQuery: limitPerAnchor is applied by the executor between query phases and ' +
15792
+ 'has no equivalent here. Use the model query path for per-anchor limits.');
15793
+ }
15794
+ const anchors = (Array.isArray(ids) ? ids : [ids]).map(iri).join(' ');
15795
+ const path = transitive ? '+' : '';
15796
+ joinPatterns.push(`
15797
+ VALUES ?_anchor { ${anchors} }`);
15798
+ joinPatterns.push(direction === 'in'
15799
+ ? `
15800
+ ?source ${iri(parentPredicate)}${path} ?_anchor .`
15801
+ : `
15802
+ ?_anchor ${iri(parentPredicate)}${path} ?source .`);
15803
+ }
15804
+ else {
15805
+ joinPatterns.push(`
14876
15806
  ${iri(query.parent.id)} ${iri(parentPredicate)} ?source .`);
15807
+ }
14877
15808
  }
14878
15809
  // Required property JOIN patterns — direct triple patterns
14879
15810
  let hasConformance = false;
@@ -15532,13 +16463,10 @@ class ModelQueryBuilder {
15532
16463
  const unsubscribe = this.perspective.client.subscribeToQueryUpdates(subscriptionId, (rawResult) => {
15533
16464
  try {
15534
16465
  const results = parseResults(rawResult);
15535
- console.debug(`[ModelQueryBuilder.subscribe] Update received for ${subscriptionId}: ${results.length} instances`);
15536
16466
  const fp = buildFingerprint(results);
15537
16467
  if (fp === lastResultFingerprint) {
15538
- console.debug(`[ModelQueryBuilder.subscribe] Fingerprint unchanged, skipping callback`);
15539
16468
  return;
15540
16469
  }
15541
- console.debug(`[ModelQueryBuilder.subscribe] Fingerprint changed, calling callback with ${results.length} results`);
15542
16470
  lastResultFingerprint = fp;
15543
16471
  callback(results);
15544
16472
  }
@@ -15807,8 +16735,21 @@ class ModelQueryBuilder {
15807
16735
  offset: pageSize * (pageNumber - 1),
15808
16736
  count: true,
15809
16737
  };
16738
+ // Each server dispatch triggers an independent async re-fetch, and those
16739
+ // re-fetches resolve in completion order, not dispatch order. A re-fetch
16740
+ // dispatched *before* a write committed can resolve *after* the re-fetch
16741
+ // that saw the write, silently rolling the consumer back to a stale page —
16742
+ // and no later dispatch ever corrects it. The generation counter drops any
16743
+ // fetch that is no longer the newest one started; the newest fetch always
16744
+ // delivers, so the callback is monotone in dispatch order.
16745
+ let fetchGeneration = 0;
15810
16746
  const processResults = async () => {
16747
+ const generation = ++fetchGeneration;
15811
16748
  const { results, totalCount } = await ctor.executeModelQuery(this.perspective, paginatedQuery, this.modelClassName);
16749
+ if (generation !== fetchGeneration) {
16750
+ console.debug(`[ModelQueryBuilder.paginateSubscribe] Dropping stale re-fetch result (generation ${generation}, newest ${fetchGeneration})`);
16751
+ return;
16752
+ }
15812
16753
  callback({ results, totalCount, pageSize, pageNumber });
15813
16754
  };
15814
16755
  const unsubscribe = this.perspective.client.subscribeToQueryUpdates(subscriptionId, (rawResult) => {
@@ -15903,6 +16844,110 @@ function normalizeValue(value) {
15903
16844
  * Rust endpoint. Recursively converts included relation values (which come
15904
16845
  * back as plain JSON objects) into proper model class instances.
15905
16846
  */
16847
+ /**
16848
+ * Key under which the executor returns a polymorphically-hydrated instance's
16849
+ * concrete class.
16850
+ *
16851
+ * Half of a wire contract: the writer is `SUBJECT_CLASS_KEY` in
16852
+ * `rust-executor/src/perspectives/model_query/relations.rs`, and the two are
16853
+ * separate literals in separate languages. Renaming one alone does not fail to
16854
+ * compile — it degrades to every instance staying plain JSON, which looks
16855
+ * identical to a relation that declared no classes to build.
16856
+ * `tests/js/tests/model/model-polymorphic.test.ts` drives both ends against one
16857
+ * executor, so the drift fails a test rather than a user's query.
16858
+ *
16859
+ * The executor also returns `__subjectClasses`, the whole set this one names the
16860
+ * head of. Nothing here reads it — it rides onto the instance with every other
16861
+ * JSON key, for a caller that wants to know a choice was made.
16862
+ */
16863
+ const SUBJECT_CLASS_KEY = '__subjectClass';
16864
+ /**
16865
+ * Turn on `polymorphic` for every relation that declares it, at every depth of
16866
+ * an include map.
16867
+ *
16868
+ * A relation being heterogeneous is a fact about the data, not about one query,
16869
+ * so the declaration lives on the model and the call site writes
16870
+ * `include: { children: true }`. That has to hold just as much one level down:
16871
+ * in `include: { posts: { include: { children: true } } }`, `children` is a
16872
+ * relation on `Post`, so the walk carries the class it is reading against down
16873
+ * with it. Without that, a nested include of an untyped polymorphic relation
16874
+ * reaches the executor with no shape to resolve and fails the query outright.
16875
+ *
16876
+ * An explicit `polymorphic: false` at any level still wins — `undefined` is the
16877
+ * only state the default fills in.
16878
+ *
16879
+ * The walk stops descending *through* a polymorphic relation, because there is
16880
+ * nothing to descend into: its targets are of several classes by definition, so
16881
+ * no single class's metadata could say what a deeper include means. The
16882
+ * executor resolves those nested includes against each concrete class instead.
16883
+ */
16884
+ function applyPolymorphicIncludeDefaults(includes, ctor) {
16885
+ const relMeta = getRelationsMetadata(ctor);
16886
+ for (const [relName, val] of Object.entries(includes)) {
16887
+ // `$`-prefixed keys are projections, not relations.
16888
+ if (relName.startsWith('$'))
16889
+ continue;
16890
+ const meta = relMeta[relName];
16891
+ if (!meta)
16892
+ continue;
16893
+ let subQuery = val;
16894
+ if (meta.polymorphic) {
16895
+ if (val === true) {
16896
+ subQuery = { polymorphic: true };
16897
+ includes[relName] = subQuery;
16898
+ }
16899
+ else if (typeof val === 'object' && val !== null && subQuery.polymorphic === undefined) {
16900
+ subQuery.polymorphic = true;
16901
+ }
16902
+ // The classes this call site can build are also the classes it wants its
16903
+ // targets read as, so the declaration answers both questions and the call
16904
+ // site repeats neither. Sent as part of the query rather than applied to
16905
+ // the results: a preference in the request is reproducible by anyone who
16906
+ // sends it, where one applied afterwards would make the same data read
16907
+ // differently depending on which classes the caller happened to import.
16908
+ //
16909
+ // It ranks and does not narrow — a target matching none of them still
16910
+ // arrives — so declaring what you can construct never costs you a member
16911
+ // of a relation that is heterogeneous by definition.
16912
+ if (typeof subQuery === 'object' &&
16913
+ subQuery !== null &&
16914
+ subQuery.polymorphic &&
16915
+ subQuery.preferClasses === undefined &&
16916
+ meta.instantiateAs) {
16917
+ const names = (meta.instantiateAs() ?? [])
16918
+ .map((cls) => cls?.className)
16919
+ .filter((name) => typeof name === 'string');
16920
+ if (names.length)
16921
+ subQuery.preferClasses = names;
16922
+ }
16923
+ }
16924
+ if (typeof subQuery !== 'object' || subQuery === null)
16925
+ continue;
16926
+ const nested = subQuery.include;
16927
+ if (!nested || subQuery.polymorphic)
16928
+ continue;
16929
+ // The thunk is only evaluated here, at query time, so a self-referential or
16930
+ // circularly-imported target that is not yet defined costs the nested
16931
+ // default rather than the whole query.
16932
+ let TargetClass;
16933
+ try {
16934
+ TargetClass = meta.target?.();
16935
+ }
16936
+ catch (e) {
16937
+ // A class not yet initialised throws `ReferenceError` from the temporal
16938
+ // dead zone, which is the expected cost of an import cycle and not worth
16939
+ // saying anything about. Anything else — a thunk closing over nothing,
16940
+ // typically — is a broken declaration that would otherwise cost the nested
16941
+ // default in silence, so it gets said out loud.
16942
+ const circularImport = e instanceof ReferenceError;
16943
+ const say = circularImport ? console.debug : console.warn;
16944
+ say(`prepareModelQueryParams: target class unavailable for include '${relName}':`, e);
16945
+ continue;
16946
+ }
16947
+ if (TargetClass)
16948
+ applyPolymorphicIncludeDefaults(nested, TargetClass);
16949
+ }
16950
+ }
15906
16951
  function jsonToModelInstance(ModelClass, perspective, json, include, properties) {
15907
16952
  const instance = new ModelClass(perspective, json.id || json.baseExpression);
15908
16953
  // When a properties projection is active, remove own properties set by the
@@ -15949,9 +16994,62 @@ function jsonToModelInstance(ModelClass, perspective, json, include, properties)
15949
16994
  if (!includeVal)
15950
16995
  continue;
15951
16996
  const meta = relMeta[relName];
15952
- if (!meta?.target)
16997
+ // A polymorphic relation may legitimately declare no target at all —
16998
+ // that is the case it exists for — so it must not be gated on one.
16999
+ if (!meta)
17000
+ continue;
17001
+ if (!meta.target && !meta.polymorphic)
15953
17002
  continue;
15954
- const TargetClass = meta.target();
17003
+ const TargetClass = meta.target?.();
17004
+ // For a polymorphic relation the executor sends each child's concrete
17005
+ // class back on the instance, because it had to know it in order to
17006
+ // hydrate against the right shape at all. What it cannot send is the
17007
+ // constructor, so `instantiateAs` names the classes this side can build
17008
+ // and the name → class map is derived from them: `@Model` records each
17009
+ // class's name on the class itself, so listing the classes and listing
17010
+ // their names would be the same list written twice, free to disagree.
17011
+ //
17012
+ // Built on first use rather than at decoration time, because the thunk
17013
+ // exists to be called late: a class defined further round a circular
17014
+ // import graph is not there yet when the decorator runs.
17015
+ let byClassName;
17016
+ // May resolve to nothing: a polymorphic relation is allowed to declare no
17017
+ // target at all, and the list may not name the class that arrived — it
17018
+ // says what this call site can construct, not what the relation may hold.
17019
+ // The item then stays plain JSON — correct data, carrying its class name
17020
+ // for a caller that wants to dispatch on it — rather than being forced
17021
+ // through a constructor that does not exist.
17022
+ const resolveChildClass = (item) => {
17023
+ if (!meta.polymorphic)
17024
+ return TargetClass;
17025
+ const concrete = item?.[SUBJECT_CLASS_KEY];
17026
+ // No concrete class means this was not read polymorphically after all —
17027
+ // an explicit `polymorphic: false` at the call site — so the relation's
17028
+ // own declared target is the right shape.
17029
+ if (typeof concrete !== 'string')
17030
+ return TargetClass;
17031
+ if (meta.instantiateAs) {
17032
+ if (!byClassName) {
17033
+ byClassName = {};
17034
+ for (const cls of meta.instantiateAs() ?? []) {
17035
+ const name = cls?.className;
17036
+ if (typeof name === 'string')
17037
+ byClassName[name] = cls;
17038
+ }
17039
+ }
17040
+ if (byClassName[concrete])
17041
+ return byClassName[concrete];
17042
+ }
17043
+ // The declared target is not a fallback, and having named no classes to
17044
+ // build does not make it one. Where a relation both declares a target
17045
+ // and reads polymorphically, a child of some third class was hydrated
17046
+ // against *its own* shape, so constructing the declared class over that
17047
+ // JSON produces an instance that answers `instanceof` for a class it is
17048
+ // not, carrying fields that class never declared — the exact
17049
+ // mislabelling polymorphic reads exist to prevent. It fits only when it
17050
+ // is the class the executor named.
17051
+ return TargetClass?.className === concrete ? TargetClass : undefined;
17052
+ };
15955
17053
  const nestedInclude = typeof includeVal === 'object' && includeVal !== null
15956
17054
  ? includeVal.include
15957
17055
  : undefined;
@@ -15961,14 +17059,18 @@ function jsonToModelInstance(ModelClass, perspective, json, include, properties)
15961
17059
  const raw = instance[relName];
15962
17060
  if (Array.isArray(raw)) {
15963
17061
  instance[relName] = raw.map((item) => {
15964
- if (typeof item === 'object' && item !== null && item.id) {
15965
- return jsonToModelInstance(TargetClass, perspective, item, nestedInclude, nestedProperties);
17062
+ const ChildClass = resolveChildClass(item);
17063
+ if (ChildClass && typeof item === 'object' && item !== null && item.id) {
17064
+ return jsonToModelInstance(ChildClass, perspective, item, nestedInclude, nestedProperties);
15966
17065
  }
15967
17066
  return item;
15968
17067
  });
15969
17068
  }
15970
17069
  else if (typeof raw === 'object' && raw !== null && raw.id) {
15971
- instance[relName] = jsonToModelInstance(TargetClass, perspective, raw, nestedInclude, nestedProperties);
17070
+ const ChildClass = resolveChildClass(raw);
17071
+ if (ChildClass) {
17072
+ instance[relName] = jsonToModelInstance(ChildClass, perspective, raw, nestedInclude, nestedProperties);
17073
+ }
15972
17074
  }
15973
17075
  }
15974
17076
  }
@@ -16216,6 +17318,7 @@ class Ad4mModel {
16216
17318
  ...(options.target !== undefined && { target: options.target }),
16217
17319
  ...(options.filter !== undefined && { filter: options.filter }),
16218
17320
  ...(options.where !== undefined && { where: options.where }),
17321
+ ...(options.ordering !== undefined && { ordering: options.ordering }),
16219
17322
  };
16220
17323
  }
16221
17324
  // Fallback: If both structures are empty but a JSON schema is attached, derive from it
@@ -16483,10 +17586,22 @@ class Ad4mModel {
16483
17586
  const current = normalizeValue(this[field]);
16484
17587
  const original = this._snapshot[field];
16485
17588
  if (Array.isArray(current) || Array.isArray(original)) {
16486
- // Order-insensitive comparison (sorted) so reordering alone
16487
- // doesn't mark a relation as dirty.
16488
- const a = Array.isArray(current) ? [...current].sort() : [];
16489
- const b = Array.isArray(original) ? [...original].sort() : [];
17589
+ // For an ordered relation the sequence *is* the state, so a reorder is
17590
+ // the whole change and must mark the field dirty — sorting first would
17591
+ // make `save()` a no-op for the one edit the ordering feature exists to
17592
+ // support.
17593
+ //
17594
+ // Everything else compares order-insensitively, because an unordered
17595
+ // relation is a set: the executor returns its members by link timestamp,
17596
+ // and a caller who assigned the same members in another order has not
17597
+ // changed anything.
17598
+ const ordered = !!metadata.relations[field]?.ordering;
17599
+ const a = Array.isArray(current) ? [...current] : [];
17600
+ const b = Array.isArray(original) ? [...original] : [];
17601
+ if (!ordered) {
17602
+ a.sort();
17603
+ b.sort();
17604
+ }
16490
17605
  if (a.length !== b.length || a.some((v, i) => v !== b[i])) {
16491
17606
  changed.push(field);
16492
17607
  }
@@ -16609,7 +17724,12 @@ class Ad4mModel {
16609
17724
  const queryInput = {};
16610
17725
  if (query.parent) {
16611
17726
  const parentPredicate = resolveParentPredicate(query.parent, this);
16612
- queryInput.parent = { id: query.parent.id, predicate: parentPredicate };
17727
+ // A traversal is forwarded as it was written: the executor reads `ids`,
17728
+ // and flattening it to one `id` here is how a request for a whole level
17729
+ // would quietly become a request for one parent's children.
17730
+ queryInput.parent = isTraverseScope(query.parent)
17731
+ ? { ...query.parent, predicate: parentPredicate }
17732
+ : { id: query.parent.id, predicate: parentPredicate };
16613
17733
  }
16614
17734
  if (query.properties)
16615
17735
  queryInput.properties = query.properties;
@@ -16626,8 +17746,17 @@ class Ad4mModel {
16626
17746
  normalIncludes[key] = val;
16627
17747
  }
16628
17748
  }
16629
- if (Object.keys(normalIncludes).length > 0)
17749
+ // A relation declared `polymorphic` reads that way by default, so the
17750
+ // caller writes `include: { children: true }` and still gets each child
17751
+ // hydrated as the class it actually is. Declaring it on the model rather
17752
+ // than repeating it at every call site is the point — the relation being
17753
+ // heterogeneous is a fact about the data, not about one query — but an
17754
+ // explicit `polymorphic: false` at the call site still wins. Applied at
17755
+ // every depth, since a nested include is a fact about the data too.
17756
+ if (Object.keys(normalIncludes).length > 0) {
17757
+ applyPolymorphicIncludeDefaults(normalIncludes, this);
16630
17758
  queryInput.include = normalIncludes;
17759
+ }
16631
17760
  if (Object.keys(projections).length > 0) {
16632
17761
  // Tag each projection with its target class name so the executor can
16633
17762
  // resolve the target shape through its in-memory cache when applying
@@ -16693,11 +17822,11 @@ class Ad4mModel {
16693
17822
  *
16694
17823
  * @internal
16695
17824
  */
16696
- static async executeModelQuery(perspective, query = {}, classNameOverride) {
17825
+ static async executeModelQuery(perspective, query = {}, classNameOverride, options) {
16697
17826
  // Delegate query input building to the shared prepareModelQueryParams
16698
17827
  // helper. The executor resolves the shape from SHACL server-side.
16699
17828
  const { className, queryJson } = this.prepareModelQueryParams(query, classNameOverride);
16700
- const result = await perspective.modelQuery(className, queryJson);
17829
+ const result = await perspective.modelQuery(className, queryJson, options);
16701
17830
  // Convert JSON instances to model class instances, recursively constructing
16702
17831
  // class instances for any included relations resolved by Rust.
16703
17832
  const instances = result.instances.map((json) => {
@@ -16738,12 +17867,12 @@ class Ad4mModel {
16738
17867
  * });
16739
17868
  * ```
16740
17869
  */
16741
- static async findAll(perspective, query) {
17870
+ static async findAll(perspective, query, options) {
16742
17871
  const q = (query ?? {});
16743
17872
  if (q.properties && q.properties.length === 0) {
16744
17873
  throw new Error("properties[] must not be empty — omit the field to return all properties, or specify at least one field name");
16745
17874
  }
16746
- const { results } = await this.executeModelQuery(perspective, q);
17875
+ const { results } = await this.executeModelQuery(perspective, q, undefined, options);
16747
17876
  return results;
16748
17877
  }
16749
17878
  /**
@@ -16766,9 +17895,9 @@ class Ad4mModel {
16766
17895
  * }
16767
17896
  * ```
16768
17897
  */
16769
- static async findOne(perspective, query) {
17898
+ static async findOne(perspective, query, options) {
16770
17899
  const limitedQuery = { ...(query ?? {}), limit: 1 };
16771
- const results = await this.findAll(perspective, limitedQuery);
17900
+ const results = await this.findAll(perspective, limitedQuery, options);
16772
17901
  return results[0] ?? null;
16773
17902
  }
16774
17903
  /**
@@ -16788,8 +17917,8 @@ class Ad4mModel {
16788
17917
  * console.log(`Showing 10 of ${totalCount} dessert recipes`);
16789
17918
  * ```
16790
17919
  */
16791
- static async findAllAndCount(perspective, query) {
16792
- const out = await this.executeModelQuery(perspective, (query ?? {}));
17920
+ static async findAllAndCount(perspective, query, options) {
17921
+ const out = await this.executeModelQuery(perspective, (query ?? {}), undefined, options);
16793
17922
  return out;
16794
17923
  }
16795
17924
  /**
@@ -16809,9 +17938,9 @@ class Ad4mModel {
16809
17938
  * console.log(`Page ${page.pageNumber} of recipes, ${page.results.length} items`);
16810
17939
  * ```
16811
17940
  */
16812
- static async paginate(perspective, pageSize, pageNumber, query) {
17941
+ static async paginate(perspective, pageSize, pageNumber, query, options) {
16813
17942
  const paginationQuery = { ...(query ?? {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
16814
- const { results, totalCount } = await this.executeModelQuery(perspective, paginationQuery);
17943
+ const { results, totalCount } = await this.executeModelQuery(perspective, paginationQuery, undefined, options);
16815
17944
  return { results: results, totalCount, pageSize, pageNumber };
16816
17945
  }
16817
17946
  /**
@@ -16839,8 +17968,8 @@ class Ad4mModel {
16839
17968
  * });
16840
17969
  * ```
16841
17970
  */
16842
- static async count(perspective, query) {
16843
- const { totalCount } = await this.executeModelQuery(perspective, { ...(query ?? {}), limit: 0 });
17971
+ static async count(perspective, query, options) {
17972
+ const { totalCount } = await this.executeModelQuery(perspective, { ...(query ?? {}), limit: 0 }, undefined, options);
16844
17973
  return totalCount;
16845
17974
  }
16846
17975
  async setProperty(key, value, batchId) {
@@ -16994,7 +18123,18 @@ class Ad4mModel {
16994
18123
  for (const [key, value] of Object.entries(this)) {
16995
18124
  if (value !== undefined && value !== null && !(Array.isArray(value) && value.length > 0) && !value?.action) {
16996
18125
  const propMeta = metadata.properties[key];
16997
- if (propMeta && effectiveLiteralStorage(propMeta).kind !== "deterministic") {
18126
+ // Only offer keys with a declared, settable model property. This
18127
+ // excludes ORM bookkeeping fields (_baseExpression, _perspective —
18128
+ // enumerable instance fields, not model properties), HasMany
18129
+ // relations (tracked in a separate registry, never in
18130
+ // `metadata.properties`), and read-only properties/flags
18131
+ // (readOnly: true). None of these have an `ad4m://setter` on the
18132
+ // Rust side, which otherwise logs a "declares no setter" warning
18133
+ // per key on every save().
18134
+ if (!propMeta || propMeta.readOnly) {
18135
+ continue;
18136
+ }
18137
+ if (effectiveLiteralStorage(propMeta).kind !== "deterministic") {
16998
18138
  deferredExpressionProps.push(key);
16999
18139
  continue;
17000
18140
  }
@@ -17103,13 +18243,36 @@ class Ad4mModel {
17103
18243
  await this.setRelationValues(key, value, batchId);
17104
18244
  }
17105
18245
  else if (value !== undefined && value !== null && value !== "") {
18246
+ // A scalar handed to a relation field is a single-member relation.
18247
+ //
18248
+ // This used to `continue` — "Skip, it's a relation, not a regular
18249
+ // property" — so `Model.create(p, { source: 'uri://x' })` typechecked,
18250
+ // ran, resolved, and wrote no link. The record was created with the
18251
+ // relation empty and nothing anywhere said so, which surfaces later as
18252
+ // a *reader* complaining about a malformed instance: a Relationship
18253
+ // with no endpoints, a Placement pointing at nothing. Both look like
18254
+ // rendering bugs from the outside, because the record exists and the
18255
+ // thing that should reference it does not.
18256
+ //
18257
+ // The array form is the documented path and stays correct; the problem
18258
+ // is that the scalar form is plausible, typechecks against a field
18259
+ // declared `string`, and fails silently. Coercing matches what a caller
18260
+ // reaching for it meant. A value `setRelationValues` cannot use now
18261
+ // fails there, loudly, instead of vanishing here.
18262
+ //
18263
+ // Deliberately outside the `setProperties` gate, mirroring the array
18264
+ // branch above. `create` passes `setProperties: false` when the class
18265
+ // has a constructor, because `create_subject` writes the values map —
18266
+ // but a relation carries `ad4m://adder`, not `ad4m://setter`, so
18267
+ // `create_subject` drops it (see the warning added in 3ee2b5bc6).
18268
+ // Relations have to be written here in both cases or they are lost by
18269
+ // both paths at once.
18270
+ const relationMeta = this.getRelationOptions(key);
18271
+ if (relationMeta) {
18272
+ await this.setRelationValues(key, [value], batchId);
18273
+ continue;
18274
+ }
17106
18275
  if (setProperties) {
17107
- // Check if this is a relation property (has relation metadata)
17108
- const relationMeta = this.getRelationOptions(key);
17109
- if (relationMeta) {
17110
- // Skip - it's a relation, not a regular property
17111
- continue;
17112
- }
17113
18276
  // Skip flag properties — they are immutable after creation
17114
18277
  const propMeta = this.getPropertyMetadata(key);
17115
18278
  if (propMeta?.flag) {
@@ -17338,9 +18501,10 @@ class Ad4mModel {
17338
18501
  if (options?.parent && !options?.batchId) {
17339
18502
  const batchId = await perspective.createBatch();
17340
18503
  await instance.save(batchId);
17341
- const predicate = resolveParentPredicate(options.parent, this);
18504
+ const parent = requireSingleParent(options.parent);
18505
+ const predicate = resolveParentPredicate(parent, this);
17342
18506
  const link = new Link({
17343
- source: options.parent.id,
18507
+ source: parent.id,
17344
18508
  predicate,
17345
18509
  target: instance.id,
17346
18510
  });
@@ -17354,9 +18518,10 @@ class Ad4mModel {
17354
18518
  await instance.save(options?.batchId);
17355
18519
  // Create parent → child link if a parent scope was provided
17356
18520
  if (options?.parent) {
17357
- const predicate = resolveParentPredicate(options.parent, this);
18521
+ const parent = requireSingleParent(options.parent);
18522
+ const predicate = resolveParentPredicate(parent, this);
17358
18523
  const link = new Link({
17359
- source: options.parent.id,
18524
+ source: parent.id,
17360
18525
  predicate,
17361
18526
  target: instance.id,
17362
18527
  });
@@ -17939,13 +19104,13 @@ class PerspectiveHandle {
17939
19104
  * const runs = await InterpretationRun.findAll(perspective);
17940
19105
  * const configs = await AutoProcessorConfig.findAll(perspective);
17941
19106
  */
17942
- var __decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
19107
+ var __decorate$1 = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
17943
19108
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
17944
19109
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
17945
19110
  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;
17946
19111
  return c > 3 && r && Object.defineProperty(target, key, r), r;
17947
19112
  };
17948
- var __metadata = (undefined && undefined.__metadata) || function (k, v) {
19113
+ var __metadata$1 = (undefined && undefined.__metadata) || function (k, v) {
17949
19114
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
17950
19115
  };
17951
19116
  // ── AutoProcessorConfig ─────────────────────────────────────────────────────
@@ -17984,71 +19149,67 @@ exports.AutoProcessorConfig = class AutoProcessorConfig extends Ad4mModel {
17984
19149
  // `batchMax` + `claimTtlMs` — the Rust SDNA takes the same shape.
17985
19150
  }
17986
19151
  };
17987
- __decorate([
19152
+ __decorate$1([
17988
19153
  Property({ through: "ad4m://processor_id", required: true, identity: true }),
17989
- __metadata("design:type", String)
19154
+ __metadata$1("design:type", String)
17990
19155
  ], exports.AutoProcessorConfig.prototype, "processorId", void 0);
17991
- __decorate([
19156
+ __decorate$1([
17992
19157
  Property({ through: "ad4m://source_scope_query", required: true }),
17993
- __metadata("design:type", String)
19158
+ __metadata$1("design:type", String)
17994
19159
  ], exports.AutoProcessorConfig.prototype, "sourceScopeQuery", void 0);
17995
- __decorate([
19160
+ __decorate$1([
17996
19161
  Optional({ through: "ad4m://base_prefix" }),
17997
- __metadata("design:type", String)
19162
+ __metadata$1("design:type", String)
17998
19163
  ], exports.AutoProcessorConfig.prototype, "basePrefix", void 0);
17999
- __decorate([
19164
+ __decorate$1([
18000
19165
  HasMany({ through: "ad4m://interpretation_class", datatype: "xsd:string" }),
18001
- __metadata("design:type", Array)
19166
+ __metadata$1("design:type", Array)
18002
19167
  ], exports.AutoProcessorConfig.prototype, "interpretationClasses", void 0);
18003
- __decorate([
19168
+ __decorate$1([
18004
19169
  Property({ through: "ad4m://debounce_ms", required: true }),
18005
- __metadata("design:type", String)
19170
+ __metadata$1("design:type", String)
18006
19171
  ], exports.AutoProcessorConfig.prototype, "debounceMs", void 0);
18007
- __decorate([
19172
+ __decorate$1([
18008
19173
  Optional({ through: "ad4m://batch_min" }),
18009
- __metadata("design:type", String)
19174
+ __metadata$1("design:type", String)
18010
19175
  ], exports.AutoProcessorConfig.prototype, "batchMin", void 0);
18011
- __decorate([
19176
+ __decorate$1([
18012
19177
  Property({ through: "ad4m://batch_max", required: true }),
18013
- __metadata("design:type", String)
19178
+ __metadata$1("design:type", String)
18014
19179
  ], exports.AutoProcessorConfig.prototype, "batchMax", void 0);
18015
- __decorate([
19180
+ __decorate$1([
18016
19181
  Optional({ through: "ad4m://max_wait_ms" }),
18017
- __metadata("design:type", String)
19182
+ __metadata$1("design:type", String)
18018
19183
  ], exports.AutoProcessorConfig.prototype, "maxWaitMs", void 0);
18019
- __decorate([
19184
+ __decorate$1([
18020
19185
  Property({ through: "ad4m://claim_ttl_ms", required: true }),
18021
- __metadata("design:type", String)
19186
+ __metadata$1("design:type", String)
18022
19187
  ], exports.AutoProcessorConfig.prototype, "claimTtlMs", void 0);
18023
- __decorate([
19188
+ __decorate$1([
18024
19189
  Optional({ through: "ad4m://source_window_ms" }),
18025
- __metadata("design:type", String)
19190
+ __metadata$1("design:type", String)
18026
19191
  ], exports.AutoProcessorConfig.prototype, "sourceWindowMs", void 0);
18027
- __decorate([
19192
+ __decorate$1([
18028
19193
  Optional({ through: "ad4m://dedup_strategy" }),
18029
- __metadata("design:type", String)
19194
+ __metadata$1("design:type", String)
18030
19195
  ], exports.AutoProcessorConfig.prototype, "dedupStrategy", void 0);
18031
- __decorate([
19196
+ __decorate$1([
18032
19197
  Optional({ through: "ad4m://existing_scope" }),
18033
- __metadata("design:type", String)
19198
+ __metadata$1("design:type", String)
18034
19199
  ], exports.AutoProcessorConfig.prototype, "existingScope", void 0);
18035
- __decorate([
19200
+ __decorate$1([
18036
19201
  Optional({ through: "ad4m://mint_scope" }),
18037
- __metadata("design:type", String)
19202
+ __metadata$1("design:type", String)
18038
19203
  ], exports.AutoProcessorConfig.prototype, "mintScope", void 0);
18039
- __decorate([
18040
- Optional({ through: "ad4m://debug_mode", resolveLanguage: "literal" }),
18041
- __metadata("design:type", String)
18042
- ], exports.AutoProcessorConfig.prototype, "debugMode", void 0);
18043
- __decorate([
18044
- Optional({ through: "ad4m://persist_debug", resolveLanguage: "literal" }),
18045
- __metadata("design:type", String)
18046
- ], exports.AutoProcessorConfig.prototype, "persistDebug", void 0);
18047
- __decorate([
19204
+ __decorate$1([
19205
+ Optional({ through: "ad4m://max_tool_calls" }),
19206
+ __metadata$1("design:type", String)
19207
+ ], exports.AutoProcessorConfig.prototype, "maxToolCalls", void 0);
19208
+ __decorate$1([
18048
19209
  Optional({ through: "ad4m://emit_debug_events", resolveLanguage: "literal" }),
18049
- __metadata("design:type", String)
19210
+ __metadata$1("design:type", String)
18050
19211
  ], exports.AutoProcessorConfig.prototype, "emitDebugEvents", void 0);
18051
- exports.AutoProcessorConfig = __decorate([
19212
+ exports.AutoProcessorConfig = __decorate$1([
18052
19213
  Model$1({ name: "AutoProcessor" })
18053
19214
  ], exports.AutoProcessorConfig);
18054
19215
  // ── InterpretationRun ───────────────────────────────────────────────────────
@@ -18072,39 +19233,39 @@ exports.InterpretationRun = class InterpretationRun extends Ad4mModel {
18072
19233
  this.sources = [];
18073
19234
  }
18074
19235
  };
18075
- __decorate([
19236
+ __decorate$1([
18076
19237
  Property({ through: "ad4m://interp/run_id", required: true, identity: true }),
18077
- __metadata("design:type", String)
19238
+ __metadata$1("design:type", String)
18078
19239
  ], exports.InterpretationRun.prototype, "runId", void 0);
18079
- __decorate([
19240
+ __decorate$1([
18080
19241
  Optional({ through: "ad4m://interp/model" }),
18081
- __metadata("design:type", String)
19242
+ __metadata$1("design:type", String)
18082
19243
  ], exports.InterpretationRun.prototype, "model", void 0);
18083
- __decorate([
19244
+ __decorate$1([
18084
19245
  Optional({ through: "ad4m://interp/prompt_version" }),
18085
- __metadata("design:type", String)
19246
+ __metadata$1("design:type", String)
18086
19247
  ], exports.InterpretationRun.prototype, "promptVersion", void 0);
18087
- __decorate([
19248
+ __decorate$1([
18088
19249
  Optional({ through: "ad4m://interp/ran_at" }),
18089
- __metadata("design:type", String)
19250
+ __metadata$1("design:type", String)
18090
19251
  ], exports.InterpretationRun.prototype, "ranAt", void 0);
18091
- __decorate([
19252
+ __decorate$1([
18092
19253
  Optional({ through: "ad4m://interp/processor" }),
18093
- __metadata("design:type", String)
19254
+ __metadata$1("design:type", String)
18094
19255
  ], exports.InterpretationRun.prototype, "processor", void 0);
18095
- __decorate([
19256
+ __decorate$1([
18096
19257
  HasMany({ through: "ad4m://interp/sources", datatype: "xsd:string" }),
18097
- __metadata("design:type", Array)
19258
+ __metadata$1("design:type", Array)
18098
19259
  ], exports.InterpretationRun.prototype, "sources", void 0);
18099
- __decorate([
19260
+ __decorate$1([
18100
19261
  Optional({ through: "ad4m://interp/debug_prompt", resolveLanguage: "literal" }),
18101
- __metadata("design:type", String)
19262
+ __metadata$1("design:type", String)
18102
19263
  ], exports.InterpretationRun.prototype, "debugPrompt", void 0);
18103
- __decorate([
19264
+ __decorate$1([
18104
19265
  Optional({ through: "ad4m://interp/debug_response", resolveLanguage: "literal" }),
18105
- __metadata("design:type", String)
19266
+ __metadata$1("design:type", String)
18106
19267
  ], exports.InterpretationRun.prototype, "debugResponse", void 0);
18107
- exports.InterpretationRun = __decorate([
19268
+ exports.InterpretationRun = __decorate$1([
18108
19269
  Model$1({ name: "InterpretationRun" })
18109
19270
  ], exports.InterpretationRun);
18110
19271
  // ── InterpretationOverlay ───────────────────────────────────────────────────
@@ -18134,18 +19295,560 @@ exports.InterpretationOverlay = class InterpretationOverlay extends Ad4mModel {
18134
19295
  this.kind = "";
18135
19296
  }
18136
19297
  };
18137
- __decorate([
19298
+ __decorate$1([
18138
19299
  Property({ through: "ad4m://interp/kind", required: true }),
18139
- __metadata("design:type", String)
19300
+ __metadata$1("design:type", String)
18140
19301
  ], exports.InterpretationOverlay.prototype, "kind", void 0);
18141
- __decorate([
19302
+ __decorate$1([
18142
19303
  Optional({ through: "ad4m://interp/run" }),
18143
- __metadata("design:type", String)
19304
+ __metadata$1("design:type", String)
18144
19305
  ], exports.InterpretationOverlay.prototype, "run", void 0);
18145
- exports.InterpretationOverlay = __decorate([
19306
+ exports.InterpretationOverlay = __decorate$1([
18146
19307
  Model$1({ name: "InterpretationOverlay" })
18147
19308
  ], exports.InterpretationOverlay);
18148
19309
 
19310
+ /**
19311
+ * TypeScript @Model classes mirroring the Rust-side hardwired SDNA for the
19312
+ * flow runtime. Apps can import these to query the perspective graph for
19313
+ * pending flow-transition proposals without knowing the raw link predicates.
19314
+ *
19315
+ * Registration:
19316
+ * await FlowTransitionProposal.register(perspective);
19317
+ *
19318
+ * Querying:
19319
+ * const pending = await FlowTransitionProposal.findAll(perspective);
19320
+ *
19321
+ * Slice 5/7 of the flow-implementation arc (design doc §4.2). The Rust
19322
+ * engine does not yet mint these — that lands with the consensus firing
19323
+ * work in a later PR arc. This class defines the on-graph shape so:
19324
+ * - clients can build UI over proposals immediately (Deliberation demo);
19325
+ * - the SDNA-parity test locks TS/Rust drift the moment the JSON exists
19326
+ * (`rust-executor/src/perspectives/hardwired_sdna/flow_transition_proposal.json`);
19327
+ * - the engine can start writing into this shape when consensus lands
19328
+ * without touching the client-side surface.
19329
+ */
19330
+ var __decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
19331
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
19332
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
19333
+ 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;
19334
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
19335
+ };
19336
+ var __metadata = (undefined && undefined.__metadata) || function (k, v) {
19337
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
19338
+ };
19339
+ // ── FlowTransitionProposal ──────────────────────────────────────────────────
19340
+ // Mirrors the Rust hardwired `flow_transition_proposal.json` SDNA (once wired
19341
+ // on the engine side; see file header). One node per proposed transition; the
19342
+ // URI is `ad4m://flow/proposal/<uuid>` when the engine mints it, but the class
19343
+ // carries no URI-format constraint — apps constructing proposals directly may
19344
+ // choose any URI they can defend as unique.
19345
+ exports.FlowTransitionProposal = class FlowTransitionProposal extends Ad4mModel {
19346
+ constructor() {
19347
+ super(...arguments);
19348
+ /**
19349
+ * URI of the running `FlowInstance` this proposal targets. First-declared
19350
+ * property so `buildSHACL` derives the shape namespace from its `through`
19351
+ * prefix — `ad4m://flow/instance` → `ad4m://` → target_class
19352
+ * `ad4m://FlowTransitionProposal`. Also the identity predicate: the
19353
+ * discriminator `findAll` uses to isolate proposal nodes.
19354
+ */
19355
+ this.flowInstance = "";
19356
+ /** Name of the state the flow instance is currently in. */
19357
+ this.fromState = "";
19358
+ /** Name of the state the proposal wants to transition to. */
19359
+ this.toState = "";
19360
+ /** DID of the agent that issued the proposal. */
19361
+ this.proposer = "";
19362
+ /**
19363
+ * URIs of instances offered as evidence that `toState.requires` is now
19364
+ * satisfied. Multiple links, one per cited instance; ordering is not
19365
+ * significant.
19366
+ */
19367
+ this.evidence = [];
19368
+ /**
19369
+ * JSON blob: `{ [uri]: sha256_hex }` — one entry per evidence URI, hashing
19370
+ * the canonicalized graph-visible properties (sorted by property URI,
19371
+ * multi-values sorted lexicographically) at proposal time. Downstream
19372
+ * verifiers use it to detect edits to cited instances after the proposal
19373
+ * was written. Stored as an opaque string because SHACL properties carry
19374
+ * no rich-object type; the engine parses it back into a map.
19375
+ */
19376
+ this.evidenceHashes = "";
19377
+ // "When was this proposal written?" is answered by `Ad4mModel`'s built-in
19378
+ // `createdAt`, synthesized on hydration from the earliest link timestamp
19379
+ // of the proposal's own links (all written together during create_subject).
19380
+ }
19381
+ };
19382
+ __decorate([
19383
+ Property({ through: "ad4m://flow/instance", required: true, identity: true }),
19384
+ __metadata("design:type", String)
19385
+ ], exports.FlowTransitionProposal.prototype, "flowInstance", void 0);
19386
+ __decorate([
19387
+ Property({ through: "ad4m://flow/from_state", required: true }),
19388
+ __metadata("design:type", String)
19389
+ ], exports.FlowTransitionProposal.prototype, "fromState", void 0);
19390
+ __decorate([
19391
+ Property({ through: "ad4m://flow/to_state", required: true }),
19392
+ __metadata("design:type", String)
19393
+ ], exports.FlowTransitionProposal.prototype, "toState", void 0);
19394
+ __decorate([
19395
+ Property({ through: "ad4m://flow/proposer", required: true }),
19396
+ __metadata("design:type", String)
19397
+ ], exports.FlowTransitionProposal.prototype, "proposer", void 0);
19398
+ __decorate([
19399
+ HasMany({ through: "ad4m://flow/evidence", datatype: "xsd:string" }),
19400
+ __metadata("design:type", Array)
19401
+ ], exports.FlowTransitionProposal.prototype, "evidence", void 0);
19402
+ __decorate([
19403
+ Property({ through: "ad4m://flow/evidence_hashes", required: true }),
19404
+ __metadata("design:type", String)
19405
+ ], exports.FlowTransitionProposal.prototype, "evidenceHashes", void 0);
19406
+ __decorate([
19407
+ Optional({ through: "ad4m://flow/run_uri" }),
19408
+ __metadata("design:type", String)
19409
+ ], exports.FlowTransitionProposal.prototype, "runUri", void 0);
19410
+ __decorate([
19411
+ Optional({ through: "ad4m://flow/rationale" }),
19412
+ __metadata("design:type", String)
19413
+ ], exports.FlowTransitionProposal.prototype, "rationale", void 0);
19414
+ exports.FlowTransitionProposal = __decorate([
19415
+ Model$1({ name: "FlowTransitionProposal" })
19416
+ ], exports.FlowTransitionProposal);
19417
+ // ── FlowInstanceRecord ──────────────────────────────────────────────────────
19418
+ // On-graph node minted by the engine when a flow is started on a specific
19419
+ // base expression. Its URI is the value that `FlowTransitionProposal.flowInstance`
19420
+ // references. Mirrors `rust-executor/src/perspectives/hardwired_sdna/flow_instance.json`.
19421
+ //
19422
+ // Design authority: `docs/flow-interpretation-hints-design.md` §4.3.
19423
+ //
19424
+ // This class is the raw on-graph record (@Model over the SDNA shape). The
19425
+ // object-oriented handle callers work with is `FlowInstance` in
19426
+ // `./FlowInstance.ts` — it wraps `FlowInstanceRecord + SHACLFlow definition`
19427
+ // and exposes `currentState`, `availableTransitions`, `proposals`, etc.
19428
+ // Renamed from `FlowInstance` → `FlowInstanceRecord` on 2026-08-27 per
19429
+ // Nico's PR #929 review R2 (the `FlowInstance` name is reserved for the
19430
+ // wrapper the design has always specified in §4.3).
19431
+ //
19432
+ // The SDNA name (`@Model({ name: "FlowInstance" })`) stays unchanged — that
19433
+ // keys the on-graph class, not the TS export. Renaming the TS class only
19434
+ // changes the JS import surface; the graph shape is identical, and Rust
19435
+ // hardwired_sdna/flow_instance.json + all the parity tests still lock down
19436
+ // the same `ad4m://FlowInstance` target class.
19437
+ exports.FlowInstanceRecord = class FlowInstanceRecord extends Ad4mModel {
19438
+ constructor() {
19439
+ super(...arguments);
19440
+ /**
19441
+ * URI of the `SHACLFlow` this instance runs — the flow's canonical
19442
+ * identity, collision-free across social-DNA modules from different
19443
+ * communities (bare names WILL collide once shared flows are adopted
19444
+ * cross-team — James PR #929 R5). Sourced from `SHACLFlow.flowUri`
19445
+ * (which is `${namespace}${name}Flow`, e.g. `coasys://DeliveryFlow`).
19446
+ *
19447
+ * First-declared property so `buildSHACL` derives the shape namespace
19448
+ * from its `through` prefix — `ad4m://flow/flow_uri` → `ad4m://` →
19449
+ * target_class `ad4m://FlowInstance`. Also the discriminator predicate
19450
+ * `findAll` uses to isolate instance nodes.
19451
+ *
19452
+ * The human-readable flow name is still available on the paired
19453
+ * `SHACLFlow` (via `perspective.getFlow(record.flowUri.split('/').pop()!.replace(/Flow$/,''))`,
19454
+ * or more commonly via the `FlowInstance` wrapper's `flowName` getter).
19455
+ */
19456
+ this.flowUri = "";
19457
+ /**
19458
+ * URI of the subject expression this flow runs on.
19459
+ * Named `subject` (not `baseExpression`) because `Ad4mModel` reserves
19460
+ * `baseExpression` as a synthetic hydration field always set to the
19461
+ * instance's own URI — a subclass property with that name is shadowed
19462
+ * on read.
19463
+ */
19464
+ this.subject = "";
19465
+ /**
19466
+ * The state name this replica's executor last derived for the flow — a
19467
+ * per-replica cache written as a `local` link, never the authority (the
19468
+ * fold over the signed proposals is). Optional on the shape: a row that
19469
+ * synced in from a peer carries no value until the local consensus pass
19470
+ * has run, so an empty string means "not yet derived here".
19471
+ */
19472
+ this.currentState = "";
19473
+ // "When was this flow started?" is answered by `Ad4mModel`'s built-in
19474
+ // `createdAt`, synthesized on hydration from the earliest link timestamp
19475
+ // of the instance's own links (all written together during `mint_flow_instance`).
19476
+ }
19477
+ };
19478
+ __decorate([
19479
+ Property({ through: "ad4m://flow/flow_uri", required: true, identity: true }),
19480
+ __metadata("design:type", String)
19481
+ ], exports.FlowInstanceRecord.prototype, "flowUri", void 0);
19482
+ __decorate([
19483
+ Property({ through: "ad4m://flow/base", required: true }),
19484
+ __metadata("design:type", String)
19485
+ ], exports.FlowInstanceRecord.prototype, "subject", void 0);
19486
+ __decorate([
19487
+ Property({ through: "ad4m://flow/current_state", local: true }),
19488
+ __metadata("design:type", String)
19489
+ ], exports.FlowInstanceRecord.prototype, "currentState", void 0);
19490
+ exports.FlowInstanceRecord = __decorate([
19491
+ Model$1({ name: "FlowInstance" })
19492
+ ], exports.FlowInstanceRecord);
19493
+
19494
+ /**
19495
+ * `FlowInstance` — object-oriented wrapper for a running flow.
19496
+ *
19497
+ * Design authority: `docs/flow-interpretation-hints-design.md` §4.3.
19498
+ *
19499
+ * Wraps two on-graph objects:
19500
+ *
19501
+ * - `FlowInstanceRecord` — the raw @Model row minted by
19502
+ * {@link FlowInstance.start}; carries `flow`, `subject`, `currentState`,
19503
+ * and Ad4mModel's synthesised `createdAt`.
19504
+ * - `SHACLFlow` — the flow definition the record is bound to. Held so
19505
+ * `availableTransitions` / `currentState` object lookups don't require
19506
+ * a per-call round-trip.
19507
+ *
19508
+ * Construct via the class factories — {@link FlowInstance.start} for the
19509
+ * mint path and {@link FlowInstance.findAll} for the read path — rather
19510
+ * than the `wrap` escape hatch, which exists for tests that already own
19511
+ * a matched (record, shape) pair.
19512
+ *
19513
+ * # What's here, and what is still absent
19514
+ *
19515
+ * Read surface (implemented today, PR #929):
19516
+ * - `uri`, `subject`, `flowName`, `currentStateName`, `startedAtMillis`
19517
+ * accessors.
19518
+ * - `currentState` — resolves the `FlowState` on the shape whose name
19519
+ * matches `record.currentState`.
19520
+ * - `availableTransitions` — filters `shape.transitions` by `fromState`.
19521
+ * - `proposals()` — queries `FlowTransitionProposal` records that
19522
+ * target this instance's URI.
19523
+ *
19524
+ * - `acceptProposal()` / `rejectProposal()` — the consensus write API:
19525
+ * accept counts your DID toward the flow's consensusRule and fires the
19526
+ * transition at quorum; reject withdraws only the links you signed and
19527
+ * resolves to how many went. Reject is not a cancel — another agent's
19528
+ * proposal is theirs, and because state is recomputed from the links
19529
+ * present now, withdrawing a vote that had settled an edge moves the
19530
+ * flow back to where it stood before it.
19531
+ *
19532
+ * Still absent (rather than shipped as `throw new Error("not yet")`
19533
+ * stubs): `proposeTransition`, `fireAction`, and the subscriptions
19534
+ * (`onStateChange`, `onProposalAdded`, `onProposalResolved`) — they land
19535
+ * with the manual-proposal and subscription-topic slices.
19536
+ */
19537
+ /**
19538
+ * Extract the flow's human-readable name from its canonical URI.
19539
+ *
19540
+ * `SHACLFlow.flowUri` is `${namespace}${name}Flow` (e.g.
19541
+ * `coasys://DeliveryFlow`). This function strips the `Flow` suffix and
19542
+ * everything before the last URI-segment separator (`/` or `#`), leaving
19543
+ * the bare name. Returns `undefined` for URIs that don't match the
19544
+ * `…{name}Flow` shape — a stale FlowInstanceRecord whose flow URI came
19545
+ * from an older writer, for instance.
19546
+ */
19547
+ function flowNameFromUri(flowUri) {
19548
+ if (!flowUri.endsWith("Flow"))
19549
+ return undefined;
19550
+ const withoutSuffix = flowUri.slice(0, -"Flow".length);
19551
+ const sepIdx = Math.max(withoutSuffix.lastIndexOf("/"), withoutSuffix.lastIndexOf("#"));
19552
+ if (sepIdx < 0)
19553
+ return withoutSuffix || undefined;
19554
+ const name = withoutSuffix.slice(sepIdx + 1);
19555
+ return name || undefined;
19556
+ }
19557
+ class FlowInstance {
19558
+ /**
19559
+ * Private constructor — construct via {@link FlowInstance.start} or
19560
+ * {@link FlowInstance.findAll}. {@link FlowInstance.wrap} is the
19561
+ * escape hatch for tests / direct construction cases.
19562
+ */
19563
+ constructor(perspective,
19564
+ /** The flow definition this instance was minted against. */
19565
+ shape,
19566
+ /**
19567
+ * The on-graph record — carries `flow`, `subject`, `currentState`
19568
+ * and Ad4mModel's synthesised `createdAt`. Callers can reach into it
19569
+ * for anything the wrapper doesn't expose directly, but should prefer
19570
+ * the wrapper accessors so future refactors of the underlying shape
19571
+ * don't ripple through their code.
19572
+ */
19573
+ record) {
19574
+ this.perspective = perspective;
19575
+ this.shape = shape;
19576
+ this.record = record;
19577
+ }
19578
+ /**
19579
+ * Escape hatch used by {@link FlowInstance.start} and
19580
+ * {@link FlowInstance.findAll} — not meant for general use, but public
19581
+ * so tests that already own a `FlowInstanceRecord + SHACLFlow` pair
19582
+ * (e.g. from pre-populated fixtures) can build a wrapper without
19583
+ * going through the mint path.
19584
+ */
19585
+ static wrap(perspective, shape, record) {
19586
+ return new FlowInstance(perspective, shape, record);
19587
+ }
19588
+ /**
19589
+ * Mint a new `FlowInstance` on the given perspective (design doc §4.3).
19590
+ *
19591
+ * Idempotently registers the hardwired `FlowInstanceRecord` +
19592
+ * `FlowTransitionProposal` @Model classes on first call — the on-graph
19593
+ * shape matches the Rust-side hardwired SDNA (parity-locked in
19594
+ * `flow-instance.test.ts` / `flow-transition-proposal.test.ts`).
19595
+ *
19596
+ * The returned wrapper carries the parsed `SHACLFlow` alongside the
19597
+ * on-graph record, so `currentState` / `availableTransitions` /
19598
+ * `proposals` accessors work without further round-trips.
19599
+ *
19600
+ * The record's `currentState` is a per-replica cache the consensus engine
19601
+ * writes as a local link. It is read back only for display — the cache-first
19602
+ * path in `gather_active_flow_contexts` fills the state rendered into LLM
19603
+ * context — and **never as authority**: anything that decides something
19604
+ * (the fold, the mint pass) derives state from the signed links present now
19605
+ * and does not consult the cache. Treat it as a display hint, not as the
19606
+ * flow's state.
19607
+ *
19608
+ * @param perspective - The perspective the flow instance lives on
19609
+ * @param flowName - Name of a `SHACLFlow` already registered on the perspective
19610
+ * @param baseExpression - URI of the subject expression the flow runs on
19611
+ * @throws When the flow is unknown or has zero declared states (zero-state
19612
+ * flows fire via the forthcoming atomic-action path, §6.3).
19613
+ */
19614
+ static async start(perspective, flowName, baseExpression) {
19615
+ const flow = await perspective.getFlow(flowName);
19616
+ if (!flow)
19617
+ throw `Flow "${flowName}" not found`;
19618
+ if (flow.states.length === 0) {
19619
+ 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)`;
19620
+ }
19621
+ // Register the hardwired runtime classes if this is the first flow
19622
+ // instance on the perspective. registerAll is a single batched RPC and
19623
+ // no-ops when both classes are already present.
19624
+ await Ad4mModel.registerAll(perspective, [exports.FlowInstanceRecord, exports.FlowTransitionProposal]);
19625
+ // Property keys must be the FlowInstanceRecord @Model field names —
19626
+ // `subject` (not `baseExpression`, which collides with Ad4mModel's
19627
+ // synthetic hydration field and would be silently shadowed on read).
19628
+ // No explicit start-time field: Ad4mModel synthesises `createdAt` on
19629
+ // hydration from the earliest link timestamp on the instance's URI.
19630
+ // Convention: `SHACLFlow.states` is stored sorted ascending by `value`
19631
+ // (enforced by `fromLinks`), so `states[0]` is the initial state. A
19632
+ // flow author who wants a specific state as the entry point must give
19633
+ // it the lowest `value` in the set.
19634
+ //
19635
+ // Store the flow's URI, not the bare name — see FlowInstanceRecord's
19636
+ // docstring for the collision-across-modules argument (James PR #929 R5).
19637
+ const record = await exports.FlowInstanceRecord.create(perspective, {
19638
+ flowUri: flow.flowUri,
19639
+ subject: baseExpression,
19640
+ currentState: flow.states[0].name,
19641
+ });
19642
+ return FlowInstance.wrap(perspective, flow, record);
19643
+ }
19644
+ /**
19645
+ * Return every live `FlowInstance` on the perspective (design doc §4.3).
19646
+ *
19647
+ * Read-only path: never registers classes. On a perspective that has
19648
+ * never minted a flow instance, the `FlowInstanceRecord` SHACL shape
19649
+ * isn't installed yet — this returns `[]` in that case rather than
19650
+ * mutating the perspective. Registration is the responsibility of
19651
+ * {@link FlowInstance.start}, which is the write path. (Registering on
19652
+ * a read would sync a write to every peer in the neighbourhood —
19653
+ * exactly what a query must not do — James PR #929 R7.)
19654
+ *
19655
+ * Filter surface (all optional, all combinable):
19656
+ * - **`flowName`** — narrows by flow-name discriminator (e.g. "Delivery")
19657
+ * - **`subject`** — narrows by base-expression URI, i.e. "give me every
19658
+ * flow running on THIS expression"
19659
+ *
19660
+ * Both filters translate to a single SHACL `where`-filter round-trip
19661
+ * (no client-side filtering); combining them AND-joins server-side.
19662
+ * The string-arg shape (`FlowInstance.findAll(p, "Delivery")`) is
19663
+ * shorthand for `{ flowName: "Delivery" }`.
19664
+ *
19665
+ * Records whose `flow` value has no matching `SHACLFlow` on the
19666
+ * perspective (e.g. the flow was unregistered) are silently skipped —
19667
+ * the wrapper can't answer `currentState` / `availableTransitions`
19668
+ * without the shape, and callers routinely iterate the returned array
19669
+ * without null-checks.
19670
+ *
19671
+ * @example
19672
+ * ```typescript
19673
+ * const all = await FlowInstance.findAll(perspective);
19674
+ * const deliveries = await FlowInstance.findAll(perspective, "Delivery");
19675
+ * const onThisTask = await FlowInstance.findAll(perspective, {
19676
+ * subject: "ad4m://task/1",
19677
+ * });
19678
+ * const deliveriesOnTask = await FlowInstance.findAll(perspective, {
19679
+ * flowName: "Delivery",
19680
+ * subject: "ad4m://task/1",
19681
+ * });
19682
+ * ```
19683
+ */
19684
+ static async findAll(perspective, filter) {
19685
+ const { flowName, subject } = typeof filter === "string"
19686
+ ? { flowName: filter, subject: undefined }
19687
+ : { flowName: filter?.flowName, subject: filter?.subject };
19688
+ // Filter surface accepts a flow *name* for ergonomics — resolve it to
19689
+ // the canonical URI before the SHACL query, since the record stores
19690
+ // the URI (James PR #929 R5). Unknown name → no matches (short-circuit
19691
+ // with an empty result rather than issuing a bare-name query that
19692
+ // would silently return nothing anyway).
19693
+ const where = {};
19694
+ if (flowName !== undefined) {
19695
+ const flow = await perspective.getFlow(flowName);
19696
+ if (!flow)
19697
+ return [];
19698
+ where.flowUri = flow.flowUri;
19699
+ }
19700
+ if (subject !== undefined)
19701
+ where.subject = subject;
19702
+ // "Shape not found" on a perspective that has never minted a flow
19703
+ // instance is a no-op read, not an error — the executor throws for a
19704
+ // missing SHACL shape and there is no side-effect-free way to ask
19705
+ // "does this class exist". Return `[]` on that specific case; rethrow
19706
+ // anything else so real infra failures don't get swallowed.
19707
+ //
19708
+ // Regex covers every message the executor + client stack raises for
19709
+ // an unregistered class:
19710
+ // "No SHACL shape stored for class 'FlowInstance'." (executor RPC)
19711
+ // "Shape not found" (older Rust path)
19712
+ // "class not registered" / "not registered" (TS Ad4mModel guard)
19713
+ let records;
19714
+ try {
19715
+ records =
19716
+ Object.keys(where).length > 0
19717
+ ? await exports.FlowInstanceRecord.findAll(perspective, { where })
19718
+ : await exports.FlowInstanceRecord.findAll(perspective);
19719
+ }
19720
+ catch (e) {
19721
+ const msg = e instanceof Error ? e.message : String(e);
19722
+ if (/no shacl shape stored|shape not found|class not registered|not registered/i.test(msg)) {
19723
+ return [];
19724
+ }
19725
+ throw e;
19726
+ }
19727
+ // Pair each record with its parsed SHACLFlow. Cache lookups by
19728
+ // flow-URI so `getFlow` fires at most once per distinct flow —
19729
+ // matters when a perspective has hundreds of instances against
19730
+ // one shape.
19731
+ //
19732
+ // The URI stored on the record is `${namespace}${name}Flow`
19733
+ // (see SHACLFlow.flowUri) — recovering the name for `getFlow`
19734
+ // means stripping the namespace + the `Flow` suffix. Records that
19735
+ // don't parse this way are treated as stale and skipped.
19736
+ const shapesByUri = new Map();
19737
+ const wrappers = [];
19738
+ for (const record of records) {
19739
+ let shape = shapesByUri.get(record.flowUri);
19740
+ if (!shape) {
19741
+ const name = flowNameFromUri(record.flowUri);
19742
+ if (!name)
19743
+ continue;
19744
+ const loaded = await perspective.getFlow(name);
19745
+ if (!loaded || loaded.flowUri !== record.flowUri) {
19746
+ // Stale record — the flow it references was unregistered,
19747
+ // or a different flow now owns that name.
19748
+ continue;
19749
+ }
19750
+ shape = loaded;
19751
+ shapesByUri.set(record.flowUri, shape);
19752
+ }
19753
+ wrappers.push(FlowInstance.wrap(perspective, shape, record));
19754
+ }
19755
+ return wrappers;
19756
+ }
19757
+ // ── Read accessors ────────────────────────────────────────────────────
19758
+ /**
19759
+ * URI of the on-graph `FlowInstance` node — `ad4m://flow/instance/{id}`.
19760
+ *
19761
+ * Sourced from `Ad4mModel`'s synthesised `baseExpression`, which for
19762
+ * `FlowInstanceRecord` *is* the instance's own URI (the value
19763
+ * `FlowTransitionProposal.flowInstance` references).
19764
+ */
19765
+ get uri() {
19766
+ return this.record.id;
19767
+ }
19768
+ /**
19769
+ * URI of the base expression this flow runs on — matches the
19770
+ * `SHACLFlow.inputTypes` that {@link PerspectiveProxy.availableFlows}
19771
+ * would greenlight for this expression.
19772
+ */
19773
+ get subject() {
19774
+ return this.record.subject;
19775
+ }
19776
+ /**
19777
+ * Human-readable flow name — the display label. Sourced from the paired
19778
+ * `SHACLFlow.name`, not from the record (which stores the URI as its
19779
+ * canonical identity — see FlowInstanceRecord's docstring for why).
19780
+ */
19781
+ get flowName() {
19782
+ return this.shape.name;
19783
+ }
19784
+ /** Flow URI — the on-graph discriminator, collision-free across modules. */
19785
+ get flowUri() {
19786
+ return this.record.flowUri;
19787
+ }
19788
+ /** Name of the state this instance is currently in. */
19789
+ get currentStateName() {
19790
+ return this.record.currentState;
19791
+ }
19792
+ /**
19793
+ * ISO-8601 (epoch millis after Ad4mModel hydration) start time.
19794
+ * Returns `undefined` when hydration didn't produce a `createdAt`
19795
+ * — rare, but not fatal.
19796
+ */
19797
+ get startedAtMillis() {
19798
+ const v = this.record.createdAt;
19799
+ return typeof v === "number" ? v : undefined;
19800
+ }
19801
+ /**
19802
+ * The `FlowState` object on the shape matching `currentStateName`.
19803
+ * Throws when the record's state name is not declared on the flow —
19804
+ * that's a "stale FlowInstance whose flow was edited under it" bug,
19805
+ * not a silent-fail case.
19806
+ */
19807
+ get currentState() {
19808
+ const s = this.shape.states.find((x) => x.name === this.currentStateName);
19809
+ if (!s) {
19810
+ throw new Error(`FlowInstance ${this.uri}: currentState "${this.currentStateName}" is not declared on flow "${this.flowName}". ` +
19811
+ `Known states: ${this.shape.states.map((x) => x.name).join(", ") || "(none)"}`);
19812
+ }
19813
+ return s;
19814
+ }
19815
+ /**
19816
+ * Every `FlowTransition` on the shape whose `fromState` matches
19817
+ * `currentStateName`. Order preserved from the shape.
19818
+ *
19819
+ * Empty when the current state is terminal (no outgoing transitions).
19820
+ */
19821
+ get availableTransitions() {
19822
+ return this.shape.transitions.filter((t) => t.fromState === this.currentStateName);
19823
+ }
19824
+ /**
19825
+ * All `FlowTransitionProposal` records targeting this instance's URI.
19826
+ *
19827
+ * Uses the SDNA identity discriminator (`ad4m://flow/instance` predicate)
19828
+ * for the where-filter — one SPARQL round-trip, no client-side
19829
+ * filtering.
19830
+ *
19831
+ * These are written by the executor's consensus pass when it mints a
19832
+ * transition, and by clients proposing directly. Superseded proposals are
19833
+ * not swept here — a stale one is simply never counted by the fold, and
19834
+ * accepting it fails with a stale-state error.
19835
+ */
19836
+ async proposals() {
19837
+ return exports.FlowTransitionProposal.findAll(this.perspective, {
19838
+ where: { flowInstance: this.uri },
19839
+ });
19840
+ }
19841
+ async acceptProposal(proposal) {
19842
+ const uri = typeof proposal === "string" ? proposal : proposal.id;
19843
+ return this.perspective.acceptFlowProposal(uri);
19844
+ }
19845
+ /** Withdraw our own links from a proposal; resolves to how many went. */
19846
+ async rejectProposal(proposal) {
19847
+ const uri = typeof proposal === "string" ? proposal : proposal.id;
19848
+ return this.perspective.rejectFlowProposal(uri);
19849
+ }
19850
+ }
19851
+
18149
19852
  /**
18150
19853
  * SPARQL binding helpers — typed shapes and parsers for `querySparql<T>()`.
18151
19854
  *
@@ -18265,15 +19968,73 @@ function parseLitBoolean(val) {
18265
19968
  /**
18266
19969
  * WakerSubscriptionManager — manages live query subscriptions for the waker.
18267
19970
  *
18268
- * Lives in core so it can be imported by both the plugin and integration tests
18269
- * without ESM/CJS import issues.
19971
+ * This is the single implementation: it is exported from `@coasys/ad4m` and
19972
+ * used by the integration tests, and the OpenClaw AD4M plugin re-exports this
19973
+ * module (`plugins/ad4m/wakerSubscriptionManager.ts`) rather than carrying its
19974
+ * own copy. Any behaviour change belongs here.
19975
+ */
19976
+ /**
19977
+ * Add a short cause hint to known subscription failures.
19978
+ * The executor needs its main key to register a live query; on a restarted
19979
+ * executor whose wallet was never unlocked this surfaces as a bare 403.
19980
+ */
19981
+ function hintFor(msg) {
19982
+ // "Executor is locked" is the current executor's message; "main key not
19983
+ // found" is what older executors (and unrelated key lookups) say for the
19984
+ // same locked state. Either way the caller cannot fix it themselves: keys
19985
+ // live in memory only, so every restart locks the node again and only its
19986
+ // operator can unlock it.
19987
+ if (/executor is locked/i.test(msg) || /main key not found/i.test(msg)) {
19988
+ return " — the executor is locked (its keys live in memory only, so every restart locks it again). Only the node's operator can unlock it: contact them and ask for unlockAgent, then subscribe again — a pending subscription re-attempts on its own once the node is unlocked";
19989
+ }
19990
+ if (/timed out after \d+ms/i.test(msg)) {
19991
+ return " — the executor accepted the waker's connection but never answered; check that the waker is pointed at the right executor host and API port (executorUrl in the plugin config) and that the node is unlocked";
19992
+ }
19993
+ return "";
19994
+ }
19995
+ /**
19996
+ * Reject `promise` after `ms` instead of waiting forever.
18270
19997
  *
18271
- * NOTE: keep in sync with plugins/ad4m/wakerSubscriptionManager.ts
19998
+ * The pending set only catches rejections. A handshake that hangs — the
19999
+ * executor accepted the socket but never answers — settles nothing, so the
20000
+ * subscription was recorded nowhere and the caller's tool invocation died at
20001
+ * the harness timeout instead (#1016). The underlying promise is left as is:
20002
+ * the caller disposes the proxy, so a late answer backs out on its own.
18272
20003
  */
20004
+ async function withTimeout(promise, ms, message) {
20005
+ let timer;
20006
+ try {
20007
+ return await Promise.race([
20008
+ promise,
20009
+ new Promise((_resolve, reject) => {
20010
+ timer = setTimeout(() => reject(new Error(message)), ms);
20011
+ }),
20012
+ ]);
20013
+ }
20014
+ finally {
20015
+ if (timer)
20016
+ clearTimeout(timer);
20017
+ }
20018
+ }
18273
20019
  class WakerSubscriptionManager {
18274
20020
  constructor(options) {
18275
20021
  this.proxies = new Map();
18276
20022
  this.activeSubscriptions = new Map();
20023
+ /** Subscriptions the executor rejected, waiting to be re-attempted. */
20024
+ this.pendingSubscriptions = new Map();
20025
+ this.retryTimer = null;
20026
+ /**
20027
+ * Cancellation tokens for in-flight `subscribe()` calls.
20028
+ *
20029
+ * `subscribe()` awaits `proxy.subscribe()` and `proxy.initialized`; a
20030
+ * `dispose()` / `disposeAll()` landing during either await used to leave a
20031
+ * live subscription behind, because nothing stopped the resumed call from
20032
+ * registering the proxy in `proxies` / `activeSubscriptions` afterwards.
20033
+ * `epoch` is bumped by `disposeAll()` (which cannot enumerate in-flight
20034
+ * ids), `generations` per id by `dispose()` and by each new `subscribe()`.
20035
+ */
20036
+ this.epoch = 0;
20037
+ this.generations = new Map();
18277
20038
  this.debounceTimers = new Map();
18278
20039
  /** Per-subscription set of already-processed message addresses (for mention subs)
18279
20040
  * or serialized result hash (for channel-messages subs). */
@@ -18285,6 +20046,18 @@ class WakerSubscriptionManager {
18285
20046
  this.onPersist = options.onPersist;
18286
20047
  this.QuerySubscriptionProxyCtor = options.QuerySubscriptionProxy ?? null;
18287
20048
  this.previousSeenMessages = options.previousSeenMessages ?? {};
20049
+ this.retryPendingMs = options.retryPendingMs ?? 30000;
20050
+ this.subscribeTimeoutMs = options.subscribeTimeoutMs ?? 15000;
20051
+ }
20052
+ /** A token identifying this attempt at subscribing `id`. */
20053
+ beginAttempt(id) {
20054
+ const gen = (this.generations.get(id) ?? 0) + 1;
20055
+ this.generations.set(id, gen);
20056
+ return { epoch: this.epoch, gen };
20057
+ }
20058
+ /** Whether this attempt has been superseded by a dispose or a newer one. */
20059
+ isStale(id, token) {
20060
+ return token.epoch !== this.epoch || this.generations.get(id) !== token.gen;
18288
20061
  }
18289
20062
  /**
18290
20063
  * Create a live SPARQL subscription.
@@ -18293,6 +20066,7 @@ class WakerSubscriptionManager {
18293
20066
  async subscribe(sub) {
18294
20067
  // Dispose existing subscription with same id if any
18295
20068
  this.dispose(sub.id, false);
20069
+ const token = this.beginAttempt(sub.id);
18296
20070
  if (!this.QuerySubscriptionProxyCtor) {
18297
20071
  throw new Error("WakerSubscriptionManager: QuerySubscriptionProxy must be provided via constructor options");
18298
20072
  }
@@ -18307,9 +20081,24 @@ class WakerSubscriptionManager {
18307
20081
  if (proxy.initialized && typeof proxy.initialized.catch === "function") {
18308
20082
  proxy.initialized.catch(() => { });
18309
20083
  }
20084
+ // One deadline for the whole handshake: `proxy.subscribe()` and the
20085
+ // `initialized` promise it resolves share the budget, so a hang in either
20086
+ // surfaces as the same loud-but-recoverable failure a rejection does.
20087
+ const budgetMs = this.subscribeTimeoutMs;
20088
+ const startedAt = Date.now();
20089
+ const bounded = (step, what) => budgetMs > 0
20090
+ ? withTimeout(step, Math.max(0, budgetMs - (Date.now() - startedAt)), `${what} timed out after ${budgetMs}ms`)
20091
+ : step;
18310
20092
  try {
18311
- await proxy.subscribe();
18312
- await proxy.initialized;
20093
+ await bounded(proxy.subscribe(), "subscribe handshake");
20094
+ if (this.isStale(sub.id, token)) {
20095
+ try {
20096
+ proxy.dispose();
20097
+ }
20098
+ catch { }
20099
+ return;
20100
+ }
20101
+ await bounded(proxy.initialized, "subscription initialization");
18313
20102
  }
18314
20103
  catch (err) {
18315
20104
  const msg = err?.message ?? String(err);
@@ -18318,12 +20107,36 @@ class WakerSubscriptionManager {
18318
20107
  proxy.dispose();
18319
20108
  }
18320
20109
  catch { }
18321
- // Remove from active state so it doesn't get persisted/retried
20110
+ // A dispose that landed mid-attempt wins: don't re-queue something the
20111
+ // caller has since asked us to forget.
20112
+ if (this.isStale(sub.id, token))
20113
+ return;
20114
+ // Remove from active state — it is not listening, so it must not be
20115
+ // reported as active or persisted as if it were.
18322
20116
  this.activeSubscriptions.delete(sub.id);
18323
20117
  this.seenMessages.delete(sub.id);
18324
20118
  this.persist();
18325
- return; // Don't throw — caller should not crash
20119
+ // Keep it pending and re-attempt: the usual cause (locked wallet, executor
20120
+ // mid-restart, a handshake the executor never answered) clears on its
20121
+ // own, and the caller asked to be enrolled.
20122
+ this.pendingSubscriptions.set(sub.id, sub);
20123
+ this.scheduleRetry();
20124
+ // Throw so callers can report the real outcome. Background callers
20125
+ // (auto-subscribe, restore-on-start) catch and log; the subscribe tools
20126
+ // turn this into an error result instead of a false "Subscribed" reply.
20127
+ throw new Error(`Waker subscription ${sub.id} failed: ${msg}${hintFor(msg)}` +
20128
+ (this.retryPendingMs > 0
20129
+ ? `. Not listening yet — re-attempting every ${Math.round(this.retryPendingMs / 1000)}s; check ad4m_list_waker_subscriptions.`
20130
+ : ""));
20131
+ }
20132
+ if (this.isStale(sub.id, token)) {
20133
+ try {
20134
+ proxy.dispose();
20135
+ }
20136
+ catch { }
20137
+ return;
18326
20138
  }
20139
+ this.pendingSubscriptions.delete(sub.id);
18327
20140
  this.logger.info(`[waker] ${sub.id}: subscription initialized successfully`);
18328
20141
  // Seed from persisted seen messages so we don't re-wake after restart
18329
20142
  const seen = new Set(this.previousSeenMessages[sub.id] ?? []);
@@ -18404,16 +20217,72 @@ class WakerSubscriptionManager {
18404
20217
  }, this.debounceMs));
18405
20218
  }
18406
20219
  });
20220
+ if (this.isStale(sub.id, token)) {
20221
+ try {
20222
+ proxy.dispose();
20223
+ }
20224
+ catch { }
20225
+ return;
20226
+ }
18407
20227
  this.proxies.set(sub.id, proxy);
18408
20228
  this.activeSubscriptions.set(sub.id, sub);
18409
20229
  this.persist();
18410
20230
  this.logger.info(`[waker] Subscription ${sub.id} active (type=${sub.type}, perspective=${sub.perspective})`);
18411
20231
  }
20232
+ /** Arm the re-attempt timer if pending subscriptions are waiting. */
20233
+ scheduleRetry() {
20234
+ if (this.retryPendingMs <= 0)
20235
+ return;
20236
+ if (this.retryTimer || this.pendingSubscriptions.size === 0)
20237
+ return;
20238
+ this.retryTimer = setTimeout(() => {
20239
+ this.retryTimer = null;
20240
+ void this.retryPending();
20241
+ }, this.retryPendingMs);
20242
+ if (typeof this.retryTimer.unref === "function")
20243
+ this.retryTimer.unref();
20244
+ }
20245
+ /**
20246
+ * Re-attempt every subscription the executor rejected.
20247
+ * Each attempt that fails puts itself back into the pending set and re-arms
20248
+ * the timer, so an agent that asked to be subscribed ends up enrolled once
20249
+ * the executor can accept the query.
20250
+ */
20251
+ async retryPending() {
20252
+ const waiting = Array.from(this.pendingSubscriptions.values());
20253
+ if (waiting.length === 0)
20254
+ return;
20255
+ this.logger.info(`[waker] re-attempting ${waiting.length} pending subscription(s)`);
20256
+ const epoch = this.epoch;
20257
+ for (const sub of waiting) {
20258
+ // A disposeAll() between two awaits must stop the whole sweep, and a
20259
+ // dispose() of this id must skip just it.
20260
+ if (epoch !== this.epoch)
20261
+ return;
20262
+ if (!this.pendingSubscriptions.has(sub.id))
20263
+ continue;
20264
+ this.pendingSubscriptions.delete(sub.id);
20265
+ try {
20266
+ await this.subscribe(sub);
20267
+ this.logger.info(`[waker] ${sub.id}: enrolled on re-attempt`);
20268
+ }
20269
+ catch (err) {
20270
+ // subscribe() already logged, re-queued and re-armed the timer.
20271
+ this.logger.debug(`[waker] ${sub.id}: still pending — ${err?.message ?? err}`);
20272
+ }
20273
+ }
20274
+ }
20275
+ /** Subscriptions that were rejected and are waiting to be re-attempted. */
20276
+ getPending() {
20277
+ return Array.from(this.pendingSubscriptions.values());
20278
+ }
18412
20279
  /**
18413
20280
  * Dispose a single subscription.
18414
20281
  * @param persist — if false, skip calling onPersist (used during batch cleanup).
18415
20282
  */
18416
20283
  dispose(id, persist = true) {
20284
+ // Invalidate any subscribe() for this id that is still awaiting.
20285
+ this.generations.set(id, (this.generations.get(id) ?? 0) + 1);
18417
20286
  const proxy = this.proxies.get(id);
18418
20287
  if (proxy) {
18419
20288
  try {
@@ -18430,15 +20299,24 @@ class WakerSubscriptionManager {
18430
20299
  this.debounceTimers.delete(id);
18431
20300
  }
18432
20301
  this.activeSubscriptions.delete(id);
20302
+ this.pendingSubscriptions.delete(id);
18433
20303
  this.seenMessages.delete(id);
18434
20304
  if (persist)
18435
20305
  this.persist();
18436
20306
  }
18437
- /** Dispose all active subscriptions. */
20307
+ /** Dispose all active subscriptions and drop anything still pending. */
18438
20308
  disposeAll() {
20309
+ // Bump the epoch first: in-flight subscribe() calls have no proxy in the
20310
+ // map yet, so per-id invalidation alone cannot reach them.
20311
+ this.epoch++;
18439
20312
  for (const [id] of this.proxies) {
18440
20313
  this.dispose(id, false);
18441
20314
  }
20315
+ this.pendingSubscriptions.clear();
20316
+ if (this.retryTimer) {
20317
+ clearTimeout(this.retryTimer);
20318
+ this.retryTimer = null;
20319
+ }
18442
20320
  }
18443
20321
  /** Get all active subscriptions. */
18444
20322
  getActive() {
@@ -18536,18 +20414,6 @@ class SmartLiteral {
18536
20414
  }
18537
20415
  _SmartLiteral_perspective = new WeakMap(), _SmartLiteral_base = new WeakMap();
18538
20416
 
18539
- /**
18540
- * Shared type definitions for the Ad4mModel system.
18541
- *
18542
- * Extracted into a standalone module so that utility files
18543
- * (`query-utils.ts`, `decorators.ts`, etc.) can import types without
18544
- * creating circular runtime dependencies on `Ad4mModel.ts`.
18545
- */
18546
- /** Type guard for IncludeProjection objects. */
18547
- function isIncludeProjection(val) {
18548
- return typeof val === 'object' && val !== null && 'from' in val;
18549
- }
18550
-
18551
20417
  /**
18552
20418
  * Shared query compilation utilities.
18553
20419
  *
@@ -18918,6 +20784,7 @@ exports.ExpressionProofInput = ExpressionProofInput;
18918
20784
  exports.ExpressionRef = ExpressionRef;
18919
20785
  exports.ExpressionRendered = ExpressionRendered;
18920
20786
  exports.Flag = Flag;
20787
+ exports.FlowInstance = FlowInstance;
18921
20788
  exports.HasMany = HasMany;
18922
20789
  exports.HasOne = HasOne;
18923
20790
  exports.HostingUserInfo = HostingUserInfo;
@@ -19021,6 +20888,7 @@ exports.getPropertiesMetadata = getPropertiesMetadata;
19021
20888
  exports.getPropertyOption = getPropertyOption;
19022
20889
  exports.getRelationsMetadata = getRelationsMetadata;
19023
20890
  exports.hasJsOnlyWhereFilters = hasJsOnlyWhereFilters;
20891
+ exports.hintFor = hintFor;
19024
20892
  exports.ifExpr = ifExpr;
19025
20893
  exports.invalidatePerspectiveCache = invalidatePerspectiveCache;
19026
20894
  exports.isArrayType = isArrayType;
@@ -19031,6 +20899,7 @@ exports.isNodeExpression = isNodeExpression;
19031
20899
  exports.isNumericType = isNumericType;
19032
20900
  exports.isObjectType = isObjectType;
19033
20901
  exports.isSchemaType = isSchemaType;
20902
+ exports.isTraverseScope = isTraverseScope;
19034
20903
  exports.linkEqual = linkEqual;
19035
20904
  exports.literal = literal;
19036
20905
  exports.looksLikeUri = looksLikeUri;
@@ -19044,6 +20913,7 @@ exports.parseLitNumber = parseLitNumber;
19044
20913
  exports.parseSparqlCount = parseSparqlCount;
19045
20914
  exports.path = path;
19046
20915
  exports.queryCacheSize = queryCacheSize;
20916
+ exports.requireSingleParent = requireSingleParent;
19047
20917
  exports.resolveParentPredicate = resolveParentPredicate;
19048
20918
  exports.setCachedResult = setCachedResult;
19049
20919
  exports.setPropertyRegistryEntry = setPropertyRegistryEntry;