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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (254) hide show
  1. package/lib/index.cjs +1982 -498
  2. package/lib/index.js +1982 -499
  3. package/lib/src/ai/AIClient.js +6 -3
  4. package/lib/src/apiClient.d.ts +40 -4
  5. package/lib/src/apiClient.js +149 -9
  6. package/lib/src/index.d.ts +3 -1
  7. package/lib/src/index.js +2 -0
  8. package/lib/src/model/Ad4mModel.d.ts +6 -5
  9. package/lib/src/model/Ad4mModel.js +246 -29
  10. package/lib/src/model/Ad4mModel.test.js +480 -735
  11. package/lib/src/model/decorators.d.ts +147 -4
  12. package/lib/src/model/decorators.js +70 -24
  13. package/lib/src/model/model-manifest.d.ts +41 -0
  14. package/lib/src/model/model-manifest.js +11 -0
  15. package/lib/src/model/query-sparql.test.js +92 -10
  16. package/lib/src/model/shacl-gen.js +33 -0
  17. package/lib/src/model/types.d.ts +9 -0
  18. package/lib/src/neighbourhood/NeighbourhoodProxy.test.js +33 -33
  19. package/lib/src/perspectives/AutoProcessor.d.ts +90 -24
  20. package/lib/src/perspectives/FlowInstance.d.ts +187 -0
  21. package/lib/src/perspectives/FlowInstance.js +336 -0
  22. package/lib/src/perspectives/FlowModels.d.ts +94 -0
  23. package/lib/src/perspectives/FlowModels.js +182 -0
  24. package/lib/src/perspectives/InterpretationModels.d.ts +12 -22
  25. package/lib/src/perspectives/InterpretationModels.js +2 -6
  26. package/lib/src/perspectives/PerspectiveClient.d.ts +68 -7
  27. package/lib/src/perspectives/PerspectiveClient.js +105 -10
  28. package/lib/src/perspectives/PerspectiveProxy.d.ts +142 -57
  29. package/lib/src/perspectives/PerspectiveProxy.js +388 -274
  30. package/lib/src/shacl/SHACLFlow.d.ts +273 -47
  31. package/lib/src/shacl/SHACLFlow.js +397 -88
  32. package/lib/src/shacl/SHACLShape.d.ts +8 -0
  33. package/lib/src/shacl/SHACLShape.js +17 -0
  34. package/lib/src/shacl/SHACLShape.test.js +82 -0
  35. package/package.json +2 -2
  36. package/src/ai/AIClient.ts +6 -3
  37. package/src/apiClient.test.ts +227 -0
  38. package/src/apiClient.ts +185 -9
  39. package/src/index.ts +3 -1
  40. package/src/model/Ad4mModel.test.ts +645 -0
  41. package/src/model/Ad4mModel.ts +245 -26
  42. package/src/model/decorators.ts +216 -35
  43. package/src/model/relation-filtering.test.ts +70 -20
  44. package/src/model/shacl-gen.ts +36 -0
  45. package/src/model/shacl-roundtrip.test.ts +130 -0
  46. package/src/model/types.ts +7 -0
  47. package/src/perspectives/AutoProcessor.ts +94 -24
  48. package/src/perspectives/FlowInstance.ts +369 -0
  49. package/src/perspectives/FlowModels.ts +157 -0
  50. package/src/perspectives/InterpretationModels.ts +13 -25
  51. package/src/perspectives/PerspectiveClient.test.ts +67 -6
  52. package/src/perspectives/PerspectiveClient.ts +142 -12
  53. package/src/perspectives/PerspectiveProxy.test.ts +406 -0
  54. package/src/perspectives/PerspectiveProxy.ts +459 -289
  55. package/src/perspectives/shacl-rpc.test.ts +258 -0
  56. package/src/shacl/SHACLFlow.test.ts +762 -35
  57. package/src/shacl/SHACLFlow.ts +680 -112
  58. package/src/shacl/SHACLShape.ts +31 -0
  59. package/lib/src/generated/rest/AIModelLoadingStatus.d.ts +0 -7
  60. package/lib/src/generated/rest/AIModelLoadingStatus.js +0 -2
  61. package/lib/src/generated/rest/AddAgentInfosRequest.d.ts +0 -3
  62. package/lib/src/generated/rest/AddAgentInfosRequest.js +0 -2
  63. package/lib/src/generated/rest/AddLinkExpressionRequest.d.ts +0 -6
  64. package/lib/src/generated/rest/AddLinkExpressionRequest.js +0 -1
  65. package/lib/src/generated/rest/AddLinkRequest.d.ts +0 -6
  66. package/lib/src/generated/rest/AddLinkRequest.js +0 -1
  67. package/lib/src/generated/rest/AddLinksBulkRequest.d.ts +0 -6
  68. package/lib/src/generated/rest/AddLinksBulkRequest.js +0 -1
  69. package/lib/src/generated/rest/AddSdnaRequest.d.ts +0 -6
  70. package/lib/src/generated/rest/AddSdnaRequest.js +0 -2
  71. package/lib/src/generated/rest/ApplyTemplateRequest.d.ts +0 -4
  72. package/lib/src/generated/rest/ApplyTemplateRequest.js +0 -2
  73. package/lib/src/generated/rest/AuthInfoInput.d.ts +0 -10
  74. package/lib/src/generated/rest/AuthInfoInput.js +0 -1
  75. package/lib/src/generated/rest/BroadcastRequest.d.ts +0 -6
  76. package/lib/src/generated/rest/BroadcastRequest.js +0 -1
  77. package/lib/src/generated/rest/CapabilityInput.d.ts +0 -5
  78. package/lib/src/generated/rest/CapabilityInput.js +0 -1
  79. package/lib/src/generated/rest/CommitBatchRequest.d.ts +0 -3
  80. package/lib/src/generated/rest/CommitBatchRequest.js +0 -2
  81. package/lib/src/generated/rest/ComputeLogEntry.d.ts +0 -9
  82. package/lib/src/generated/rest/ComputeLogEntry.js +0 -2
  83. package/lib/src/generated/rest/CreateExpressionRequest.d.ts +0 -4
  84. package/lib/src/generated/rest/CreateExpressionRequest.js +0 -2
  85. package/lib/src/generated/rest/CreatePerspectiveRequest.d.ts +0 -3
  86. package/lib/src/generated/rest/CreatePerspectiveRequest.js +0 -2
  87. package/lib/src/generated/rest/CreateSubjectRequest.d.ts +0 -6
  88. package/lib/src/generated/rest/CreateSubjectRequest.js +0 -2
  89. package/lib/src/generated/rest/CreateUserRequest.d.ts +0 -4
  90. package/lib/src/generated/rest/CreateUserRequest.js +0 -2
  91. package/lib/src/generated/rest/CreateUserResponse.d.ts +0 -5
  92. package/lib/src/generated/rest/CreateUserResponse.js +0 -2
  93. package/lib/src/generated/rest/DecoratedExpressionProof.d.ts +0 -6
  94. package/lib/src/generated/rest/DecoratedExpressionProof.js +0 -2
  95. package/lib/src/generated/rest/DecoratedLinkExpression.d.ts +0 -10
  96. package/lib/src/generated/rest/DecoratedLinkExpression.js +0 -1
  97. package/lib/src/generated/rest/DisposeQueryRequest.d.ts +0 -3
  98. package/lib/src/generated/rest/DisposeQueryRequest.js +0 -2
  99. package/lib/src/generated/rest/EmailTestRequest.d.ts +0 -6
  100. package/lib/src/generated/rest/EmailTestRequest.js +0 -2
  101. package/lib/src/generated/rest/EmbedRequest.d.ts +0 -4
  102. package/lib/src/generated/rest/EmbedRequest.js +0 -2
  103. package/lib/src/generated/rest/EntanglementProofInput.d.ts +0 -6
  104. package/lib/src/generated/rest/EntanglementProofInput.js +0 -2
  105. package/lib/src/generated/rest/EntanglementProofPreflightRequest.d.ts +0 -4
  106. package/lib/src/generated/rest/EntanglementProofPreflightRequest.js +0 -2
  107. package/lib/src/generated/rest/ExecuteCommandsRequest.d.ts +0 -4
  108. package/lib/src/generated/rest/ExecuteCommandsRequest.js +0 -2
  109. package/lib/src/generated/rest/ExportRequest.d.ts +0 -5
  110. package/lib/src/generated/rest/ExportRequest.js +0 -2
  111. package/lib/src/generated/rest/ExpressionManyRequest.d.ts +0 -3
  112. package/lib/src/generated/rest/ExpressionManyRequest.js +0 -2
  113. package/lib/src/generated/rest/ExpressionProof.d.ts +0 -4
  114. package/lib/src/generated/rest/ExpressionProof.js +0 -2
  115. package/lib/src/generated/rest/ExpressionProofInput.d.ts +0 -6
  116. package/lib/src/generated/rest/ExpressionProofInput.js +0 -2
  117. package/lib/src/generated/rest/FriendSendMessageRequest.d.ts +0 -3
  118. package/lib/src/generated/rest/FriendSendMessageRequest.js +0 -2
  119. package/lib/src/generated/rest/FriendsListRequest.d.ts +0 -3
  120. package/lib/src/generated/rest/FriendsListRequest.js +0 -2
  121. package/lib/src/generated/rest/GenerateAgentRequest.d.ts +0 -3
  122. package/lib/src/generated/rest/GenerateAgentRequest.js +0 -2
  123. package/lib/src/generated/rest/GenerateJwtRequest.d.ts +0 -4
  124. package/lib/src/generated/rest/GenerateJwtRequest.js +0 -2
  125. package/lib/src/generated/rest/GetSubjectDataRequest.d.ts +0 -4
  126. package/lib/src/generated/rest/GetSubjectDataRequest.js +0 -2
  127. package/lib/src/generated/rest/HostingInfoResponse.d.ts +0 -5
  128. package/lib/src/generated/rest/HostingInfoResponse.js +0 -2
  129. package/lib/src/generated/rest/HostingWalletResponse.d.ts +0 -4
  130. package/lib/src/generated/rest/HostingWalletResponse.js +0 -2
  131. package/lib/src/generated/rest/ImportAgentRequest.d.ts +0 -6
  132. package/lib/src/generated/rest/ImportAgentRequest.js +0 -2
  133. package/lib/src/generated/rest/ImportRequest.d.ts +0 -4
  134. package/lib/src/generated/rest/ImportRequest.js +0 -2
  135. package/lib/src/generated/rest/JoinNeighbourhoodRequest.d.ts +0 -3
  136. package/lib/src/generated/rest/JoinNeighbourhoodRequest.js +0 -2
  137. package/lib/src/generated/rest/KeepAliveQueryRequest.d.ts +0 -3
  138. package/lib/src/generated/rest/KeepAliveQueryRequest.js +0 -2
  139. package/lib/src/generated/rest/LanguageMetaInput.d.ts +0 -6
  140. package/lib/src/generated/rest/LanguageMetaInput.js +0 -2
  141. package/lib/src/generated/rest/Link.d.ts +0 -5
  142. package/lib/src/generated/rest/Link.js +0 -2
  143. package/lib/src/generated/rest/LinkExpression.d.ts +0 -10
  144. package/lib/src/generated/rest/LinkExpression.js +0 -1
  145. package/lib/src/generated/rest/LinkExpressionInput.d.ts +0 -10
  146. package/lib/src/generated/rest/LinkExpressionInput.js +0 -1
  147. package/lib/src/generated/rest/LinkInput.d.ts +0 -5
  148. package/lib/src/generated/rest/LinkInput.js +0 -2
  149. package/lib/src/generated/rest/LinkLanguageTemplatesRequest.d.ts +0 -3
  150. package/lib/src/generated/rest/LinkLanguageTemplatesRequest.js +0 -2
  151. package/lib/src/generated/rest/LinkMutationRequest.d.ts +0 -12
  152. package/lib/src/generated/rest/LinkMutationRequest.js +0 -1
  153. package/lib/src/generated/rest/LinkMutationResponse.d.ts +0 -9
  154. package/lib/src/generated/rest/LinkMutationResponse.js +0 -1
  155. package/lib/src/generated/rest/LinkMutations.d.ts +0 -6
  156. package/lib/src/generated/rest/LinkMutations.js +0 -1
  157. package/lib/src/generated/rest/LinkMutationsRequest.d.ts +0 -5
  158. package/lib/src/generated/rest/LinkMutationsRequest.js +0 -1
  159. package/lib/src/generated/rest/LinkStatus.d.ts +0 -1
  160. package/lib/src/generated/rest/LinkStatus.js +0 -2
  161. package/lib/src/generated/rest/LinkUpdateInput.d.ts +0 -5
  162. package/lib/src/generated/rest/LinkUpdateInput.js +0 -1
  163. package/lib/src/generated/rest/LockAgentRequest.d.ts +0 -3
  164. package/lib/src/generated/rest/LockAgentRequest.js +0 -2
  165. package/lib/src/generated/rest/LoginUserRequest.d.ts +0 -5
  166. package/lib/src/generated/rest/LoginUserRequest.js +0 -2
  167. package/lib/src/generated/rest/ModelType.d.ts +0 -1
  168. package/lib/src/generated/rest/ModelType.js +0 -2
  169. package/lib/src/generated/rest/NotificationGrantRequest.d.ts +0 -3
  170. package/lib/src/generated/rest/NotificationGrantRequest.js +0 -2
  171. package/lib/src/generated/rest/NotificationInput.d.ts +0 -10
  172. package/lib/src/generated/rest/NotificationInput.js +0 -2
  173. package/lib/src/generated/rest/OpenLinkRequest.d.ts +0 -3
  174. package/lib/src/generated/rest/OpenLinkRequest.js +0 -2
  175. package/lib/src/generated/rest/PermitCapabilityRequest.d.ts +0 -3
  176. package/lib/src/generated/rest/PermitCapabilityRequest.js +0 -2
  177. package/lib/src/generated/rest/PerspectiveInput.d.ts +0 -4
  178. package/lib/src/generated/rest/PerspectiveInput.js +0 -1
  179. package/lib/src/generated/rest/PromptRequest.d.ts +0 -4
  180. package/lib/src/generated/rest/PromptRequest.js +0 -2
  181. package/lib/src/generated/rest/PublicPerspectiveInput.d.ts +0 -4
  182. package/lib/src/generated/rest/PublicPerspectiveInput.js +0 -1
  183. package/lib/src/generated/rest/PublishLanguageRequest.d.ts +0 -5
  184. package/lib/src/generated/rest/PublishLanguageRequest.js +0 -1
  185. package/lib/src/generated/rest/PublishNeighbourhoodRequest.d.ts +0 -6
  186. package/lib/src/generated/rest/PublishNeighbourhoodRequest.js +0 -1
  187. package/lib/src/generated/rest/QueryRequest.d.ts +0 -7
  188. package/lib/src/generated/rest/QueryRequest.js +0 -2
  189. package/lib/src/generated/rest/RemoveLinkRequest.d.ts +0 -5
  190. package/lib/src/generated/rest/RemoveLinkRequest.js +0 -1
  191. package/lib/src/generated/rest/RemoveLinksBulkRequest.d.ts +0 -5
  192. package/lib/src/generated/rest/RemoveLinksBulkRequest.js +0 -1
  193. package/lib/src/generated/rest/RequestCapabilityRequest.d.ts +0 -4
  194. package/lib/src/generated/rest/RequestCapabilityRequest.js +0 -1
  195. package/lib/src/generated/rest/RequestPaymentRequest.d.ts +0 -3
  196. package/lib/src/generated/rest/RequestPaymentRequest.js +0 -2
  197. package/lib/src/generated/rest/RequestVerificationRequest.d.ts +0 -4
  198. package/lib/src/generated/rest/RequestVerificationRequest.js +0 -2
  199. package/lib/src/generated/rest/ResourceInput.d.ts +0 -4
  200. package/lib/src/generated/rest/ResourceInput.js +0 -2
  201. package/lib/src/generated/rest/SetDefaultModelRequest.d.ts +0 -4
  202. package/lib/src/generated/rest/SetDefaultModelRequest.js +0 -1
  203. package/lib/src/generated/rest/SetFreeHostingEnabledRequest.d.ts +0 -3
  204. package/lib/src/generated/rest/SetFreeHostingEnabledRequest.js +0 -2
  205. package/lib/src/generated/rest/SetHotWalletAddressRequest.d.ts +0 -3
  206. package/lib/src/generated/rest/SetHotWalletAddressRequest.js +0 -2
  207. package/lib/src/generated/rest/SetMultiUserRequest.d.ts +0 -3
  208. package/lib/src/generated/rest/SetMultiUserRequest.js +0 -2
  209. package/lib/src/generated/rest/SetOnlineStatusRequest.d.ts +0 -5
  210. package/lib/src/generated/rest/SetOnlineStatusRequest.js +0 -1
  211. package/lib/src/generated/rest/SetStatusRequest.d.ts +0 -3
  212. package/lib/src/generated/rest/SetStatusRequest.js +0 -2
  213. package/lib/src/generated/rest/SetUserFreeAccessRequest.d.ts +0 -4
  214. package/lib/src/generated/rest/SetUserFreeAccessRequest.js +0 -2
  215. package/lib/src/generated/rest/SignMessageRequest.d.ts +0 -3
  216. package/lib/src/generated/rest/SignMessageRequest.js +0 -2
  217. package/lib/src/generated/rest/SignalRequest.d.ts +0 -6
  218. package/lib/src/generated/rest/SignalRequest.js +0 -1
  219. package/lib/src/generated/rest/SubscribeQueryRequest.d.ts +0 -3
  220. package/lib/src/generated/rest/SubscribeQueryRequest.js +0 -2
  221. package/lib/src/generated/rest/SubscribeQueryResponse.d.ts +0 -4
  222. package/lib/src/generated/rest/SubscribeQueryResponse.js +0 -2
  223. package/lib/src/generated/rest/TrustedAgentsRequest.d.ts +0 -3
  224. package/lib/src/generated/rest/TrustedAgentsRequest.js +0 -2
  225. package/lib/src/generated/rest/UnlockAgentRequest.d.ts +0 -4
  226. package/lib/src/generated/rest/UnlockAgentRequest.js +0 -2
  227. package/lib/src/generated/rest/UpdateLinkRequest.d.ts +0 -7
  228. package/lib/src/generated/rest/UpdateLinkRequest.js +0 -1
  229. package/lib/src/generated/rest/UpdatePerspectiveRequest.d.ts +0 -3
  230. package/lib/src/generated/rest/UpdatePerspectiveRequest.js +0 -2
  231. package/lib/src/generated/rest/UpdateProfileRequest.d.ts +0 -5
  232. package/lib/src/generated/rest/UpdateProfileRequest.js +0 -1
  233. package/lib/src/generated/rest/UserStatistics.d.ts +0 -9
  234. package/lib/src/generated/rest/UserStatistics.js +0 -2
  235. package/lib/src/generated/rest/VerificationRequestResult.d.ts +0 -6
  236. package/lib/src/generated/rest/VerificationRequestResult.js +0 -2
  237. package/lib/src/generated/rest/VerifyEmailRequest.d.ts +0 -6
  238. package/lib/src/generated/rest/VerifyEmailRequest.js +0 -2
  239. package/lib/src/generated/rest/VerifySignatureRequest.d.ts +0 -5
  240. package/lib/src/generated/rest/VerifySignatureRequest.js +0 -2
  241. package/lib/src/generated/rest/WriteSettingsRequest.d.ts +0 -3
  242. package/lib/src/generated/rest/WriteSettingsRequest.js +0 -2
  243. package/lib/src/generated/rest/index.d.ts +0 -73
  244. package/lib/src/generated/rest/index.js +0 -8
  245. package/lib/src/generated/rest/routes.d.ts +0 -587
  246. package/lib/src/generated/rest/routes.js +0 -3
  247. package/lib/src/model/query-surreal.d.ts +0 -44
  248. package/lib/src/model/query-surreal.js +0 -249
  249. package/lib/src/model/surreal-utils.d.ts +0 -42
  250. package/lib/src/model/surreal-utils.js +0 -128
  251. package/lib/src/perspectives/PerspectiveProxy.test.d.ts +0 -1
  252. package/lib/src/perspectives/PerspectiveProxy.test.js +0 -34
  253. package/lib/src/restClient.d.ts +0 -52
  254. 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) {
@@ -2104,10 +2261,24 @@ interpretationHint) {
2104
2261
  if (relMeta.filter === false) {
2105
2262
  relShape.filter = false;
2106
2263
  }
2264
+ // Ordering is declared in the type system so the executor can act on it
2265
+ // for every writer, not just this client.
2266
+ if (relMeta.ordering) {
2267
+ relShape.ordering = relMeta.ordering.strategy;
2268
+ }
2107
2269
  // AD4M-specific metadata
2108
2270
  if (relMeta.local !== undefined) {
2109
2271
  relShape.local = relMeta.local;
2110
2272
  }
2273
+ // Per-relation interpretation hint — sentence-level meaning that
2274
+ // steers the harness LLM's `_propose_link_child` `predicate` field
2275
+ // description. Read back on the Rust side by
2276
+ // `ShaclProperty.interpretation_hint` and rendered into the tool
2277
+ // schema alongside the predicate URI enum (so `basedOn` reads
2278
+ // "prior beliefs this intention derives from", not just "some link").
2279
+ if (relMeta.interpretationHint) {
2280
+ relShape.interpretationHint = relMeta.interpretationHint;
2281
+ }
2111
2282
  // Adder / Remover actions — only meaningful for relations backed
2112
2283
  // by a real link predicate. Getter-only relations are read-only.
2113
2284
  if (relMeta.predicate) {
@@ -2244,6 +2415,25 @@ interpretationHint) {
2244
2415
  }
2245
2416
  shape.addProperty(relShape);
2246
2417
  }
2418
+ // ── Ordering links ─────────────────────────────────────────────────
2419
+ // Ordering entries are stored on the *parent*, under one shared predicate,
2420
+ // so that reconstruction needs no extra query: they arrive with the
2421
+ // instance's own links. That only works if the instance query asks for them,
2422
+ // and it builds its predicate filter from the shape's declared paths — so a
2423
+ // class owning any ordered collection has to declare the predicate, or the
2424
+ // very links the ordering depends on are filtered out of the read that needs
2425
+ // them.
2426
+ //
2427
+ // One entry covers every ordered relation on the class; each entry names the
2428
+ // relation it belongs to.
2429
+ const hasOrderedRelation = Object.values(allRelationsMeta).some((m) => m.ordering);
2430
+ if (hasOrderedRelation) {
2431
+ shape.addProperty({
2432
+ name: '_collectionOrder',
2433
+ path: 'ad4m://collection_order',
2434
+ nodeKind: 'IRI',
2435
+ });
2436
+ }
2247
2437
  // Always set constructor and destructor actions on the shape, even
2248
2438
  // when empty. An empty array serialises to `literal:string:[]`
2249
2439
  // which the Rust executor parses as a valid (no-op) command list,
@@ -2833,35 +3023,57 @@ function resolveRelationArgs(first, second) {
2833
3023
  const opts = typeof first === 'function'
2834
3024
  ? { ...(second || {}), target: first }
2835
3025
  : first;
2836
- // getter is mutually exclusive with through, target, and where
3026
+ // `where` and `filter: false` contradict each other on every relation,
3027
+ // getter-backed ones included — checked before the getter path returns.
3028
+ if (opts.where && opts.filter === false) {
3029
+ throw new Error('Relation decorator: `where` and `filter: false` are contradictory. ' +
3030
+ '`where` adds filtering constraints; `filter: false` disables filtering.');
3031
+ }
3032
+ // getter is mutually exclusive with through
2837
3033
  if (opts.getter) {
2838
3034
  if (opts.through) {
2839
3035
  throw new Error('Relation decorator: `getter` and `through` are mutually exclusive. ' +
2840
3036
  'Use `getter` alone for custom read-only relations, or `through` ' +
2841
3037
  '(with optional `target`) for standard link-based relations.');
2842
3038
  }
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
- }
3039
+ // `target` and `where` are NOT mutually exclusive with `getter`.
3040
+ //
3041
+ // `target` does two separable jobs: it auto-derives a conformance
3042
+ // getter, and it names the class the relation's values hydrate into.
3043
+ // Only the first conflicts with an explicit getter, and `buildSHACL`
3044
+ // already resolves that on its own — an explicit getter wins the getter
3045
+ // slot, while `sh:class` / `ad4m:targetClassName` are emitted from
3046
+ // `target` independently.
3047
+ //
3048
+ // Refusing the pair cost the one thing a custom getter is for. A getter
3049
+ // expresses a traversal the link-shaped DSL cannot — most usefully
3050
+ // through a reified edge, where the connection is a record rather than
3051
+ // a predicate:
3052
+ //
3053
+ // @HasMany({
3054
+ // getter: "SELECT ?target WHERE { \
3055
+ // ?citation <paper://cites_from> <Base> . \
3056
+ // ?citation <paper://cites_to> ?target . }",
3057
+ // target: () => Paper,
3058
+ // })
3059
+ // cited: Paper[] = [];
3060
+ //
3061
+ // Without `target` the relation has no target class, so `include` on it
3062
+ // resolves a shape named "" and fails — leaving a traversal that can
3063
+ // only ever return bare URIs. With it, the values hydrate like any other
3064
+ // relation, because getters are evaluated before include resolution.
3065
+ //
3066
+ // `where` is the same story: the executor applies post-getter where
3067
+ // filters specifically to getter-backed relations
3068
+ // (`apply_where_filter_to_relation`), and emitting `wherePredicates`
3069
+ // needs `target` to resolve the target's metadata — so the runtime is
3070
+ // built for all three together and only this check said otherwise.
2852
3071
  return opts;
2853
3072
  }
2854
3073
  // Default predicate when not provided
2855
3074
  if (!opts.through) {
2856
3075
  opts.through = 'ad4m://has_child';
2857
3076
  }
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
3077
  return opts;
2866
3078
  }
2867
3079
  function HasMany(first, second) {
@@ -2881,6 +3093,10 @@ function HasMany(first, second) {
2881
3093
  ...(opts.filter !== undefined && { filter: opts.filter }),
2882
3094
  ...(opts.where && { where: opts.where }),
2883
3095
  ...(opts.datatype && { datatype: opts.datatype }),
3096
+ ...(opts.polymorphic && { polymorphic: opts.polymorphic }),
3097
+ ...(opts.instantiateAs && { instantiateAs: opts.instantiateAs }),
3098
+ ...(opts.ordering && { ordering: opts.ordering }),
3099
+ ...(opts.interpretationHint && { interpretationHint: opts.interpretationHint }),
2884
3100
  };
2885
3101
  const relKey = key;
2886
3102
  // Only add mutation methods when a predicate is available
@@ -2915,6 +3131,10 @@ function HasOne(first, second) {
2915
3131
  ...(opts.filter !== undefined && { filter: opts.filter }),
2916
3132
  ...(opts.where && { where: opts.where }),
2917
3133
  ...(opts.datatype && { datatype: opts.datatype }),
3134
+ ...(opts.polymorphic && { polymorphic: opts.polymorphic }),
3135
+ ...(opts.instantiateAs && { instantiateAs: opts.instantiateAs }),
3136
+ ...(opts.ordering && { ordering: opts.ordering }),
3137
+ ...(opts.interpretationHint && { interpretationHint: opts.interpretationHint }),
2918
3138
  };
2919
3139
  const relKey = key;
2920
3140
  if (opts.through) {
@@ -2924,15 +3144,23 @@ function HasOne(first, second) {
2924
3144
  readOnly: false,
2925
3145
  local: opts.local,
2926
3146
  })(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);
3147
+ // Add prototype methods for add/remove/set (mirroring @HasMany).
3148
+ //
3149
+ // `batchId` is part of that mirroring: without it a to-one link
3150
+ // cannot join a write group, so anything that creates a record and
3151
+ // then points it at something has to commit twice and every
3152
+ // subscriber sees the state in between — a record whose to-one
3153
+ // relation is still empty. Anything rendering from a subscription
3154
+ // therefore has a frame in which the record exists and points at
3155
+ // nothing.
3156
+ target[`add${capitalize(relKey)}`] = async function (arg, batchId) {
3157
+ return this.addRelationValue(relKey, arg, batchId);
2930
3158
  };
2931
- target[`remove${capitalize(relKey)}`] = async function (arg) {
2932
- return this.removeRelationValue(relKey, arg);
3159
+ target[`remove${capitalize(relKey)}`] = async function (arg, batchId) {
3160
+ return this.removeRelationValue(relKey, arg, batchId);
2933
3161
  };
2934
- target[`set${capitalize(relKey)}`] = async function (arg) {
2935
- return this.setRelationValues(relKey, arg);
3162
+ target[`set${capitalize(relKey)}`] = async function (arg, batchId) {
3163
+ return this.setRelationValues(relKey, arg, batchId);
2936
3164
  };
2937
3165
  }
2938
3166
  else {
@@ -2956,6 +3184,10 @@ function BelongsToOne(first, second) {
2956
3184
  ...(opts.filter !== undefined && { filter: opts.filter }),
2957
3185
  ...(opts.where && { where: opts.where }),
2958
3186
  ...(opts.datatype && { datatype: opts.datatype }),
3187
+ ...(opts.polymorphic && { polymorphic: opts.polymorphic }),
3188
+ ...(opts.instantiateAs && { instantiateAs: opts.instantiateAs }),
3189
+ ...(opts.ordering && { ordering: opts.ordering }),
3190
+ ...(opts.interpretationHint && { interpretationHint: opts.interpretationHint }),
2959
3191
  };
2960
3192
  if (opts.through) {
2961
3193
  // Read-only property (the owning side manages the link)
@@ -2986,6 +3218,10 @@ function BelongsToMany(first, second) {
2986
3218
  ...(opts.filter !== undefined && { filter: opts.filter }),
2987
3219
  ...(opts.where && { where: opts.where }),
2988
3220
  ...(opts.datatype && { datatype: opts.datatype }),
3221
+ ...(opts.polymorphic && { polymorphic: opts.polymorphic }),
3222
+ ...(opts.instantiateAs && { instantiateAs: opts.instantiateAs }),
3223
+ ...(opts.ordering && { ordering: opts.ordering }),
3224
+ ...(opts.interpretationHint && { interpretationHint: opts.interpretationHint }),
2989
3225
  };
2990
3226
  // @BelongsToMany is the inverse/read-only side — do NOT generate add*/remove*/set*
2991
3227
  // prototype methods. Mutation must go through the owning side's @HasMany decorator.
@@ -3061,59 +3297,82 @@ function queryCacheSize() {
3061
3297
  return cache.size;
3062
3298
  }
3063
3299
 
3300
+ /**
3301
+ * Runtime shape check for a decoded `ModelQuery`. Deserialization paths use
3302
+ * this to guard against malformed guard arrays leaking into flow metadata
3303
+ * (an untyped `Array.isArray` would happily accept `[null]` or `[{}]`).
3304
+ * Only the mandatory `className: string` field is enforced — richer
3305
+ * validation stays with the runtime engine that will actually execute the
3306
+ * query.
3307
+ */
3308
+ function isModelQueryShape(v) {
3309
+ if (typeof v !== "object" ||
3310
+ v === null ||
3311
+ typeof v.className !== "string" ||
3312
+ v.className.length === 0) {
3313
+ return false;
3314
+ }
3315
+ const or = v.or;
3316
+ if (or !== undefined) {
3317
+ if (!Array.isArray(or) || !or.every(isModelQueryShape))
3318
+ return false;
3319
+ }
3320
+ return true;
3321
+ }
3322
+ /**
3323
+ * Runtime shape check for a decoded `ConsensusRule`. Enforces the one
3324
+ * mandatory field (`n: number` with a sane range) and, when `fromRole`
3325
+ * is present, that it's a valid ModelQuery. A malformed literal (e.g.
3326
+ * `{ n: "many" }` or `{ n: 1, fromRole: null }`) leaves the field unset
3327
+ * rather than becoming corrupt flow metadata that downstream engines
3328
+ * would trip over.
3329
+ */
3330
+ function isConsensusRuleShape(v) {
3331
+ if (typeof v !== "object" || v === null)
3332
+ return false;
3333
+ const n = v.n;
3334
+ if (typeof n !== "number" || !Number.isFinite(n) || n < 1 || !Number.isInteger(n)) {
3335
+ return false;
3336
+ }
3337
+ const fromRole = v.fromRole;
3338
+ if (fromRole !== undefined && !isModelQueryShape(fromRole))
3339
+ return false;
3340
+ return true;
3341
+ }
3064
3342
  /**
3065
3343
  * SHACL Flow - represents a state machine for AD4M expressions
3066
3344
  *
3067
3345
  * 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)
3346
+ * - Which expressions can enter the flow (via `inputTypes`)
3347
+ * - What states exist and their per-state guards (via `requires`)
3348
+ * - How to transition between states (via transitions + consensus rules)
3349
+ *
3350
+ * State lives on the on-graph `FlowInstanceRecord.currentState` and is
3351
+ * read/written through the `FlowInstance` wrapper class
3352
+ * ({@link FlowInstance.start} / {@link FlowInstance.findAll}) — see design
3353
+ * doc §4.3/§5.
3071
3354
  *
3072
3355
  * @example
3073
3356
  * ```typescript
3074
3357
  * const todoFlow = new SHACLFlow('todo://TODO', 'todo://');
3075
3358
  *
3076
3359
  * // 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
- * });
3360
+ * todoFlow.inputTypes = ['any'];
3095
3361
  *
3096
- * // Define start action
3097
- * todoFlow.startAction = [{
3098
- * action: 'addLink',
3099
- * source: 'this',
3100
- * predicate: 'todo://state',
3101
- * target: 'todo://ready'
3102
- * }];
3362
+ * todoFlow.addState({ name: 'ready', value: 0 });
3363
+ * todoFlow.addState({ name: 'doing', value: 0.5 });
3364
+ * todoFlow.addState({ name: 'done', value: 1 });
3103
3365
  *
3104
- * // Define transitions
3105
3366
  * todoFlow.addTransition({
3106
3367
  * actionName: 'Start',
3107
3368
  * fromState: 'ready',
3108
3369
  * 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
- * ]
3370
+ * actions: [],
3113
3371
  * });
3114
3372
  *
3115
- * // Store in perspective
3373
+ * // Register on the perspective and mint an instance on a subject.
3116
3374
  * await perspective.addFlow('TODO', todoFlow);
3375
+ * const instance = await FlowInstance.start(perspective, 'TODO', 'expr://123');
3117
3376
  * ```
3118
3377
  */
3119
3378
  class SHACLFlow {
@@ -3123,11 +3382,41 @@ class SHACLFlow {
3123
3382
  * @param namespace - Namespace for URIs (e.g., "todo://")
3124
3383
  */
3125
3384
  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 */
3385
+ /**
3386
+ * Subject-class URIs the flow accepts as its base expression.
3387
+ *
3388
+ * Design doc §4.1: a flow's *typed input*. When an
3389
+ * expression whose class matches any URI in this array enters scope,
3390
+ * the flow-spawn engine considers it a candidate base. Superseded
3391
+ * the older link-level `flowable: LinkPattern` primitive — model-level
3392
+ * matching by subject class instead of link matching. Empty array =
3393
+ * flow declares no typed input. The `"any"` sentinel is accepted as
3394
+ * a wildcard for tests and legacy flows.
3395
+ */
3396
+ this.inputTypes = [];
3397
+ /**
3398
+ * Subject-class URIs the flow must produce (linked to the base) for a
3399
+ * run to count as complete.
3400
+ *
3401
+ * Design doc §4.1: a flow's *typed output*. Two jobs:
3402
+ * (a) documentation for stateful flows — records what a completed run
3403
+ * leaves in the graph; (b) **terminal condition** for zero-state flows —
3404
+ * a flow with no `FlowState`s completes when at least one instance of
3405
+ * each `outputTypes` entry exists in scope and is linked to the base,
3406
+ * and `consensusRule` fires. This is what makes "Like" a first-class
3407
+ * flow with no state machine.
3408
+ */
3409
+ this.outputTypes = [];
3410
+ /**
3411
+ * States in this flow.
3412
+ *
3413
+ * **Ordering convention (James PR #929 R9):** the array is stored sorted
3414
+ * ascending by `value`. `states[0]` is the initial state — the one
3415
+ * {@link FlowInstance.start} mints a fresh instance into. A flow author
3416
+ * who wants a specific state as the entry point must give it the lowest
3417
+ * `value` in the set. `fromLinks` enforces this sort, so link-order on
3418
+ * the graph never dictates the initial state.
3419
+ */
3131
3420
  this._states = [];
3132
3421
  /** Transitions between states */
3133
3422
  this._transitions = [];
@@ -3195,27 +3484,63 @@ class SHACLFlow {
3195
3484
  predicate: "ad4m://flowName",
3196
3485
  target: Literal.from(this.name).toUrl()
3197
3486
  });
3198
- // Flowable condition
3199
- if (this.flowable === "any") {
3487
+ // Top-level interpretation hint (optional, drives AI state suggestion).
3488
+ // Empty strings are treated as "unset" so a round-trip through the graph
3489
+ // doesn't materialise an empty-hint predicate that consumers would then
3490
+ // read back as a meaningful value.
3491
+ if (this.interpretationHint) {
3200
3492
  links.push({
3201
3493
  source: flowUri,
3202
- predicate: "ad4m://flowable",
3203
- target: "ad4m://any"
3494
+ predicate: "ad4m://interpretationHint",
3495
+ target: Literal.from(this.interpretationHint).toUrl()
3204
3496
  });
3205
3497
  }
3206
- else {
3498
+ // Typed I/O (flow-level, design §4.1). Both arrays are only
3499
+ // serialized when non-empty — an empty list is indistinguishable
3500
+ // from "unset" for a round-trip, and emitting one would give
3501
+ // downstream consumers a meaningless predicate to interpret.
3502
+ if (this.inputTypes.length > 0) {
3503
+ links.push({
3504
+ source: flowUri,
3505
+ predicate: "ad4m://inputTypes",
3506
+ target: `literal:string:${encodeURIComponent(JSON.stringify(this.inputTypes))}`
3507
+ });
3508
+ }
3509
+ if (this.outputTypes.length > 0) {
3510
+ links.push({
3511
+ source: flowUri,
3512
+ predicate: "ad4m://outputTypes",
3513
+ target: `literal:string:${encodeURIComponent(JSON.stringify(this.outputTypes))}`
3514
+ });
3515
+ }
3516
+ // Flow-level `creationHint` — same empty-string-is-unset guard as
3517
+ // `interpretationHint`, same reason (round-trip fidelity).
3518
+ if (this.creationHint) {
3207
3519
  links.push({
3208
3520
  source: flowUri,
3209
- predicate: "ad4m://flowable",
3210
- target: `literal:string:${encodeURIComponent(JSON.stringify(this.flowable))}`
3521
+ predicate: "ad4m://creationHint",
3522
+ target: Literal.from(this.creationHint).toUrl()
3211
3523
  });
3212
3524
  }
3213
- // Start action
3214
- if (this.startAction.length > 0) {
3525
+ // Flow-level `context` — background queries the LLM sees but not
3526
+ // guard evidence. Single JSON literal, consumers parse back.
3527
+ if (this.context && this.context.length > 0) {
3215
3528
  links.push({
3216
3529
  source: flowUri,
3217
- predicate: "ad4m://startAction",
3218
- target: `literal:string:${encodeURIComponent(JSON.stringify(this.startAction))}`
3530
+ predicate: "ad4m://context",
3531
+ target: `literal:string:${encodeURIComponent(JSON.stringify(this.context))}`
3532
+ });
3533
+ }
3534
+ // Flow-level `consensusRule` — default for state transitions when a
3535
+ // FlowState omits its own rule; also the terminal-firing rule for
3536
+ // zero-state flows. Serialized as one JSON literal (the shape is
3537
+ // fixed and cheap to parse; consistent with `context` / `requires`
3538
+ // so consumers only need one parser).
3539
+ if (this.consensusRule) {
3540
+ links.push({
3541
+ source: flowUri,
3542
+ predicate: "ad4m://consensusRule",
3543
+ target: `literal:string:${encodeURIComponent(JSON.stringify(this.consensusRule))}`
3219
3544
  });
3220
3545
  }
3221
3546
  // States
@@ -3245,12 +3570,45 @@ class SHACLFlow {
3245
3570
  predicate: "ad4m://stateValue",
3246
3571
  target: Literal.from(state.value).toUrl()
3247
3572
  });
3248
- // State check pattern
3249
- links.push({
3250
- source: stateUri,
3251
- predicate: "ad4m://stateCheck",
3252
- target: `literal:string:${encodeURIComponent(JSON.stringify(state.stateCheck))}`
3253
- });
3573
+ // Per-state interpretation hint (optional, drives AI state suggestion).
3574
+ // Empty strings treated as unset — same rationale as the flow-level hint.
3575
+ if (state.interpretationHint) {
3576
+ links.push({
3577
+ source: stateUri,
3578
+ predicate: "ad4m://interpretationHint",
3579
+ target: Literal.from(state.interpretationHint).toUrl()
3580
+ });
3581
+ }
3582
+ // Per-state `requires` guard — array of ModelQueries, AND-combined.
3583
+ // Serialized as one JSON string on `ad4m://requires`. Consumers
3584
+ // (state-transition engine, `flow.availableActions`) parse back.
3585
+ if (state.requires && state.requires.length > 0) {
3586
+ links.push({
3587
+ source: stateUri,
3588
+ predicate: "ad4m://requires",
3589
+ target: `literal:string:${encodeURIComponent(JSON.stringify(state.requires))}`
3590
+ });
3591
+ }
3592
+ // Per-state `semanticCheck` hint — optional English confirmation
3593
+ // that runs after `requires` matches, for states where structural
3594
+ // presence isn't sufficient evidence. Empty string = unset.
3595
+ if (state.semanticCheck) {
3596
+ links.push({
3597
+ source: stateUri,
3598
+ predicate: "ad4m://semanticCheck",
3599
+ target: Literal.from(state.semanticCheck).toUrl()
3600
+ });
3601
+ }
3602
+ // Per-state `consensusRule` override — one JSON literal on the
3603
+ // state, same predicate name as the flow-level rule but scoped by
3604
+ // source URI so the reader can tell them apart.
3605
+ if (state.consensusRule) {
3606
+ links.push({
3607
+ source: stateUri,
3608
+ predicate: "ad4m://consensusRule",
3609
+ target: `literal:string:${encodeURIComponent(JSON.stringify(state.consensusRule))}`
3610
+ });
3611
+ }
3254
3612
  }
3255
3613
  // Transitions
3256
3614
  for (const transition of this._transitions) {
@@ -3315,31 +3673,96 @@ class SHACLFlow {
3315
3673
  const namespace = withoutSuffix.slice(0, lastSlashOrColon + 1);
3316
3674
  const name = withoutSuffix.slice(lastSlashOrColon + 1);
3317
3675
  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";
3676
+ // Find top-level interpretation hint. Only accept a decoded value that
3677
+ // is a non-empty string — malformed literals (Literal.get() can return
3678
+ // an object, number, etc.) leave the field unset rather than becoming
3679
+ // corrupt flow metadata.
3680
+ const flowHintLink = links.find(l => l.source === flowUri && l.predicate === "ad4m://interpretationHint");
3681
+ if (flowHintLink) {
3682
+ try {
3683
+ const decoded = Literal.fromUrl(flowHintLink.target).get();
3684
+ if (typeof decoded === "string" && decoded.length > 0) {
3685
+ flow.interpretationHint = decoded;
3686
+ }
3323
3687
  }
3324
- else {
3325
- try {
3326
- const jsonStr = flowableLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
3327
- flow.flowable = JSON.parse(decodeURIComponent(jsonStr));
3688
+ catch {
3689
+ // Ignore parse errors — leave unset.
3690
+ }
3691
+ }
3692
+ // Find typed I/O (flow-level, design §4.1). Both arrays validated
3693
+ // element-wise — only accept string[] payloads. A malformed literal
3694
+ // (`[null]`, `[42]`, non-array) leaves the field as its default
3695
+ // empty array rather than corrupting flow metadata.
3696
+ const inputTypesLink = links.find(l => l.source === flowUri && l.predicate === "ad4m://inputTypes");
3697
+ if (inputTypesLink) {
3698
+ try {
3699
+ const jsonStr = inputTypesLink.target.replace(/^literal:\/\/string:|^literal:string:/, "");
3700
+ const parsed = JSON.parse(decodeURIComponent(jsonStr));
3701
+ if (Array.isArray(parsed) && parsed.every(v => typeof v === "string" && v.length > 0)) {
3702
+ flow.inputTypes = parsed;
3328
3703
  }
3329
- catch {
3330
- flow.flowable = "any";
3704
+ }
3705
+ catch {
3706
+ // Ignore parse errors — leave as default empty array.
3707
+ }
3708
+ }
3709
+ const outputTypesLink = links.find(l => l.source === flowUri && l.predicate === "ad4m://outputTypes");
3710
+ if (outputTypesLink) {
3711
+ try {
3712
+ const jsonStr = outputTypesLink.target.replace(/^literal:\/\/string:|^literal:string:/, "");
3713
+ const parsed = JSON.parse(decodeURIComponent(jsonStr));
3714
+ if (Array.isArray(parsed) && parsed.every(v => typeof v === "string" && v.length > 0)) {
3715
+ flow.outputTypes = parsed;
3331
3716
  }
3332
3717
  }
3718
+ catch {
3719
+ // Ignore parse errors — leave as default empty array.
3720
+ }
3333
3721
  }
3334
- // Find start action
3335
- const startActionLink = links.find(l => l.source === flowUri && l.predicate === "ad4m://startAction");
3336
- if (startActionLink) {
3722
+ // Find flow-level `creationHint`. Non-empty-string guard — same
3723
+ // rationale as `interpretationHint`.
3724
+ const creationHintLink = links.find(l => l.source === flowUri && l.predicate === "ad4m://creationHint");
3725
+ if (creationHintLink) {
3337
3726
  try {
3338
- const jsonStr = startActionLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
3339
- flow.startAction = JSON.parse(decodeURIComponent(jsonStr));
3727
+ const decoded = Literal.fromUrl(creationHintLink.target).get();
3728
+ if (typeof decoded === "string" && decoded.length > 0) {
3729
+ flow.creationHint = decoded;
3730
+ }
3340
3731
  }
3341
3732
  catch {
3342
- // Ignore parse errors
3733
+ // Ignore parse errors — leave unset.
3734
+ }
3735
+ }
3736
+ // Find flow-level `context` — same ModelQuery-shape guard as
3737
+ // FlowState.requires (rejects `[null]`, `[{}]`, non-string
3738
+ // `className`).
3739
+ const contextLink = links.find(l => l.source === flowUri && l.predicate === "ad4m://context");
3740
+ if (contextLink) {
3741
+ try {
3742
+ const jsonStr = contextLink.target.replace(/^literal:\/\/string:|^literal:string:/, "");
3743
+ const parsed = JSON.parse(decodeURIComponent(jsonStr));
3744
+ if (Array.isArray(parsed) && parsed.every(isModelQueryShape)) {
3745
+ flow.context = parsed;
3746
+ }
3747
+ }
3748
+ catch {
3749
+ // Ignore parse errors — leave unset.
3750
+ }
3751
+ }
3752
+ // Find flow-level `consensusRule`. Reject malformed literals
3753
+ // (missing `n`, non-integer `n`, invalid `fromRole`) so the runtime
3754
+ // engine never has to defensively re-validate a stored rule.
3755
+ const consensusRuleLink = links.find(l => l.source === flowUri && l.predicate === "ad4m://consensusRule");
3756
+ if (consensusRuleLink) {
3757
+ try {
3758
+ const jsonStr = consensusRuleLink.target.replace(/^literal:\/\/string:|^literal:string:/, "");
3759
+ const parsed = JSON.parse(decodeURIComponent(jsonStr));
3760
+ if (isConsensusRuleShape(parsed)) {
3761
+ flow.consensusRule = parsed;
3762
+ }
3763
+ }
3764
+ catch {
3765
+ // Ignore parse errors — leave unset.
3343
3766
  }
3344
3767
  }
3345
3768
  // Find states
@@ -3356,20 +3779,85 @@ class SHACLFlow {
3356
3779
  // Get state value
3357
3780
  const valueLink = links.find(l => l.source === stateUri && l.predicate === "ad4m://stateValue");
3358
3781
  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) {
3782
+ // Get per-state interpretation hint (optional). Same non-empty-string
3783
+ // guard as the flow-level hint.
3784
+ const hintLink = links.find(l => l.source === stateUri && l.predicate === "ad4m://interpretationHint");
3785
+ let interpretationHint;
3786
+ if (hintLink) {
3363
3787
  try {
3364
- const jsonStr = checkLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
3365
- stateCheck = JSON.parse(decodeURIComponent(jsonStr));
3788
+ const decoded = Literal.fromUrl(hintLink.target).get();
3789
+ if (typeof decoded === "string" && decoded.length > 0) {
3790
+ interpretationHint = decoded;
3791
+ }
3366
3792
  }
3367
3793
  catch {
3368
- // Ignore parse errors
3794
+ // Ignore parse errors — leave unset.
3795
+ }
3796
+ }
3797
+ // Get per-state `requires` guard (optional) — one link carrying a
3798
+ // JSON-encoded ModelQuery[]. Reject arrays whose entries are not
3799
+ // ModelQuery-shaped (missing/non-string `className`, `null`, primitives).
3800
+ const requiresLink = links.find(l => l.source === stateUri && l.predicate === "ad4m://requires");
3801
+ let requires;
3802
+ if (requiresLink) {
3803
+ try {
3804
+ const jsonStr = requiresLink.target.replace(/^literal:\/\/string:|^literal:string:/, "");
3805
+ const parsed = JSON.parse(decodeURIComponent(jsonStr));
3806
+ if (Array.isArray(parsed) && parsed.every(isModelQueryShape)) {
3807
+ requires = parsed;
3808
+ }
3809
+ }
3810
+ catch {
3811
+ // Ignore parse errors — leave requires unset rather than crash
3369
3812
  }
3370
3813
  }
3371
- flow.addState({ name: stateName, value: stateValue, stateCheck });
3814
+ // Get per-state `semanticCheck` hint (optional). Non-empty-string guard.
3815
+ const semanticCheckLink = links.find(l => l.source === stateUri && l.predicate === "ad4m://semanticCheck");
3816
+ let semanticCheck;
3817
+ if (semanticCheckLink) {
3818
+ try {
3819
+ const decoded = Literal.fromUrl(semanticCheckLink.target).get();
3820
+ if (typeof decoded === "string" && decoded.length > 0) {
3821
+ semanticCheck = decoded;
3822
+ }
3823
+ }
3824
+ catch {
3825
+ // Ignore parse errors — leave unset.
3826
+ }
3827
+ }
3828
+ // Get per-state `consensusRule` override (optional). Same shape
3829
+ // guard as the flow-level rule; a malformed literal (missing `n`,
3830
+ // non-integer, invalid `fromRole`) leaves the field unset.
3831
+ const stateConsensusLink = links.find(l => l.source === stateUri && l.predicate === "ad4m://consensusRule");
3832
+ let consensusRule;
3833
+ if (stateConsensusLink) {
3834
+ try {
3835
+ const jsonStr = stateConsensusLink.target.replace(/^literal:\/\/string:|^literal:string:/, "");
3836
+ const parsed = JSON.parse(decodeURIComponent(jsonStr));
3837
+ if (isConsensusRuleShape(parsed)) {
3838
+ consensusRule = parsed;
3839
+ }
3840
+ }
3841
+ catch {
3842
+ // Ignore parse errors — leave unset.
3843
+ }
3844
+ }
3845
+ flow.addState({
3846
+ name: stateName,
3847
+ value: stateValue,
3848
+ ...(interpretationHint !== undefined ? { interpretationHint } : {}),
3849
+ ...(requires !== undefined ? { requires } : {}),
3850
+ ...(semanticCheck !== undefined ? { semanticCheck } : {}),
3851
+ ...(consensusRule !== undefined ? { consensusRule } : {}),
3852
+ });
3372
3853
  }
3854
+ // Perspective link storage does not preserve insertion order — `hasState`
3855
+ // links come back in arbitrary order from the graph, so `flow.states[0]`
3856
+ // was randomly one of the round-tripped states. Sort by `value` ascending
3857
+ // so the "initial state = states[0]" convention (used by
3858
+ // `FlowInstance.start`) survives a fromGraph round trip.
3859
+ // The `states` getter returns a defensive copy, so mutate `_states` directly.
3860
+ flow._states.sort((a, b) => a.value - b.value);
3373
3861
  // Find transitions
3374
3862
  const transitionLinks = links.filter(l => l.source === flowUri && l.predicate === "ad4m://hasTransition");
3375
3863
  for (const transitionLink of transitionLinks) {
@@ -3405,13 +3893,31 @@ class SHACLFlow {
3405
3893
  * Convert to JSON representation
3406
3894
  */
3407
3895
  toJSON() {
3896
+ // Per-state metadata is optional; strip empty strings / empty arrays so
3897
+ // json.states[i] agrees with what toLinks() would materialise (a state
3898
+ // constructed with `interpretationHint: ""` produces no predicate, so
3899
+ // JSON must not carry the empty field either).
3900
+ const sanitizedStates = this._states.map(s => ({
3901
+ name: s.name,
3902
+ value: s.value,
3903
+ ...(s.interpretationHint ? { interpretationHint: s.interpretationHint } : {}),
3904
+ ...(s.requires && s.requires.length > 0 ? { requires: s.requires } : {}),
3905
+ ...(s.semanticCheck ? { semanticCheck: s.semanticCheck } : {}),
3906
+ ...(s.consensusRule ? { consensusRule: s.consensusRule } : {})
3907
+ }));
3408
3908
  return {
3409
3909
  name: this.name,
3410
3910
  namespace: this.namespace,
3411
- flowable: this.flowable,
3412
- startAction: this.startAction,
3413
- states: this._states,
3414
- transitions: this._transitions
3911
+ states: sanitizedStates,
3912
+ transitions: this._transitions,
3913
+ // Empty strings / empty arrays treated as unset — same semantics
3914
+ // as the toLinks path, so JSON <-> links round-trips agree.
3915
+ ...(this.interpretationHint ? { interpretationHint: this.interpretationHint } : {}),
3916
+ ...(this.inputTypes.length > 0 ? { inputTypes: this.inputTypes } : {}),
3917
+ ...(this.outputTypes.length > 0 ? { outputTypes: this.outputTypes } : {}),
3918
+ ...(this.creationHint ? { creationHint: this.creationHint } : {}),
3919
+ ...(this.context && this.context.length > 0 ? { context: this.context } : {}),
3920
+ ...(this.consensusRule ? { consensusRule: this.consensusRule } : {})
3415
3921
  };
3416
3922
  }
3417
3923
  /**
@@ -3419,10 +3925,49 @@ class SHACLFlow {
3419
3925
  */
3420
3926
  static fromJSON(json) {
3421
3927
  const flow = new SHACLFlow(json.name, json.namespace);
3422
- flow.flowable = json.flowable || "any";
3423
- flow.startAction = json.startAction || [];
3928
+ // Non-empty-string guard — mirrors the toLinks-side reader.
3929
+ if (typeof json.interpretationHint === "string" && json.interpretationHint.length > 0) {
3930
+ flow.interpretationHint = json.interpretationHint;
3931
+ }
3932
+ // Typed I/O (design §4.1). Same string[]/ModelQuery[] shape guards
3933
+ // as the fromLinks path — malformed payloads leave defaults untouched.
3934
+ if (Array.isArray(json.inputTypes) &&
3935
+ json.inputTypes.every((v) => typeof v === "string" && v.length > 0)) {
3936
+ flow.inputTypes = json.inputTypes;
3937
+ }
3938
+ if (Array.isArray(json.outputTypes) &&
3939
+ json.outputTypes.every((v) => typeof v === "string" && v.length > 0)) {
3940
+ flow.outputTypes = json.outputTypes;
3941
+ }
3942
+ if (typeof json.creationHint === "string" && json.creationHint.length > 0) {
3943
+ flow.creationHint = json.creationHint;
3944
+ }
3945
+ if (Array.isArray(json.context) && json.context.every(isModelQueryShape)) {
3946
+ flow.context = json.context;
3947
+ }
3948
+ if (isConsensusRuleShape(json.consensusRule)) {
3949
+ flow.consensusRule = json.consensusRule;
3950
+ }
3424
3951
  for (const state of json.states || []) {
3425
- flow.addState(state);
3952
+ // Same validation as the toLinks path: reject malformed optional fields
3953
+ // rather than let them poison downstream consumers.
3954
+ const sanitized = {
3955
+ name: state.name,
3956
+ value: state.value,
3957
+ };
3958
+ if (typeof state.interpretationHint === "string" && state.interpretationHint.length > 0) {
3959
+ sanitized.interpretationHint = state.interpretationHint;
3960
+ }
3961
+ if (Array.isArray(state.requires) && state.requires.every(isModelQueryShape)) {
3962
+ sanitized.requires = state.requires;
3963
+ }
3964
+ if (typeof state.semanticCheck === "string" && state.semanticCheck.length > 0) {
3965
+ sanitized.semanticCheck = state.semanticCheck;
3966
+ }
3967
+ if (isConsensusRuleShape(state.consensusRule)) {
3968
+ sanitized.consensusRule = state.consensusRule;
3969
+ }
3970
+ flow.addState(sanitized);
3426
3971
  }
3427
3972
  for (const transition of json.transitions || []) {
3428
3973
  flow.addTransition(transition);
@@ -3442,7 +3987,7 @@ var __classPrivateFieldGet$a = (undefined && undefined.__classPrivateFieldGet) |
3442
3987
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
3443
3988
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
3444
3989
  };
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;
3990
+ var _QuerySubscriptionProxy_instances, _QuerySubscriptionProxy_uuid, _QuerySubscriptionProxy_subscriptionId, _QuerySubscriptionProxy_client, _QuerySubscriptionProxy_callbacks, _QuerySubscriptionProxy_keepaliveTimer, _QuerySubscriptionProxy_unsubscribe, _QuerySubscriptionProxy_reconnectUnsub, _QuerySubscriptionProxy_latestResult, _QuerySubscriptionProxy_disposed, _QuerySubscriptionProxy_initialized, _QuerySubscriptionProxy_initResolve, _QuerySubscriptionProxy_initReject, _QuerySubscriptionProxy_initTimeoutId, _QuerySubscriptionProxy_query, _QuerySubscriptionProxy_generation, _QuerySubscriptionProxy_deliverResult, _QuerySubscriptionProxy_startKeepalive, _QuerySubscriptionProxy_notifyCallbacks, _PerspectiveProxy_handle, _PerspectiveProxy_client, _PerspectiveProxy_perspectiveLinkAddedCallbacks, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, _PerspectiveProxy_perspectiveSyncStateChangeCallbacks, _PerspectiveProxy_ensuredSubjectClasses;
3446
3991
  /** Extract namespace prefix from a URI (everything up to and including the last / or #) */
3447
3992
  function extractNamespaceFromUri(uri) {
3448
3993
  const hashIdx = uri.lastIndexOf('#');
@@ -3503,6 +4048,7 @@ class QuerySubscriptionProxy {
3503
4048
  _QuerySubscriptionProxy_callbacks.set(this, void 0);
3504
4049
  _QuerySubscriptionProxy_keepaliveTimer.set(this, void 0);
3505
4050
  _QuerySubscriptionProxy_unsubscribe.set(this, void 0);
4051
+ _QuerySubscriptionProxy_reconnectUnsub.set(this, void 0);
3506
4052
  _QuerySubscriptionProxy_latestResult.set(this, void 0);
3507
4053
  _QuerySubscriptionProxy_disposed.set(this, false);
3508
4054
  _QuerySubscriptionProxy_initialized.set(this, void 0);
@@ -3510,6 +4056,15 @@ class QuerySubscriptionProxy {
3510
4056
  _QuerySubscriptionProxy_initReject.set(this, void 0);
3511
4057
  _QuerySubscriptionProxy_initTimeoutId.set(this, void 0);
3512
4058
  _QuerySubscriptionProxy_query.set(this, void 0);
4059
+ // Monotonic token guarding the three concurrent writers of
4060
+ // `#unsubscribe`/`#subscriptionId` (full subscribe() from the keepalive
4061
+ // and init-timeout retry paths, and the reconnect swap handler). Each
4062
+ // writer bumps it on entry and re-checks after every await; a mismatch
4063
+ // means a newer writer took over while we were suspended, so the stale
4064
+ // continuation must back out instead of clobbering the newer state
4065
+ // (worst case otherwise: an overwritten-but-never-called unsubscribe
4066
+ // leaks its callback in ApiClient._wsCallbacks for the client lifetime).
4067
+ _QuerySubscriptionProxy_generation.set(this, 0);
3513
4068
  __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_uuid, uuid, "f");
3514
4069
  __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_query, query, "f");
3515
4070
  __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_client, client, "f");
@@ -3522,6 +4077,26 @@ class QuerySubscriptionProxy {
3522
4077
  }), "f");
3523
4078
  }
3524
4079
  async subscribe() {
4080
+ var _a;
4081
+ // Invalidate any suspended writer (older subscribe() or reconnect
4082
+ // swap parked on an await) — see #generation.
4083
+ const generation = __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_generation, (_a = __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_generation, "f"), ++_a), "f");
4084
+ // Remove any prior reconnect listener FIRST — before we touch
4085
+ // `#unsubscribe`. Rationale: `#unsubscribe()` calls into
4086
+ // `ApiClient.subscribe()`'s deleter, which closes the WebSocket
4087
+ // whenever this query owned the last `_wsCallbacks` entry (and no
4088
+ // RPCs are pending). The subsequent `subscribeQuery()` below then
4089
+ // re-opens a fresh socket, and that fresh `onopen` fires the
4090
+ // reconnect callback set. If the OLD reconnect listener is still
4091
+ // in that set, it re-enters this method, closes the socket again,
4092
+ // reopens again … an endless resubscribe loop. Clearing the
4093
+ // listener up-front breaks the cycle; a fresh listener is
4094
+ // installed at the end of a successful subscribe(), and a
4095
+ // full-retry recovery listener in the catch block on failure.
4096
+ if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_reconnectUnsub, "f")) {
4097
+ __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_reconnectUnsub, "f").call(this);
4098
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_reconnectUnsub, undefined, "f");
4099
+ }
3525
4100
  // Clean up previous subscription attempt if retrying
3526
4101
  if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_unsubscribe, "f")) {
3527
4102
  __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_unsubscribe, "f").call(this);
@@ -3541,19 +4116,22 @@ class QuerySubscriptionProxy {
3541
4116
  // Initialize the query subscription
3542
4117
  let initialResult;
3543
4118
  initialResult = await __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, "f").subscribeQuery(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_query, "f"));
4119
+ // A newer writer (another subscribe() or a reconnect swap) took
4120
+ // over while we awaited — back out without touching shared state,
4121
+ // and release the now-orphaned server-side subscription so it
4122
+ // doesn't linger until its keepalive TTL expires.
4123
+ if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_disposed, "f") || __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_generation, "f") !== generation) {
4124
+ __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, "f").disposeQuerySubscription(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_uuid, "f"), initialResult.subscriptionId)
4125
+ .catch(e => console.error('Error disposing superseded query subscription:', e));
4126
+ return;
4127
+ }
3544
4128
  __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_subscriptionId, initialResult.subscriptionId, "f");
3545
4129
  // Process the initial result immediately for fast UX.
3546
4130
  // The subscribeQuery() RPC call already returns the initial result,
3547
4131
  // so treat that as successful initialization instead of waiting for a
3548
4132
  // follow-up WebSocket update that may never arrive until the query changes.
3549
4133
  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
- }
4134
+ __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_instances, "m", _QuerySubscriptionProxy_deliverResult).call(this, initialResult.result);
3557
4135
  }
3558
4136
  else {
3559
4137
  console.warn('⚠️ No initial result returned from subscribeQuery!');
@@ -3568,21 +4146,7 @@ class QuerySubscriptionProxy {
3568
4146
  }, 30000), "f");
3569
4147
  }
3570
4148
  // 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");
4149
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_unsubscribe, __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, "f").subscribeToQueryUpdates(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_subscriptionId, "f"), (updateResult) => __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_instances, "m", _QuerySubscriptionProxy_deliverResult).call(this, updateResult)), "f");
3586
4150
  }
3587
4151
  catch (error) {
3588
4152
  console.error('Error setting up subscription:', error);
@@ -3592,36 +4156,117 @@ class QuerySubscriptionProxy {
3592
4156
  __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initResolve, undefined, "f");
3593
4157
  __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initReject, undefined, "f");
3594
4158
  }
4159
+ // Restore reconnect recovery before rethrowing. The listener was
4160
+ // removed at the top of this method; without re-installing one
4161
+ // here, a single failed resubscribe (e.g. subscribeQuery timing
4162
+ // out during a network flap) would leave the proxy permanently
4163
+ // dead: the keepalive loop stops itself on resubscribe failure,
4164
+ // and nothing else retries. The recovery listener runs the FULL
4165
+ // subscribe() (not the swap-in-place handler) because after a
4166
+ // failed attempt there is no keepalive loop left to feed the new
4167
+ // server subscription — subscribe() restarts it. This is
4168
+ // loop-safe: in this failed state the proxy owns no
4169
+ // `_wsCallbacks` entry (the old one was unsubscribed at the top
4170
+ // of this method and no new one got registered), so the
4171
+ // subscribe() it triggers has nothing to unsubscribe → the
4172
+ // socket never closes/reopens under it → no re-entrant onopen.
4173
+ if (!__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_disposed, "f") && __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_generation, "f") === generation && __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, "f").onReconnect) {
4174
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_reconnectUnsub, __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, "f").onReconnect(() => {
4175
+ if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_disposed, "f"))
4176
+ return;
4177
+ console.log('WebSocket reconnected — retrying failed subscription for query:', __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_query, "f"));
4178
+ this.subscribe().catch(e => {
4179
+ console.error('Error during subscription retry after reconnect:', e);
4180
+ });
4181
+ }), "f");
4182
+ }
3595
4183
  throw error; // Re-throw so caller knows it failed
3596
4184
  }
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"));
4185
+ // Start keepalive loop
4186
+ __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_instances, "m", _QuerySubscriptionProxy_startKeepalive).call(this, generation);
4187
+ // Register for reconnect notification — on WebSocket reconnect,
4188
+ // immediately re-establish a fresh server-side subscription instead
4189
+ // of waiting up to 30s for the keepalive to fail.
4190
+ //
4191
+ // We deliberately do NOT call `this.subscribe()` here. Full subscribe
4192
+ // runs `#unsubscribe` first, which delegates to `ApiClient.subscribe`'s
4193
+ // deleter — that closes the WebSocket when this query owned the LAST
4194
+ // `_wsCallbacks` entry. The subsequent `subscribeQuery` reopens the
4195
+ // socket, whose fresh `onopen` fires every registered reconnect
4196
+ // callback again → recursion (CodeRabbit's original finding). And
4197
+ // during that close→reopen gap, RPCs in flight from OTHER proxies
4198
+ // fail with `503 WebSocket not connected` (observed in
4199
+ // integration-tests-mcp `should fire onWake when mention uses agent DID`
4200
+ // after PR #899's initial fix — the WakerSubscriptionManager tests
4201
+ // share a wakerClient across cases, so any dying reconnect handler
4202
+ // interferes with sibling subscriptions).
4203
+ //
4204
+ // The correct shape is a swap-in-place: get a new server-side
4205
+ // subscription ID via `subscribeQuery`, register a new client-side
4206
+ // callback FIRST, and only then unsubscribe the old one. That way
4207
+ // `_wsCallbacks.size` never dips to 0 during the transition, so the
4208
+ // socket doesn't close, no reconnect loop, and no cross-proxy 503s.
4209
+ // Any prior listener was already removed at the top of this method
4210
+ // (see the note there for why cleanup must run before `#unsubscribe`,
4211
+ // not here).
4212
+ if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, "f").onReconnect) {
4213
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_reconnectUnsub, __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, "f").onReconnect(async () => {
4214
+ var _a;
4215
+ if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_disposed, "f"))
4216
+ return;
4217
+ // The handler is a writer of `#unsubscribe`/`#subscriptionId`
4218
+ // too, so it takes its own generation — see #generation.
4219
+ const swapGeneration = __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_generation, (_a = __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_generation, "f"), ++_a), "f");
4220
+ console.log('WebSocket reconnected — re-establishing server subscription for query:', __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_query, "f"));
3608
4221
  try {
3609
- await this.subscribe();
3610
- console.log('Subscription reinitialized');
4222
+ const newInitial = await __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, "f").subscribeQuery(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_query, "f"));
4223
+ if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_disposed, "f") || __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_generation, "f") !== swapGeneration) {
4224
+ // A newer writer took over while we awaited — back out
4225
+ // and release the orphaned server-side subscription.
4226
+ __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, "f").disposeQuerySubscription(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_uuid, "f"), newInitial.subscriptionId)
4227
+ .catch(e => console.error('Error disposing superseded query subscription:', e));
4228
+ return;
4229
+ }
4230
+ const newSubId = newInitial.subscriptionId;
4231
+ // Register the NEW client-side callback BEFORE removing the
4232
+ // old one — keeps `_wsCallbacks.size >= 1` across the swap.
4233
+ const newUnsub = __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, "f").subscribeToQueryUpdates(newSubId, (updateResult) => __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_instances, "m", _QuerySubscriptionProxy_deliverResult).call(this, updateResult));
4234
+ const oldUnsub = __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_unsubscribe, "f");
4235
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_unsubscribe, newUnsub, "f");
4236
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_subscriptionId, newSubId, "f");
4237
+ if (oldUnsub)
4238
+ oldUnsub();
4239
+ // Our generation bump invalidated the running keepalive
4240
+ // loop — restart it under our generation so the new
4241
+ // server subscription keeps receiving keepalives.
4242
+ clearTimeout(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_keepaliveTimer, "f"));
4243
+ __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_instances, "m", _QuerySubscriptionProxy_startKeepalive).call(this, swapGeneration);
4244
+ // Deliver the fresh initial result if the server included one
4245
+ // (matches the eager-delivery path in the main subscribe() body).
4246
+ // #deliverResult also clears a still-pending init timeout and
4247
+ // resolves #initialized, keeping this path symmetric with the
4248
+ // update callback in subscribe() — without it, a swap landing
4249
+ // while initialization was pending would leave the 30s init
4250
+ // timer armed and trigger a spurious full resubscribe.
4251
+ if (newInitial.result !== undefined) {
4252
+ __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_instances, "m", _QuerySubscriptionProxy_deliverResult).call(this, newInitial.result);
4253
+ }
3611
4254
  }
3612
- catch (resubscribeError) {
3613
- console.error('Error during resubscription from keepalive:', resubscribeError);
3614
- // Don't schedule another keepalive on resubscribe failure
3615
- return;
4255
+ catch (error) {
4256
+ console.error('Error re-establishing subscription after reconnect:', error);
4257
+ // Our generation bump invalidated the running keepalive
4258
+ // loop; if nothing newer superseded us, restart it so
4259
+ // liveness is preserved — its keepAliveQuery against the
4260
+ // dead old subscription will fail and fall back to a
4261
+ // full subscribe(). The reconnect listener also remains
4262
+ // installed, so a later reconnect retries this handler.
4263
+ if (!__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_disposed, "f") && __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_generation, "f") === swapGeneration) {
4264
+ clearTimeout(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_keepaliveTimer, "f"));
4265
+ __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_instances, "m", _QuerySubscriptionProxy_startKeepalive).call(this, swapGeneration);
4266
+ }
3616
4267
  }
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");
4268
+ }), "f");
4269
+ }
3625
4270
  }
3626
4271
  /** Get the subscription ID for this query subscription
3627
4272
  *
@@ -3694,11 +4339,19 @@ class QuerySubscriptionProxy {
3694
4339
  * will not receive any more updates. The instance should be discarded.
3695
4340
  */
3696
4341
  dispose() {
4342
+ var _a;
3697
4343
  __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_disposed, true, "f");
4344
+ // Invalidate any suspended writer so a mid-flight subscribe() or
4345
+ // reconnect swap backs out instead of resurrecting state.
4346
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_generation, (_a = __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_generation, "f"), _a++, _a), "f");
3698
4347
  clearTimeout(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_keepaliveTimer, "f"));
3699
4348
  if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_unsubscribe, "f")) {
3700
4349
  __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_unsubscribe, "f").call(this);
3701
4350
  }
4351
+ if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_reconnectUnsub, "f")) {
4352
+ __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_reconnectUnsub, "f").call(this);
4353
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_reconnectUnsub, undefined, "f");
4354
+ }
3702
4355
  __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_callbacks, "f").clear();
3703
4356
  if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initTimeoutId, "f")) {
3704
4357
  clearTimeout(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initTimeoutId, "f"));
@@ -3711,7 +4364,58 @@ class QuerySubscriptionProxy {
3711
4364
  }
3712
4365
  }
3713
4366
  }
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) {
4367
+ _QuerySubscriptionProxy_uuid = new WeakMap(), _QuerySubscriptionProxy_subscriptionId = new WeakMap(), _QuerySubscriptionProxy_client = new WeakMap(), _QuerySubscriptionProxy_callbacks = new WeakMap(), _QuerySubscriptionProxy_keepaliveTimer = new WeakMap(), _QuerySubscriptionProxy_unsubscribe = new WeakMap(), _QuerySubscriptionProxy_reconnectUnsub = new WeakMap(), _QuerySubscriptionProxy_latestResult = new WeakMap(), _QuerySubscriptionProxy_disposed = new WeakMap(), _QuerySubscriptionProxy_initialized = new WeakMap(), _QuerySubscriptionProxy_initResolve = new WeakMap(), _QuerySubscriptionProxy_initReject = new WeakMap(), _QuerySubscriptionProxy_initTimeoutId = new WeakMap(), _QuerySubscriptionProxy_query = new WeakMap(), _QuerySubscriptionProxy_generation = new WeakMap(), _QuerySubscriptionProxy_instances = new WeakSet(), _QuerySubscriptionProxy_deliverResult = function _QuerySubscriptionProxy_deliverResult(result) {
4368
+ if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initTimeoutId, "f")) {
4369
+ clearTimeout(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initTimeoutId, "f"));
4370
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initTimeoutId, undefined, "f");
4371
+ }
4372
+ // Resolve the initialization promise (only resolves once)
4373
+ if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initResolve, "f")) {
4374
+ __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initResolve, "f").call(this, true);
4375
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initResolve, undefined, "f"); // Prevent double-resolve
4376
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initReject, undefined, "f");
4377
+ }
4378
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_latestResult, result, "f");
4379
+ __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_instances, "m", _QuerySubscriptionProxy_notifyCallbacks).call(this, result);
4380
+ }, _QuerySubscriptionProxy_startKeepalive = function _QuerySubscriptionProxy_startKeepalive(generation) {
4381
+ const keepaliveLoop = async () => {
4382
+ // Generation check kills orphaned loops: a loop whose
4383
+ // keepAliveQuery was in flight while a newer writer ran is not
4384
+ // cancelled by clearTimeout and would otherwise reschedule
4385
+ // itself alongside the newer loop.
4386
+ if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_disposed, "f") || __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_generation, "f") !== generation)
4387
+ return;
4388
+ try {
4389
+ await __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, "f").keepAliveQuery(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_subscriptionId, "f"));
4390
+ }
4391
+ catch (e) {
4392
+ if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_disposed, "f") || __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_generation, "f") !== generation)
4393
+ return;
4394
+ console.error('Error in keepalive:', e);
4395
+ // try to reinitialize the subscription
4396
+ console.log('Reinitializing subscription for query:', __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_query, "f"));
4397
+ try {
4398
+ await this.subscribe();
4399
+ console.log('Subscription reinitialized');
4400
+ }
4401
+ catch (resubscribeError) {
4402
+ console.error('Error during resubscription from keepalive:', resubscribeError);
4403
+ // Don't schedule another keepalive on resubscribe failure.
4404
+ // Recovery is not lost: the failed subscribe() installed a
4405
+ // reconnect listener that retries the full subscribe.
4406
+ return;
4407
+ }
4408
+ // subscribe() succeeded and started its own keepalive loop
4409
+ // under a new generation — this loop is done.
4410
+ return;
4411
+ }
4412
+ // Schedule next keepalive if still the active generation
4413
+ if (!__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_disposed, "f") && __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_generation, "f") === generation) {
4414
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_keepaliveTimer, setTimeout(keepaliveLoop, 30000), "f");
4415
+ }
4416
+ };
4417
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_keepaliveTimer, setTimeout(keepaliveLoop, 30000), "f");
4418
+ }, _QuerySubscriptionProxy_notifyCallbacks = function _QuerySubscriptionProxy_notifyCallbacks(result) {
3715
4419
  for (const callback of __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_callbacks, "f")) {
3716
4420
  try {
3717
4421
  callback(result);
@@ -3910,8 +4614,8 @@ class PerspectiveProxy {
3910
4614
  * });
3911
4615
  * ```
3912
4616
  */
3913
- async get(query) {
3914
- return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").queryLinks(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, query);
4617
+ async get(query, options) {
4618
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").queryLinks(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, query, options);
3915
4619
  }
3916
4620
  /**
3917
4621
  * Runs generic LLM interpretation over a conversation transcript, turning it
@@ -3926,8 +4630,38 @@ class PerspectiveProxy {
3926
4630
  * @param basePrefix URI namespace for new instance identities, e.g. `soa://ext/`
3927
4631
  * @param classes local names of the subject classes to extract into; omit for all
3928
4632
  */
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);
4633
+ async runInterpretation(transcript, basePrefix, classes, options) {
4634
+ // Grouped into an options bag rather than continuing the client's positional list.
4635
+ // The scopes were already unreachable from here for that reason, and a fourth, fifth and
4636
+ // sixth positional parameter would have made `undefined, undefined, { … }` the normal way
4637
+ // to ask for the only one of them most callers want.
4638
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").runInterpretation(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, transcript, basePrefix, classes, options?.existingScope, options?.mintScope, options?.observe);
4639
+ }
4640
+ /**
4641
+ * Harness-dispatched interpretation pass over this perspective (design v3
4642
+ * §6 — the tool-calling counterpart to {@link runInterpretation}). The LLM
4643
+ * sees a live per-class tool surface (`{Class}_query`, `{Class}_get`,
4644
+ * `{Class}_propose_create`, `{Class}_propose_link_child`, …) and drives
4645
+ * the extraction via tool calls; buffered proposals drain through the
4646
+ * same overlay gate the single-shot path uses.
4647
+ *
4648
+ * @param transcript ordered `{ speaker, text }` turns
4649
+ * @param basePrefix URI namespace new instance identities are minted under
4650
+ * @param maxToolCalls upper bound on tool calls the harness will make in
4651
+ * one pass (must be > 0 — use {@link runInterpretation} for the
4652
+ * classic single-shot path)
4653
+ * @param classes local names of the subject classes to extract into; omit for all
4654
+ * @param modelOverride optional model override; omit for the default LLM
4655
+ */
4656
+ async runInterpretationWithHarness(transcript, basePrefix, maxToolCalls, classes, modelOverride,
4657
+ // Optional live-debug observability. When both `observationId` and
4658
+ // `emitDebugEvents` are supplied, every dispatched tool call fires
4659
+ // `ToolCall` + `ToolResult` events on the `auto-processor-event`
4660
+ // topic keyed by `observationId`. Subscribe with
4661
+ // {@link addAutoProcessorEventListener} to render the harness loop
4662
+ // live in a UI. Absent = fast headless path (no telemetry cost).
4663
+ observationId, emitDebugEvents) {
4664
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").runInterpretationWithHarness(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, transcript, basePrefix, maxToolCalls, classes, modelOverride, undefined, observationId, emitDebugEvents);
3931
4665
  }
3932
4666
  /**
3933
4667
  * Register a neighbourhood auto-processor on this perspective. The executor
@@ -3938,6 +4672,24 @@ class PerspectiveProxy {
3938
4672
  async addAutoProcessor(config) {
3939
4673
  return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").addAutoProcessor(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, config);
3940
4674
  }
4675
+ /**
4676
+ * Stop an auto-processor by deleting its config.
4677
+ *
4678
+ * The registration is data — the watch loop reads the processor set back out of the
4679
+ * perspective's graph on every tick — so deleting the config is what stops it, and there is
4680
+ * nothing else to unregister. The config is `Shared`, so this stops the processor for the
4681
+ * neighbourhood rather than only for this peer.
4682
+ *
4683
+ * Resolves `true` when there was a processor to remove and `false` when there was not; a
4684
+ * processor another peer has already removed is not an error.
4685
+ *
4686
+ * The processor's `InterpretationRun` nodes stay: they are the record of what it did and the
4687
+ * processed-turn cursor, so a processor later registered under the same id resumes where this
4688
+ * one left off rather than re-reading every turn.
4689
+ */
4690
+ async removeAutoProcessor(processorId) {
4691
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").removeAutoProcessor(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, processorId);
4692
+ }
3941
4693
  /**
3942
4694
  * Pending interpretation overlays on this perspective — LLM suggestions the
3943
4695
  * §4 divergence gate staged rather than applied, awaiting human accept/reject.
@@ -3998,8 +4750,8 @@ class PerspectiveProxy {
3998
4750
  * `);
3999
4751
  * ```
4000
4752
  */
4001
- async infer(query) {
4002
- return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").queryProlog(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, query);
4753
+ async infer(query, options) {
4754
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").queryProlog(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, query, options);
4003
4755
  }
4004
4756
  /**
4005
4757
  * Executes a SPARQL query against the perspective's link cache.
@@ -4009,19 +4761,25 @@ class PerspectiveProxy {
4009
4761
  * Mutating operations (DELETE, UPDATE, INSERT, CREATE, DROP, DEFINE, etc.) are
4010
4762
  * blocked for security reasons. Use the perspective's add/remove methods to modify links.
4011
4763
  *
4012
- * @param query - SPARQL query string (read-only operations only)
4013
- * @returns Query results as parsed JSON
4014
- *
4015
- * Executes a SPARQL query against the perspective's RDF (Oxigraph) store.
4764
+ * **Cancellation:** Pass `{ signal }` from an `AbortController` to abort
4765
+ * an in-flight query. The executor receives `request.cancel` over the
4766
+ * WebSocket and short-circuits the JSON reply. Caveat: Oxigraph itself
4767
+ * cannot be interrupted mid-evaluation, so an already-running scan will
4768
+ * keep its blocking thread busy until it completes; what's saved is the
4769
+ * serialise + network + client-deserialise tax on the result. Aborted
4770
+ * calls reject with `DOMException('Aborted', 'AbortError')` — match
4771
+ * `fetch()` for handling. Cached results bypass the round-trip entirely
4772
+ * and are returned synchronously, ignoring the signal.
4016
4773
  *
4017
- * @param query - SPARQL query string
4774
+ * @param query - SPARQL query string (read-only operations only)
4775
+ * @param options - Optional call options (e.g. AbortSignal for cancellation)
4018
4776
  * @returns Query results as parsed JSON
4019
4777
  */
4020
- async querySparql(query) {
4778
+ async querySparql(query, options) {
4021
4779
  const cached = getCachedResult(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, query);
4022
4780
  if (cached !== undefined)
4023
4781
  return cached;
4024
- const result = await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").querySparql(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, query);
4782
+ const result = await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").querySparql(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, query, options);
4025
4783
  setCachedResult(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, query, result);
4026
4784
  return result;
4027
4785
  }
@@ -4036,8 +4794,43 @@ class PerspectiveProxy {
4036
4794
  * @param queryJson - Structured query as JSON string
4037
4795
  * @returns Object with `instances` array and `totalCount`
4038
4796
  */
4039
- async modelQuery(className, queryJson) {
4040
- return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").modelQuery(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, className, queryJson);
4797
+ async modelQuery(className, queryJson, options) {
4798
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").modelQuery(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, className, queryJson, options);
4799
+ }
4800
+ /** Resolve each URI to the names of every subject class it is an instance of.
4801
+ *
4802
+ * The counterpart of {@link isSubjectInstance}, which asks the same question
4803
+ * one class at a time. Without this, finding the class of an arbitrary URI
4804
+ * meant looping over every registered class — a round trip each — and doing
4805
+ * it again for every URI.
4806
+ *
4807
+ * Class membership in AD4M is structural — a URI belongs to a class when it
4808
+ * carries that class's flags and required properties — so membership is **not
4809
+ * exclusive**: an instance conforms to its parent classes, and to any
4810
+ * unrelated class whose required set happens to be a subset of what it
4811
+ * carries. Every match is returned.
4812
+ *
4813
+ * The list is ordered **most specific first**, meaning by the number of
4814
+ * triples the class requires — a subclass requires everything its parent does
4815
+ * and more — with ties broken alphabetically so that every peer answers
4816
+ * identically. A caller that can only act on one class should take
4817
+ * `classes[0]`, but that head is only a heuristic: it is arbitrary between two
4818
+ * unrelated classes requiring the same number of triples, which is exactly
4819
+ * the case the full list exists to expose.
4820
+ *
4821
+ * A URI is **absent from the result** when no *registered* class matched it.
4822
+ * That covers two situations, and nothing here separates them: the URI may
4823
+ * not be a subject instance at all, or it may be an instance of a class this
4824
+ * perspective has not registered. Absence is used rather than an empty list
4825
+ * because an empty list would claim the stronger thing — that the URI belongs
4826
+ * to no class — which this cannot know.
4827
+ *
4828
+ * @param uris The expression URIs to classify.
4829
+ */
4830
+ async subjectClassesOf(uris) {
4831
+ if (uris.length === 0)
4832
+ return {};
4833
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").subjectClassesOf(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, uris);
4041
4834
  }
4042
4835
  /**
4043
4836
  * Evaluate property getters for a batch of instances in a single RPC call.
@@ -4373,116 +5166,48 @@ class PerspectiveProxy {
4373
5166
  }
4374
5167
  });
4375
5168
  }
4376
- /** Returns all Social DNA flows that can be started from the given expression */
5169
+ /**
5170
+ * Returns all Social DNA flows that can be started from the given expression.
5171
+ *
5172
+ * Post-`flowable` retirement: a flow is a candidate iff its `inputTypes`
5173
+ * declaration is compatible with the expression. Matching rules:
5174
+ * - Empty `inputTypes` or one containing the `"any"` wildcard → always
5175
+ * matches (same behaviour as the legacy `flowable === "any"` case).
5176
+ * - Otherwise, at least one of the expression's registered subject-class
5177
+ * URIs (resolved via {@link subjectClassesOf}) must appear in
5178
+ * `inputTypes`. This is the concrete-type match the design doc's §5
5179
+ * spawn engine calls for; without it, a flow declaring
5180
+ * `inputTypes: ["Task"]` was previously *never* returned by
5181
+ * `availableFlows("some-task-uri")` — the entire point of typed
5182
+ * flows was silently unreachable (James PR #929 J#3).
5183
+ *
5184
+ * The expression is classified against the perspective's registered
5185
+ * classes only. An expression whose class is not registered on this
5186
+ * perspective matches no typed flow (absence, not falsehood — same
5187
+ * discipline as {@link subjectClassesOf}); typed flows requiring
5188
+ * unknown classes are still returned to their untyped-caller peers.
5189
+ */
4377
5190
  async availableFlows(exprAddr) {
4378
5191
  const allFlowNames = await this.sdnaFlows();
5192
+ if (allFlowNames.length === 0)
5193
+ return [];
5194
+ const classesOf = await this.subjectClassesOf([exprAddr]);
5195
+ const exprClasses = classesOf[exprAddr] ?? [];
4379
5196
  const available = [];
4380
5197
  for (const name of allFlowNames) {
4381
5198
  const flow = await this.getFlow(name);
4382
5199
  if (!flow)
4383
5200
  continue;
4384
- if (flow.flowable === "any") {
5201
+ if (flow.inputTypes.length === 0 || flow.inputTypes.includes("any")) {
4385
5202
  available.push(name);
5203
+ continue;
4386
5204
  }
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
- }
5205
+ if (exprClasses.some(cls => flow.inputTypes.includes(cls))) {
5206
+ available.push(name);
4399
5207
  }
4400
5208
  }
4401
5209
  return available;
4402
5210
  }
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
5211
  /** Returns the perspective's Social DNA code
4487
5212
  * This will return all SDNA code elements in an array.
4488
5213
  */
@@ -4662,111 +5387,45 @@ class PerspectiveProxy {
4662
5387
  await this.addLinks(allLinks);
4663
5388
  }
4664
5389
  /**
4665
- * Retrieve a SHACL shape by name from this Perspective
5390
+ * Retrieve a SHACL shape by name from this Perspective (one RPC call).
5391
+ * The executor resolves the full shape (including property sub-shapes)
5392
+ * in-process and returns link triples for client-side reconstruction.
4666
5393
  */
4667
5394
  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) {
5395
+ const result = await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").getShacl(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, name);
5396
+ if (!result)
4675
5397
  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);
5398
+ return SHACLShape.fromLinks(result.links, result.shapeUri);
4712
5399
  }
4713
5400
  /**
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.
5401
+ * List the names of every SHACL shape stored in this Perspective (one RPC call).
4719
5402
  */
4720
5403
  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)];
5404
+ return __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").getShaclNames(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid);
4733
5405
  }
4734
5406
  /**
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.
5407
+ * Resolve a shape's `sh:targetClass` by name (one RPC call).
5408
+ *
5409
+ * `PerspectiveClient.getShaclTargetClass` now returns `undefined` on
5410
+ * "not found" already (see review r3897752023 — the null→undefined
5411
+ * coercion used to happen here and be duplicated one layer down),
5412
+ * so this method is a pure passthrough.
4741
5413
  */
4742
5414
  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;
5415
+ return __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").getShaclTargetClass(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, name);
4754
5416
  }
4755
5417
  /**
4756
- * Get all SHACL shapes stored in this Perspective
5418
+ * Get all SHACL shapes stored in this Perspective (one RPC call).
5419
+ * The executor resolves all shapes in-process and returns them in bulk.
4757
5420
  */
4758
5421
  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);
5422
+ const entries = await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").getAllShacl(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid);
5423
+ return entries
5424
+ .map(({ name, shapeUri, links }) => {
5425
+ const shape = SHACLShape.fromLinks(links, shapeUri);
5426
+ return shape ? { name, shape } : null;
5427
+ })
5428
+ .filter((s) => s !== null);
4770
5429
  }
4771
5430
  /**
4772
5431
  * **Recommended way to add Flow definitions.**
@@ -4781,28 +5440,26 @@ class PerspectiveProxy {
4781
5440
  * ```typescript
4782
5441
  * import { SHACLFlow } from '@coasys/ad4m';
4783
5442
  *
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
- * });
5443
+ * const deliveryFlow = new SHACLFlow('Delivery', 'delivery://');
5444
+ * deliveryFlow.inputTypes = ['Task'];
5445
+ * deliveryFlow.interpretationHint =
5446
+ * 'Advance a Task through delivery: Identified → Scoped → InProgress → Review → Done.';
5447
+ *
5448
+ * deliveryFlow.addState({ name: 'Identified', value: 0 });
5449
+ * deliveryFlow.addState({ name: 'Scoped', value: 1 });
5450
+ * deliveryFlow.addState({ name: 'InProgress', value: 2 });
5451
+ * deliveryFlow.addState({ name: 'Review', value: 3 });
5452
+ * deliveryFlow.addState({ name: 'Done', value: 4 });
5453
+ *
5454
+ * deliveryFlow.addTransition({ actionName: 'Scope', fromState: 'Identified', toState: 'Scoped', actions: [] });
5455
+ * deliveryFlow.addTransition({ actionName: 'Start', fromState: 'Scoped', toState: 'InProgress', actions: [] });
5456
+ * deliveryFlow.addTransition({ actionName: 'Submit', fromState: 'InProgress', toState: 'Review', actions: [] });
5457
+ * deliveryFlow.addTransition({ actionName: 'Accept', fromState: 'Review', toState: 'Done', actions: [] });
4804
5458
  *
4805
- * await perspective.addFlow('TODO', todoFlow);
5459
+ * // Optional: n distinct DIDs must co-sign a proposal before it fires.
5460
+ * deliveryFlow.consensusRule = { n: 2 };
5461
+ *
5462
+ * await perspective.addFlow('Delivery', deliveryFlow);
4806
5463
  * ```
4807
5464
  */
4808
5465
  async addFlow(name, flow) {
@@ -4847,7 +5504,7 @@ class PerspectiveProxy {
4847
5504
  return null;
4848
5505
  }
4849
5506
  const flowUri = flowUriLinks[0].data.target;
4850
- // Fetch flow-level links (hasState, hasTransition, flowable, startAction)
5507
+ // Fetch flow-level links (hasState, hasTransition, startAction, inputTypes/outputTypes/…)
4851
5508
  const flowLevelLinks = await this.get(new LinkQuery({ source: flowUri }));
4852
5509
  // Collect state and transition URIs, then fetch their child links
4853
5510
  const childUris = flowLevelLinks
@@ -4913,7 +5570,9 @@ class PerspectiveProxy {
4913
5570
  * with the properties of the subject class.
4914
5571
  * @param exprAddr The address of the expression to be turned into a subject instance
4915
5572
  * @param initialValues Optional initial values for properties. If provided, these will be
4916
- * merged with constructor actions for better performance.
5573
+ * merged with constructor actions for better performance. A collection property accepts
5574
+ * an array value and stores one entry per element; scalar properties store arrays/objects
5575
+ * as a single JSON value.
4917
5576
  * @param batchId Optional batch ID for grouping operations. If provided, returns the expression address
4918
5577
  * instead of the subject proxy since the subject won't exist until the batch is committed.
4919
5578
  * @returns A proxy object for the created subject, or just the expression address if in batch mode
@@ -5700,7 +6359,7 @@ class PerspectiveClient {
5700
6359
  async publishSnapshotByUUID(uuid) {
5701
6360
  return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.publishSnapshot', { uuid });
5702
6361
  }
5703
- async queryLinks(uuid, query) {
6362
+ async queryLinks(uuid, query, options) {
5704
6363
  const params = { uuid };
5705
6364
  if (query.source)
5706
6365
  params.source = query.source;
@@ -5714,14 +6373,14 @@ class PerspectiveClient {
5714
6373
  params.untilDate = query.untilDate instanceof Date ? query.untilDate.toISOString() : String(query.untilDate);
5715
6374
  if (query.limit !== undefined)
5716
6375
  params.limit = query.limit;
5717
- return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.queryLinks', params);
6376
+ return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.queryLinks', params, options);
5718
6377
  }
5719
- async queryProlog(uuid, query) {
5720
- const result = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.queryProlog', { uuid, query });
6378
+ async queryProlog(uuid, query, options) {
6379
+ const result = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.queryProlog', { uuid, query }, options);
5721
6380
  return JSON.parse(result);
5722
6381
  }
5723
- async querySparql(uuid, query) {
5724
- const result = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.querySparql', { uuid, engine: 'sparql', query });
6382
+ async querySparql(uuid, query, options) {
6383
+ const result = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.querySparql', { uuid, engine: 'sparql', query }, options);
5725
6384
  return JSON.parse(result);
5726
6385
  }
5727
6386
  async subscribeQuery(uuid, query) {
@@ -5761,10 +6420,13 @@ class PerspectiveClient {
5761
6420
  }
5762
6421
  return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.disposeQuery', { uuid, subscriptionId });
5763
6422
  }
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 });
6423
+ async modelQuery(uuid, className, queryJson, options) {
6424
+ const resultJson = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.modelQuery', { uuid, class_name: className, query_json: queryJson }, options);
5766
6425
  return JSON.parse(resultJson);
5767
6426
  }
6427
+ async subjectClassesOf(uuid, uris) {
6428
+ return await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.subjectClassesOf', { uuid, uris });
6429
+ }
5768
6430
  async evaluateGetters(uuid, className, instanceIds, propertyNames) {
5769
6431
  const resultJson = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.evaluateGetters', {
5770
6432
  uuid,
@@ -5822,9 +6484,55 @@ class PerspectiveClient {
5822
6484
  * `mintScope.id` via its predicate (upserts of pre-existing instances
5823
6485
  * are NOT re-parented — same rule as the watcher).
5824
6486
  */
5825
- async runInterpretation(uuid, transcript, basePrefix, classes, existingScope, mintScope) {
6487
+ async runInterpretation(uuid, transcript, basePrefix, classes, existingScope, mintScope, observe) {
5826
6488
  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);
6489
+ return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.runInterpretation', {
6490
+ uuid, transcript, basePrefix, classes, existingScope, mintScope,
6491
+ // Spread rather than always-present, so a client talking to a pre-#903
6492
+ // executor sends exactly the params it sent before. `serde` would ignore
6493
+ // the extra keys anyway; keeping the wire identical means a bug report
6494
+ // from an older node cannot be about these.
6495
+ ...(observe ? {
6496
+ observationId: observe.observationId,
6497
+ emitDebugEvents: observe.emitDebugEvents ?? false,
6498
+ } : {}),
6499
+ }, { timeoutMs: RUN_INTERPRETATION_TIMEOUT_MS });
6500
+ }
6501
+ /**
6502
+ * Tool-calling counterpart to {@link runInterpretation}. The LLM sees a
6503
+ * live per-class tool surface (`{Class}_query`, `{Class}_propose_create`,
6504
+ * `{Class}_propose_link_child`, …) and drives the extraction via tool
6505
+ * calls; buffered proposals drain through the same overlay gate the
6506
+ * single-shot path uses.
6507
+ *
6508
+ * `maxToolCalls` bounds the loop and MUST be > 0 — zero would collapse
6509
+ * the harness to a no-op final-answer step; use {@link runInterpretation}
6510
+ * for the classic single-shot path.
6511
+ *
6512
+ * Same 20-minute RPC timeout as the single-shot path — an LLM loop
6513
+ * that calls several tools can legitimately take longer than one plain
6514
+ * generation.
6515
+ */
6516
+ async runInterpretationWithHarness(uuid, transcript, basePrefix, maxToolCalls, classes, modelOverride, existingScope,
6517
+ // Optional live-debug event surface — same shape/semantics as the
6518
+ // single-shot `runInterpretation`. `observationId` names the
6519
+ // `processor_id` + `batch_key` on emitted `ToolCall` / `ToolResult`
6520
+ // events so a subscribed UI can correlate them to this pass.
6521
+ // `emitDebugEvents` is a dead-letter without an observationId
6522
+ // (nothing to key against); the server gates on both.
6523
+ observationId, emitDebugEvents) {
6524
+ const RUN_INTERPRETATION_TIMEOUT_MS = 20 * 60 * 1000;
6525
+ return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.runInterpretationWithHarness', {
6526
+ uuid,
6527
+ transcript,
6528
+ basePrefix,
6529
+ maxToolCalls,
6530
+ classes,
6531
+ modelOverride,
6532
+ existingScope,
6533
+ observationId,
6534
+ emitDebugEvents,
6535
+ }, { timeoutMs: RUN_INTERPRETATION_TIMEOUT_MS });
5828
6536
  }
5829
6537
  /**
5830
6538
  * Register a neighbourhood auto-processor on this perspective. The executor's
@@ -5837,6 +6545,10 @@ class PerspectiveClient {
5837
6545
  async addAutoProcessor(uuid, config) {
5838
6546
  return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.addAutoProcessor', { uuid, ...config });
5839
6547
  }
6548
+ /** Delete an auto-processor's config. `false` when there was none to delete. */
6549
+ async removeAutoProcessor(uuid, processorId) {
6550
+ return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.removeAutoProcessor', { uuid, processorId });
6551
+ }
5840
6552
  /** Pending interpretation overlays (LLM suggestions awaiting human accept/reject). */
5841
6553
  async interpretationOverlays(uuid) {
5842
6554
  return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.interpretationOverlays', { uuid });
@@ -5919,6 +6631,43 @@ class PerspectiveClient {
5919
6631
  async getSubjectData(uuid, subjectClass, expressionAddress) {
5920
6632
  return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.getSubjectData', { uuid, subjectClass, expressionAddress });
5921
6633
  }
6634
+ // ── SHACL resolution (server-side) ─────────────────────────────────────────
6635
+ // These methods delegate shape resolution to the executor, which reads links
6636
+ // from its local store in-process. Each call replaces the multi-round-trip
6637
+ // `queryLinks` sequences the old PerspectiveProxy methods performed.
6638
+ /** List the names of every SHACL shape stored in a perspective (one RPC call). */
6639
+ async getShaclNames(uuid) {
6640
+ return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.getShaclNames', { uuid });
6641
+ }
6642
+ /**
6643
+ * Resolve a shape's `sh:targetClass` by name (one RPC call).
6644
+ *
6645
+ * Returns `undefined` when the shape (or its `sh://targetClass` edge) is
6646
+ * absent — unified with `PerspectiveProxy.getShaclTargetClass` so callers
6647
+ * see a single "not found" representation across both layers. The
6648
+ * executor wire format is still `null` (see `perspective.getShaclTargetClass`
6649
+ * in `perspectives_ws.rs`); this method maps that at the boundary rather
6650
+ * than pushing the null one layer further up. PR #935 review r3897752023.
6651
+ */
6652
+ async getShaclTargetClass(uuid, name) {
6653
+ const result = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.getShaclTargetClass', { uuid, name });
6654
+ return result ?? undefined;
6655
+ }
6656
+ /**
6657
+ * Retrieve a single SHACL shape's link triples by name (one RPC call).
6658
+ * Returns `{shapeUri, links}` for reconstruction via `SHACLShape.fromLinks()`,
6659
+ * or `null` if no shape with that name exists.
6660
+ */
6661
+ async getShacl(uuid, name) {
6662
+ return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.getShacl', { uuid, name });
6663
+ }
6664
+ /**
6665
+ * Retrieve all SHACL shapes in one call. Returns an array of
6666
+ * `{name, shapeUri, links}` — one entry per shape (one RPC call).
6667
+ */
6668
+ async getAllShacl(uuid) {
6669
+ return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.getAllShacl', { uuid });
6670
+ }
5922
6671
  // ExpressionClient functions, needed for Subjects:
5923
6672
  async getExpression(expressionURI) {
5924
6673
  return await __classPrivateFieldGet$9(this, _PerspectiveClient_expressionClient, "f").get(expressionURI);
@@ -6040,6 +6789,11 @@ class PerspectiveClient {
6040
6789
  async commitBatch(uuid, batchId) {
6041
6790
  return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.commitBatch', { uuid, batchId });
6042
6791
  }
6792
+ /** Register a callback that fires after a successful WebSocket reconnect.
6793
+ * Passes through to ApiClient.onReconnect(). Returns an unsubscribe function. */
6794
+ onReconnect(callback) {
6795
+ return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").onReconnect(callback);
6796
+ }
6043
6797
  }
6044
6798
  _PerspectiveClient_apiClient = new WeakMap(), _PerspectiveClient_perspectiveAddedCallbacks = new WeakMap(), _PerspectiveClient_perspectiveUpdatedCallbacks = new WeakMap(), _PerspectiveClient_perspectiveRemovedCallbacks = new WeakMap(), _PerspectiveClient_perspectiveSyncStateChangeCallbacks = new WeakMap(), _PerspectiveClient_expressionClient = new WeakMap(), _PerspectiveClient_neighbourhoodClient = new WeakMap(), _PerspectiveClient_aiClient = new WeakMap(), _PerspectiveClient_unsubscribers = new WeakMap(), _PerspectiveClient_linkUnsubscribers = new WeakMap(), _PerspectiveClient_querySubscriptionUnsubscribers = new WeakMap();
6045
6799
 
@@ -14218,9 +14972,12 @@ class AIClient {
14218
14972
  async embed(modelId, text) {
14219
14973
  const aiEmbed = await __classPrivateFieldGet$2(this, _AIClient_apiClient, "f").call('ai.embed', { modelId, text });
14220
14974
  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)));
14975
+ // NB: pako v1 accepts `{ to: 'string' }`, pako v2 wants `{ toText: true }`,
14976
+ // pako v3 also drops that overload from its bundled types. Call the
14977
+ // version-agnostic form (returns Uint8Array) and decode explicitly so
14978
+ // this works regardless of which pako major the lockfile pins.
14979
+ const inflated = pako.inflate(compressed);
14980
+ const decompressed = JSON.parse(new TextDecoder('utf-8').decode(inflated));
14224
14981
  return decompressed;
14225
14982
  }
14226
14983
  async openTranscriptionStream(modelId, streamCallback, params) {
@@ -15903,6 +16660,110 @@ function normalizeValue(value) {
15903
16660
  * Rust endpoint. Recursively converts included relation values (which come
15904
16661
  * back as plain JSON objects) into proper model class instances.
15905
16662
  */
16663
+ /**
16664
+ * Key under which the executor returns a polymorphically-hydrated instance's
16665
+ * concrete class.
16666
+ *
16667
+ * Half of a wire contract: the writer is `SUBJECT_CLASS_KEY` in
16668
+ * `rust-executor/src/perspectives/model_query/relations.rs`, and the two are
16669
+ * separate literals in separate languages. Renaming one alone does not fail to
16670
+ * compile — it degrades to every instance staying plain JSON, which looks
16671
+ * identical to a relation that declared no classes to build.
16672
+ * `tests/js/tests/model/model-polymorphic.test.ts` drives both ends against one
16673
+ * executor, so the drift fails a test rather than a user's query.
16674
+ *
16675
+ * The executor also returns `__subjectClasses`, the whole set this one names the
16676
+ * head of. Nothing here reads it — it rides onto the instance with every other
16677
+ * JSON key, for a caller that wants to know a choice was made.
16678
+ */
16679
+ const SUBJECT_CLASS_KEY = '__subjectClass';
16680
+ /**
16681
+ * Turn on `polymorphic` for every relation that declares it, at every depth of
16682
+ * an include map.
16683
+ *
16684
+ * A relation being heterogeneous is a fact about the data, not about one query,
16685
+ * so the declaration lives on the model and the call site writes
16686
+ * `include: { children: true }`. That has to hold just as much one level down:
16687
+ * in `include: { posts: { include: { children: true } } }`, `children` is a
16688
+ * relation on `Post`, so the walk carries the class it is reading against down
16689
+ * with it. Without that, a nested include of an untyped polymorphic relation
16690
+ * reaches the executor with no shape to resolve and fails the query outright.
16691
+ *
16692
+ * An explicit `polymorphic: false` at any level still wins — `undefined` is the
16693
+ * only state the default fills in.
16694
+ *
16695
+ * The walk stops descending *through* a polymorphic relation, because there is
16696
+ * nothing to descend into: its targets are of several classes by definition, so
16697
+ * no single class's metadata could say what a deeper include means. The
16698
+ * executor resolves those nested includes against each concrete class instead.
16699
+ */
16700
+ function applyPolymorphicIncludeDefaults(includes, ctor) {
16701
+ const relMeta = getRelationsMetadata(ctor);
16702
+ for (const [relName, val] of Object.entries(includes)) {
16703
+ // `$`-prefixed keys are projections, not relations.
16704
+ if (relName.startsWith('$'))
16705
+ continue;
16706
+ const meta = relMeta[relName];
16707
+ if (!meta)
16708
+ continue;
16709
+ let subQuery = val;
16710
+ if (meta.polymorphic) {
16711
+ if (val === true) {
16712
+ subQuery = { polymorphic: true };
16713
+ includes[relName] = subQuery;
16714
+ }
16715
+ else if (typeof val === 'object' && val !== null && subQuery.polymorphic === undefined) {
16716
+ subQuery.polymorphic = true;
16717
+ }
16718
+ // The classes this call site can build are also the classes it wants its
16719
+ // targets read as, so the declaration answers both questions and the call
16720
+ // site repeats neither. Sent as part of the query rather than applied to
16721
+ // the results: a preference in the request is reproducible by anyone who
16722
+ // sends it, where one applied afterwards would make the same data read
16723
+ // differently depending on which classes the caller happened to import.
16724
+ //
16725
+ // It ranks and does not narrow — a target matching none of them still
16726
+ // arrives — so declaring what you can construct never costs you a member
16727
+ // of a relation that is heterogeneous by definition.
16728
+ if (typeof subQuery === 'object' &&
16729
+ subQuery !== null &&
16730
+ subQuery.polymorphic &&
16731
+ subQuery.preferClasses === undefined &&
16732
+ meta.instantiateAs) {
16733
+ const names = (meta.instantiateAs() ?? [])
16734
+ .map((cls) => cls?.className)
16735
+ .filter((name) => typeof name === 'string');
16736
+ if (names.length)
16737
+ subQuery.preferClasses = names;
16738
+ }
16739
+ }
16740
+ if (typeof subQuery !== 'object' || subQuery === null)
16741
+ continue;
16742
+ const nested = subQuery.include;
16743
+ if (!nested || subQuery.polymorphic)
16744
+ continue;
16745
+ // The thunk is only evaluated here, at query time, so a self-referential or
16746
+ // circularly-imported target that is not yet defined costs the nested
16747
+ // default rather than the whole query.
16748
+ let TargetClass;
16749
+ try {
16750
+ TargetClass = meta.target?.();
16751
+ }
16752
+ catch (e) {
16753
+ // A class not yet initialised throws `ReferenceError` from the temporal
16754
+ // dead zone, which is the expected cost of an import cycle and not worth
16755
+ // saying anything about. Anything else — a thunk closing over nothing,
16756
+ // typically — is a broken declaration that would otherwise cost the nested
16757
+ // default in silence, so it gets said out loud.
16758
+ const circularImport = e instanceof ReferenceError;
16759
+ const say = circularImport ? console.debug : console.warn;
16760
+ say(`prepareModelQueryParams: target class unavailable for include '${relName}':`, e);
16761
+ continue;
16762
+ }
16763
+ if (TargetClass)
16764
+ applyPolymorphicIncludeDefaults(nested, TargetClass);
16765
+ }
16766
+ }
15906
16767
  function jsonToModelInstance(ModelClass, perspective, json, include, properties) {
15907
16768
  const instance = new ModelClass(perspective, json.id || json.baseExpression);
15908
16769
  // When a properties projection is active, remove own properties set by the
@@ -15949,9 +16810,62 @@ function jsonToModelInstance(ModelClass, perspective, json, include, properties)
15949
16810
  if (!includeVal)
15950
16811
  continue;
15951
16812
  const meta = relMeta[relName];
15952
- if (!meta?.target)
16813
+ // A polymorphic relation may legitimately declare no target at all —
16814
+ // that is the case it exists for — so it must not be gated on one.
16815
+ if (!meta)
15953
16816
  continue;
15954
- const TargetClass = meta.target();
16817
+ if (!meta.target && !meta.polymorphic)
16818
+ continue;
16819
+ const TargetClass = meta.target?.();
16820
+ // For a polymorphic relation the executor sends each child's concrete
16821
+ // class back on the instance, because it had to know it in order to
16822
+ // hydrate against the right shape at all. What it cannot send is the
16823
+ // constructor, so `instantiateAs` names the classes this side can build
16824
+ // and the name → class map is derived from them: `@Model` records each
16825
+ // class's name on the class itself, so listing the classes and listing
16826
+ // their names would be the same list written twice, free to disagree.
16827
+ //
16828
+ // Built on first use rather than at decoration time, because the thunk
16829
+ // exists to be called late: a class defined further round a circular
16830
+ // import graph is not there yet when the decorator runs.
16831
+ let byClassName;
16832
+ // May resolve to nothing: a polymorphic relation is allowed to declare no
16833
+ // target at all, and the list may not name the class that arrived — it
16834
+ // says what this call site can construct, not what the relation may hold.
16835
+ // The item then stays plain JSON — correct data, carrying its class name
16836
+ // for a caller that wants to dispatch on it — rather than being forced
16837
+ // through a constructor that does not exist.
16838
+ const resolveChildClass = (item) => {
16839
+ if (!meta.polymorphic)
16840
+ return TargetClass;
16841
+ const concrete = item?.[SUBJECT_CLASS_KEY];
16842
+ // No concrete class means this was not read polymorphically after all —
16843
+ // an explicit `polymorphic: false` at the call site — so the relation's
16844
+ // own declared target is the right shape.
16845
+ if (typeof concrete !== 'string')
16846
+ return TargetClass;
16847
+ if (meta.instantiateAs) {
16848
+ if (!byClassName) {
16849
+ byClassName = {};
16850
+ for (const cls of meta.instantiateAs() ?? []) {
16851
+ const name = cls?.className;
16852
+ if (typeof name === 'string')
16853
+ byClassName[name] = cls;
16854
+ }
16855
+ }
16856
+ if (byClassName[concrete])
16857
+ return byClassName[concrete];
16858
+ }
16859
+ // The declared target is not a fallback, and having named no classes to
16860
+ // build does not make it one. Where a relation both declares a target
16861
+ // and reads polymorphically, a child of some third class was hydrated
16862
+ // against *its own* shape, so constructing the declared class over that
16863
+ // JSON produces an instance that answers `instanceof` for a class it is
16864
+ // not, carrying fields that class never declared — the exact
16865
+ // mislabelling polymorphic reads exist to prevent. It fits only when it
16866
+ // is the class the executor named.
16867
+ return TargetClass?.className === concrete ? TargetClass : undefined;
16868
+ };
15955
16869
  const nestedInclude = typeof includeVal === 'object' && includeVal !== null
15956
16870
  ? includeVal.include
15957
16871
  : undefined;
@@ -15961,14 +16875,18 @@ function jsonToModelInstance(ModelClass, perspective, json, include, properties)
15961
16875
  const raw = instance[relName];
15962
16876
  if (Array.isArray(raw)) {
15963
16877
  instance[relName] = raw.map((item) => {
15964
- if (typeof item === 'object' && item !== null && item.id) {
15965
- return jsonToModelInstance(TargetClass, perspective, item, nestedInclude, nestedProperties);
16878
+ const ChildClass = resolveChildClass(item);
16879
+ if (ChildClass && typeof item === 'object' && item !== null && item.id) {
16880
+ return jsonToModelInstance(ChildClass, perspective, item, nestedInclude, nestedProperties);
15966
16881
  }
15967
16882
  return item;
15968
16883
  });
15969
16884
  }
15970
16885
  else if (typeof raw === 'object' && raw !== null && raw.id) {
15971
- instance[relName] = jsonToModelInstance(TargetClass, perspective, raw, nestedInclude, nestedProperties);
16886
+ const ChildClass = resolveChildClass(raw);
16887
+ if (ChildClass) {
16888
+ instance[relName] = jsonToModelInstance(ChildClass, perspective, raw, nestedInclude, nestedProperties);
16889
+ }
15972
16890
  }
15973
16891
  }
15974
16892
  }
@@ -16216,6 +17134,7 @@ class Ad4mModel {
16216
17134
  ...(options.target !== undefined && { target: options.target }),
16217
17135
  ...(options.filter !== undefined && { filter: options.filter }),
16218
17136
  ...(options.where !== undefined && { where: options.where }),
17137
+ ...(options.ordering !== undefined && { ordering: options.ordering }),
16219
17138
  };
16220
17139
  }
16221
17140
  // Fallback: If both structures are empty but a JSON schema is attached, derive from it
@@ -16483,10 +17402,22 @@ class Ad4mModel {
16483
17402
  const current = normalizeValue(this[field]);
16484
17403
  const original = this._snapshot[field];
16485
17404
  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() : [];
17405
+ // For an ordered relation the sequence *is* the state, so a reorder is
17406
+ // the whole change and must mark the field dirty — sorting first would
17407
+ // make `save()` a no-op for the one edit the ordering feature exists to
17408
+ // support.
17409
+ //
17410
+ // Everything else compares order-insensitively, because an unordered
17411
+ // relation is a set: the executor returns its members by link timestamp,
17412
+ // and a caller who assigned the same members in another order has not
17413
+ // changed anything.
17414
+ const ordered = !!metadata.relations[field]?.ordering;
17415
+ const a = Array.isArray(current) ? [...current] : [];
17416
+ const b = Array.isArray(original) ? [...original] : [];
17417
+ if (!ordered) {
17418
+ a.sort();
17419
+ b.sort();
17420
+ }
16490
17421
  if (a.length !== b.length || a.some((v, i) => v !== b[i])) {
16491
17422
  changed.push(field);
16492
17423
  }
@@ -16626,8 +17557,17 @@ class Ad4mModel {
16626
17557
  normalIncludes[key] = val;
16627
17558
  }
16628
17559
  }
16629
- if (Object.keys(normalIncludes).length > 0)
17560
+ // A relation declared `polymorphic` reads that way by default, so the
17561
+ // caller writes `include: { children: true }` and still gets each child
17562
+ // hydrated as the class it actually is. Declaring it on the model rather
17563
+ // than repeating it at every call site is the point — the relation being
17564
+ // heterogeneous is a fact about the data, not about one query — but an
17565
+ // explicit `polymorphic: false` at the call site still wins. Applied at
17566
+ // every depth, since a nested include is a fact about the data too.
17567
+ if (Object.keys(normalIncludes).length > 0) {
17568
+ applyPolymorphicIncludeDefaults(normalIncludes, this);
16630
17569
  queryInput.include = normalIncludes;
17570
+ }
16631
17571
  if (Object.keys(projections).length > 0) {
16632
17572
  // Tag each projection with its target class name so the executor can
16633
17573
  // resolve the target shape through its in-memory cache when applying
@@ -16693,11 +17633,11 @@ class Ad4mModel {
16693
17633
  *
16694
17634
  * @internal
16695
17635
  */
16696
- static async executeModelQuery(perspective, query = {}, classNameOverride) {
17636
+ static async executeModelQuery(perspective, query = {}, classNameOverride, options) {
16697
17637
  // Delegate query input building to the shared prepareModelQueryParams
16698
17638
  // helper. The executor resolves the shape from SHACL server-side.
16699
17639
  const { className, queryJson } = this.prepareModelQueryParams(query, classNameOverride);
16700
- const result = await perspective.modelQuery(className, queryJson);
17640
+ const result = await perspective.modelQuery(className, queryJson, options);
16701
17641
  // Convert JSON instances to model class instances, recursively constructing
16702
17642
  // class instances for any included relations resolved by Rust.
16703
17643
  const instances = result.instances.map((json) => {
@@ -16738,12 +17678,12 @@ class Ad4mModel {
16738
17678
  * });
16739
17679
  * ```
16740
17680
  */
16741
- static async findAll(perspective, query) {
17681
+ static async findAll(perspective, query, options) {
16742
17682
  const q = (query ?? {});
16743
17683
  if (q.properties && q.properties.length === 0) {
16744
17684
  throw new Error("properties[] must not be empty — omit the field to return all properties, or specify at least one field name");
16745
17685
  }
16746
- const { results } = await this.executeModelQuery(perspective, q);
17686
+ const { results } = await this.executeModelQuery(perspective, q, undefined, options);
16747
17687
  return results;
16748
17688
  }
16749
17689
  /**
@@ -16766,9 +17706,9 @@ class Ad4mModel {
16766
17706
  * }
16767
17707
  * ```
16768
17708
  */
16769
- static async findOne(perspective, query) {
17709
+ static async findOne(perspective, query, options) {
16770
17710
  const limitedQuery = { ...(query ?? {}), limit: 1 };
16771
- const results = await this.findAll(perspective, limitedQuery);
17711
+ const results = await this.findAll(perspective, limitedQuery, options);
16772
17712
  return results[0] ?? null;
16773
17713
  }
16774
17714
  /**
@@ -16788,8 +17728,8 @@ class Ad4mModel {
16788
17728
  * console.log(`Showing 10 of ${totalCount} dessert recipes`);
16789
17729
  * ```
16790
17730
  */
16791
- static async findAllAndCount(perspective, query) {
16792
- const out = await this.executeModelQuery(perspective, (query ?? {}));
17731
+ static async findAllAndCount(perspective, query, options) {
17732
+ const out = await this.executeModelQuery(perspective, (query ?? {}), undefined, options);
16793
17733
  return out;
16794
17734
  }
16795
17735
  /**
@@ -16809,9 +17749,9 @@ class Ad4mModel {
16809
17749
  * console.log(`Page ${page.pageNumber} of recipes, ${page.results.length} items`);
16810
17750
  * ```
16811
17751
  */
16812
- static async paginate(perspective, pageSize, pageNumber, query) {
17752
+ static async paginate(perspective, pageSize, pageNumber, query, options) {
16813
17753
  const paginationQuery = { ...(query ?? {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
16814
- const { results, totalCount } = await this.executeModelQuery(perspective, paginationQuery);
17754
+ const { results, totalCount } = await this.executeModelQuery(perspective, paginationQuery, undefined, options);
16815
17755
  return { results: results, totalCount, pageSize, pageNumber };
16816
17756
  }
16817
17757
  /**
@@ -16839,8 +17779,8 @@ class Ad4mModel {
16839
17779
  * });
16840
17780
  * ```
16841
17781
  */
16842
- static async count(perspective, query) {
16843
- const { totalCount } = await this.executeModelQuery(perspective, { ...(query ?? {}), limit: 0 });
17782
+ static async count(perspective, query, options) {
17783
+ const { totalCount } = await this.executeModelQuery(perspective, { ...(query ?? {}), limit: 0 }, undefined, options);
16844
17784
  return totalCount;
16845
17785
  }
16846
17786
  async setProperty(key, value, batchId) {
@@ -16994,7 +17934,18 @@ class Ad4mModel {
16994
17934
  for (const [key, value] of Object.entries(this)) {
16995
17935
  if (value !== undefined && value !== null && !(Array.isArray(value) && value.length > 0) && !value?.action) {
16996
17936
  const propMeta = metadata.properties[key];
16997
- if (propMeta && effectiveLiteralStorage(propMeta).kind !== "deterministic") {
17937
+ // Only offer keys with a declared, settable model property. This
17938
+ // excludes ORM bookkeeping fields (_baseExpression, _perspective —
17939
+ // enumerable instance fields, not model properties), HasMany
17940
+ // relations (tracked in a separate registry, never in
17941
+ // `metadata.properties`), and read-only properties/flags
17942
+ // (readOnly: true). None of these have an `ad4m://setter` on the
17943
+ // Rust side, which otherwise logs a "declares no setter" warning
17944
+ // per key on every save().
17945
+ if (!propMeta || propMeta.readOnly) {
17946
+ continue;
17947
+ }
17948
+ if (effectiveLiteralStorage(propMeta).kind !== "deterministic") {
16998
17949
  deferredExpressionProps.push(key);
16999
17950
  continue;
17000
17951
  }
@@ -17103,13 +18054,36 @@ class Ad4mModel {
17103
18054
  await this.setRelationValues(key, value, batchId);
17104
18055
  }
17105
18056
  else if (value !== undefined && value !== null && value !== "") {
18057
+ // A scalar handed to a relation field is a single-member relation.
18058
+ //
18059
+ // This used to `continue` — "Skip, it's a relation, not a regular
18060
+ // property" — so `Model.create(p, { source: 'uri://x' })` typechecked,
18061
+ // ran, resolved, and wrote no link. The record was created with the
18062
+ // relation empty and nothing anywhere said so, which surfaces later as
18063
+ // a *reader* complaining about a malformed instance: a Relationship
18064
+ // with no endpoints, a Placement pointing at nothing. Both look like
18065
+ // rendering bugs from the outside, because the record exists and the
18066
+ // thing that should reference it does not.
18067
+ //
18068
+ // The array form is the documented path and stays correct; the problem
18069
+ // is that the scalar form is plausible, typechecks against a field
18070
+ // declared `string`, and fails silently. Coercing matches what a caller
18071
+ // reaching for it meant. A value `setRelationValues` cannot use now
18072
+ // fails there, loudly, instead of vanishing here.
18073
+ //
18074
+ // Deliberately outside the `setProperties` gate, mirroring the array
18075
+ // branch above. `create` passes `setProperties: false` when the class
18076
+ // has a constructor, because `create_subject` writes the values map —
18077
+ // but a relation carries `ad4m://adder`, not `ad4m://setter`, so
18078
+ // `create_subject` drops it (see the warning added in 3ee2b5bc6).
18079
+ // Relations have to be written here in both cases or they are lost by
18080
+ // both paths at once.
18081
+ const relationMeta = this.getRelationOptions(key);
18082
+ if (relationMeta) {
18083
+ await this.setRelationValues(key, [value], batchId);
18084
+ continue;
18085
+ }
17106
18086
  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
18087
  // Skip flag properties — they are immutable after creation
17114
18088
  const propMeta = this.getPropertyMetadata(key);
17115
18089
  if (propMeta?.flag) {
@@ -17939,13 +18913,13 @@ class PerspectiveHandle {
17939
18913
  * const runs = await InterpretationRun.findAll(perspective);
17940
18914
  * const configs = await AutoProcessorConfig.findAll(perspective);
17941
18915
  */
17942
- var __decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
18916
+ var __decorate$1 = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
17943
18917
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
17944
18918
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
17945
18919
  else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
17946
18920
  return c > 3 && r && Object.defineProperty(target, key, r), r;
17947
18921
  };
17948
- var __metadata = (undefined && undefined.__metadata) || function (k, v) {
18922
+ var __metadata$1 = (undefined && undefined.__metadata) || function (k, v) {
17949
18923
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
17950
18924
  };
17951
18925
  // ── AutoProcessorConfig ─────────────────────────────────────────────────────
@@ -17984,71 +18958,67 @@ exports.AutoProcessorConfig = class AutoProcessorConfig extends Ad4mModel {
17984
18958
  // `batchMax` + `claimTtlMs` — the Rust SDNA takes the same shape.
17985
18959
  }
17986
18960
  };
17987
- __decorate([
18961
+ __decorate$1([
17988
18962
  Property({ through: "ad4m://processor_id", required: true, identity: true }),
17989
- __metadata("design:type", String)
18963
+ __metadata$1("design:type", String)
17990
18964
  ], exports.AutoProcessorConfig.prototype, "processorId", void 0);
17991
- __decorate([
18965
+ __decorate$1([
17992
18966
  Property({ through: "ad4m://source_scope_query", required: true }),
17993
- __metadata("design:type", String)
18967
+ __metadata$1("design:type", String)
17994
18968
  ], exports.AutoProcessorConfig.prototype, "sourceScopeQuery", void 0);
17995
- __decorate([
18969
+ __decorate$1([
17996
18970
  Optional({ through: "ad4m://base_prefix" }),
17997
- __metadata("design:type", String)
18971
+ __metadata$1("design:type", String)
17998
18972
  ], exports.AutoProcessorConfig.prototype, "basePrefix", void 0);
17999
- __decorate([
18973
+ __decorate$1([
18000
18974
  HasMany({ through: "ad4m://interpretation_class", datatype: "xsd:string" }),
18001
- __metadata("design:type", Array)
18975
+ __metadata$1("design:type", Array)
18002
18976
  ], exports.AutoProcessorConfig.prototype, "interpretationClasses", void 0);
18003
- __decorate([
18977
+ __decorate$1([
18004
18978
  Property({ through: "ad4m://debounce_ms", required: true }),
18005
- __metadata("design:type", String)
18979
+ __metadata$1("design:type", String)
18006
18980
  ], exports.AutoProcessorConfig.prototype, "debounceMs", void 0);
18007
- __decorate([
18981
+ __decorate$1([
18008
18982
  Optional({ through: "ad4m://batch_min" }),
18009
- __metadata("design:type", String)
18983
+ __metadata$1("design:type", String)
18010
18984
  ], exports.AutoProcessorConfig.prototype, "batchMin", void 0);
18011
- __decorate([
18985
+ __decorate$1([
18012
18986
  Property({ through: "ad4m://batch_max", required: true }),
18013
- __metadata("design:type", String)
18987
+ __metadata$1("design:type", String)
18014
18988
  ], exports.AutoProcessorConfig.prototype, "batchMax", void 0);
18015
- __decorate([
18989
+ __decorate$1([
18016
18990
  Optional({ through: "ad4m://max_wait_ms" }),
18017
- __metadata("design:type", String)
18991
+ __metadata$1("design:type", String)
18018
18992
  ], exports.AutoProcessorConfig.prototype, "maxWaitMs", void 0);
18019
- __decorate([
18993
+ __decorate$1([
18020
18994
  Property({ through: "ad4m://claim_ttl_ms", required: true }),
18021
- __metadata("design:type", String)
18995
+ __metadata$1("design:type", String)
18022
18996
  ], exports.AutoProcessorConfig.prototype, "claimTtlMs", void 0);
18023
- __decorate([
18997
+ __decorate$1([
18024
18998
  Optional({ through: "ad4m://source_window_ms" }),
18025
- __metadata("design:type", String)
18999
+ __metadata$1("design:type", String)
18026
19000
  ], exports.AutoProcessorConfig.prototype, "sourceWindowMs", void 0);
18027
- __decorate([
19001
+ __decorate$1([
18028
19002
  Optional({ through: "ad4m://dedup_strategy" }),
18029
- __metadata("design:type", String)
19003
+ __metadata$1("design:type", String)
18030
19004
  ], exports.AutoProcessorConfig.prototype, "dedupStrategy", void 0);
18031
- __decorate([
19005
+ __decorate$1([
18032
19006
  Optional({ through: "ad4m://existing_scope" }),
18033
- __metadata("design:type", String)
19007
+ __metadata$1("design:type", String)
18034
19008
  ], exports.AutoProcessorConfig.prototype, "existingScope", void 0);
18035
- __decorate([
19009
+ __decorate$1([
18036
19010
  Optional({ through: "ad4m://mint_scope" }),
18037
- __metadata("design:type", String)
19011
+ __metadata$1("design:type", String)
18038
19012
  ], 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([
19013
+ __decorate$1([
19014
+ Optional({ through: "ad4m://max_tool_calls" }),
19015
+ __metadata$1("design:type", String)
19016
+ ], exports.AutoProcessorConfig.prototype, "maxToolCalls", void 0);
19017
+ __decorate$1([
18048
19018
  Optional({ through: "ad4m://emit_debug_events", resolveLanguage: "literal" }),
18049
- __metadata("design:type", String)
19019
+ __metadata$1("design:type", String)
18050
19020
  ], exports.AutoProcessorConfig.prototype, "emitDebugEvents", void 0);
18051
- exports.AutoProcessorConfig = __decorate([
19021
+ exports.AutoProcessorConfig = __decorate$1([
18052
19022
  Model$1({ name: "AutoProcessor" })
18053
19023
  ], exports.AutoProcessorConfig);
18054
19024
  // ── InterpretationRun ───────────────────────────────────────────────────────
@@ -18072,39 +19042,39 @@ exports.InterpretationRun = class InterpretationRun extends Ad4mModel {
18072
19042
  this.sources = [];
18073
19043
  }
18074
19044
  };
18075
- __decorate([
19045
+ __decorate$1([
18076
19046
  Property({ through: "ad4m://interp/run_id", required: true, identity: true }),
18077
- __metadata("design:type", String)
19047
+ __metadata$1("design:type", String)
18078
19048
  ], exports.InterpretationRun.prototype, "runId", void 0);
18079
- __decorate([
19049
+ __decorate$1([
18080
19050
  Optional({ through: "ad4m://interp/model" }),
18081
- __metadata("design:type", String)
19051
+ __metadata$1("design:type", String)
18082
19052
  ], exports.InterpretationRun.prototype, "model", void 0);
18083
- __decorate([
19053
+ __decorate$1([
18084
19054
  Optional({ through: "ad4m://interp/prompt_version" }),
18085
- __metadata("design:type", String)
19055
+ __metadata$1("design:type", String)
18086
19056
  ], exports.InterpretationRun.prototype, "promptVersion", void 0);
18087
- __decorate([
19057
+ __decorate$1([
18088
19058
  Optional({ through: "ad4m://interp/ran_at" }),
18089
- __metadata("design:type", String)
19059
+ __metadata$1("design:type", String)
18090
19060
  ], exports.InterpretationRun.prototype, "ranAt", void 0);
18091
- __decorate([
19061
+ __decorate$1([
18092
19062
  Optional({ through: "ad4m://interp/processor" }),
18093
- __metadata("design:type", String)
19063
+ __metadata$1("design:type", String)
18094
19064
  ], exports.InterpretationRun.prototype, "processor", void 0);
18095
- __decorate([
19065
+ __decorate$1([
18096
19066
  HasMany({ through: "ad4m://interp/sources", datatype: "xsd:string" }),
18097
- __metadata("design:type", Array)
19067
+ __metadata$1("design:type", Array)
18098
19068
  ], exports.InterpretationRun.prototype, "sources", void 0);
18099
- __decorate([
19069
+ __decorate$1([
18100
19070
  Optional({ through: "ad4m://interp/debug_prompt", resolveLanguage: "literal" }),
18101
- __metadata("design:type", String)
19071
+ __metadata$1("design:type", String)
18102
19072
  ], exports.InterpretationRun.prototype, "debugPrompt", void 0);
18103
- __decorate([
19073
+ __decorate$1([
18104
19074
  Optional({ through: "ad4m://interp/debug_response", resolveLanguage: "literal" }),
18105
- __metadata("design:type", String)
19075
+ __metadata$1("design:type", String)
18106
19076
  ], exports.InterpretationRun.prototype, "debugResponse", void 0);
18107
- exports.InterpretationRun = __decorate([
19077
+ exports.InterpretationRun = __decorate$1([
18108
19078
  Model$1({ name: "InterpretationRun" })
18109
19079
  ], exports.InterpretationRun);
18110
19080
  // ── InterpretationOverlay ───────────────────────────────────────────────────
@@ -18134,18 +19104,531 @@ exports.InterpretationOverlay = class InterpretationOverlay extends Ad4mModel {
18134
19104
  this.kind = "";
18135
19105
  }
18136
19106
  };
18137
- __decorate([
19107
+ __decorate$1([
18138
19108
  Property({ through: "ad4m://interp/kind", required: true }),
18139
- __metadata("design:type", String)
19109
+ __metadata$1("design:type", String)
18140
19110
  ], exports.InterpretationOverlay.prototype, "kind", void 0);
18141
- __decorate([
19111
+ __decorate$1([
18142
19112
  Optional({ through: "ad4m://interp/run" }),
18143
- __metadata("design:type", String)
19113
+ __metadata$1("design:type", String)
18144
19114
  ], exports.InterpretationOverlay.prototype, "run", void 0);
18145
- exports.InterpretationOverlay = __decorate([
19115
+ exports.InterpretationOverlay = __decorate$1([
18146
19116
  Model$1({ name: "InterpretationOverlay" })
18147
19117
  ], exports.InterpretationOverlay);
18148
19118
 
19119
+ /**
19120
+ * TypeScript @Model classes mirroring the Rust-side hardwired SDNA for the
19121
+ * flow runtime. Apps can import these to query the perspective graph for
19122
+ * pending flow-transition proposals without knowing the raw link predicates.
19123
+ *
19124
+ * Registration:
19125
+ * await FlowTransitionProposal.register(perspective);
19126
+ *
19127
+ * Querying:
19128
+ * const pending = await FlowTransitionProposal.findAll(perspective);
19129
+ *
19130
+ * Slice 5/7 of the flow-implementation arc (design doc §4.2). The Rust
19131
+ * engine does not yet mint these — that lands with the consensus firing
19132
+ * work in a later PR arc. This class defines the on-graph shape so:
19133
+ * - clients can build UI over proposals immediately (Deliberation demo);
19134
+ * - the SDNA-parity test locks TS/Rust drift the moment the JSON exists
19135
+ * (`rust-executor/src/perspectives/hardwired_sdna/flow_transition_proposal.json`);
19136
+ * - the engine can start writing into this shape when consensus lands
19137
+ * without touching the client-side surface.
19138
+ */
19139
+ var __decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
19140
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
19141
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
19142
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
19143
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
19144
+ };
19145
+ var __metadata = (undefined && undefined.__metadata) || function (k, v) {
19146
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
19147
+ };
19148
+ // ── FlowTransitionProposal ──────────────────────────────────────────────────
19149
+ // Mirrors the Rust hardwired `flow_transition_proposal.json` SDNA (once wired
19150
+ // on the engine side; see file header). One node per proposed transition; the
19151
+ // URI is `ad4m://flow/proposal/<uuid>` when the engine mints it, but the class
19152
+ // carries no URI-format constraint — apps constructing proposals directly may
19153
+ // choose any URI they can defend as unique.
19154
+ exports.FlowTransitionProposal = class FlowTransitionProposal extends Ad4mModel {
19155
+ constructor() {
19156
+ super(...arguments);
19157
+ /**
19158
+ * URI of the running `FlowInstance` this proposal targets. First-declared
19159
+ * property so `buildSHACL` derives the shape namespace from its `through`
19160
+ * prefix — `ad4m://flow/instance` → `ad4m://` → target_class
19161
+ * `ad4m://FlowTransitionProposal`. Also the identity predicate: the
19162
+ * discriminator `findAll` uses to isolate proposal nodes.
19163
+ */
19164
+ this.flowInstance = "";
19165
+ /** Name of the state the flow instance is currently in. */
19166
+ this.fromState = "";
19167
+ /** Name of the state the proposal wants to transition to. */
19168
+ this.toState = "";
19169
+ /** DID of the agent that issued the proposal. */
19170
+ this.proposer = "";
19171
+ /**
19172
+ * URIs of instances offered as evidence that `toState.requires` is now
19173
+ * satisfied. Multiple links, one per cited instance; ordering is not
19174
+ * significant.
19175
+ */
19176
+ this.evidence = [];
19177
+ /**
19178
+ * JSON blob: `{ [uri]: sha256_hex }` — one entry per evidence URI, hashing
19179
+ * the canonicalized graph-visible properties (sorted by property URI,
19180
+ * multi-values sorted lexicographically) at proposal time. Downstream
19181
+ * verifiers use it to detect edits to cited instances after the proposal
19182
+ * was written. Stored as an opaque string because SHACL properties carry
19183
+ * no rich-object type; the engine parses it back into a map.
19184
+ */
19185
+ this.evidenceHashes = "";
19186
+ // "When was this proposal written?" is answered by `Ad4mModel`'s built-in
19187
+ // `createdAt`, synthesized on hydration from the earliest link timestamp
19188
+ // of the proposal's own links (all written together during create_subject).
19189
+ }
19190
+ };
19191
+ __decorate([
19192
+ Property({ through: "ad4m://flow/instance", required: true, identity: true }),
19193
+ __metadata("design:type", String)
19194
+ ], exports.FlowTransitionProposal.prototype, "flowInstance", void 0);
19195
+ __decorate([
19196
+ Property({ through: "ad4m://flow/from_state", required: true }),
19197
+ __metadata("design:type", String)
19198
+ ], exports.FlowTransitionProposal.prototype, "fromState", void 0);
19199
+ __decorate([
19200
+ Property({ through: "ad4m://flow/to_state", required: true }),
19201
+ __metadata("design:type", String)
19202
+ ], exports.FlowTransitionProposal.prototype, "toState", void 0);
19203
+ __decorate([
19204
+ Property({ through: "ad4m://flow/proposer", required: true }),
19205
+ __metadata("design:type", String)
19206
+ ], exports.FlowTransitionProposal.prototype, "proposer", void 0);
19207
+ __decorate([
19208
+ HasMany({ through: "ad4m://flow/evidence", datatype: "xsd:string" }),
19209
+ __metadata("design:type", Array)
19210
+ ], exports.FlowTransitionProposal.prototype, "evidence", void 0);
19211
+ __decorate([
19212
+ Property({ through: "ad4m://flow/evidence_hashes", required: true }),
19213
+ __metadata("design:type", String)
19214
+ ], exports.FlowTransitionProposal.prototype, "evidenceHashes", void 0);
19215
+ __decorate([
19216
+ Optional({ through: "ad4m://flow/run_uri" }),
19217
+ __metadata("design:type", String)
19218
+ ], exports.FlowTransitionProposal.prototype, "runUri", void 0);
19219
+ __decorate([
19220
+ Optional({ through: "ad4m://flow/rationale" }),
19221
+ __metadata("design:type", String)
19222
+ ], exports.FlowTransitionProposal.prototype, "rationale", void 0);
19223
+ exports.FlowTransitionProposal = __decorate([
19224
+ Model$1({ name: "FlowTransitionProposal" })
19225
+ ], exports.FlowTransitionProposal);
19226
+ // ── FlowInstanceRecord ──────────────────────────────────────────────────────
19227
+ // On-graph node minted by the engine when a flow is started on a specific
19228
+ // base expression. Its URI is the value that `FlowTransitionProposal.flowInstance`
19229
+ // references. Mirrors `rust-executor/src/perspectives/hardwired_sdna/flow_instance.json`.
19230
+ //
19231
+ // Design authority: `docs/flow-interpretation-hints-design.md` §4.3.
19232
+ //
19233
+ // This class is the raw on-graph record (@Model over the SDNA shape). The
19234
+ // object-oriented handle callers work with is `FlowInstance` in
19235
+ // `./FlowInstance.ts` — it wraps `FlowInstanceRecord + SHACLFlow definition`
19236
+ // and exposes `currentState`, `availableTransitions`, `proposals`, etc.
19237
+ // Renamed from `FlowInstance` → `FlowInstanceRecord` on 2026-08-27 per
19238
+ // Nico's PR #929 review R2 (the `FlowInstance` name is reserved for the
19239
+ // wrapper the design has always specified in §4.3).
19240
+ //
19241
+ // The SDNA name (`@Model({ name: "FlowInstance" })`) stays unchanged — that
19242
+ // keys the on-graph class, not the TS export. Renaming the TS class only
19243
+ // changes the JS import surface; the graph shape is identical, and Rust
19244
+ // hardwired_sdna/flow_instance.json + all the parity tests still lock down
19245
+ // the same `ad4m://FlowInstance` target class.
19246
+ exports.FlowInstanceRecord = class FlowInstanceRecord extends Ad4mModel {
19247
+ constructor() {
19248
+ super(...arguments);
19249
+ /**
19250
+ * URI of the `SHACLFlow` this instance runs — the flow's canonical
19251
+ * identity, collision-free across social-DNA modules from different
19252
+ * communities (bare names WILL collide once shared flows are adopted
19253
+ * cross-team — James PR #929 R5). Sourced from `SHACLFlow.flowUri`
19254
+ * (which is `${namespace}${name}Flow`, e.g. `coasys://DeliveryFlow`).
19255
+ *
19256
+ * First-declared property so `buildSHACL` derives the shape namespace
19257
+ * from its `through` prefix — `ad4m://flow/flow_uri` → `ad4m://` →
19258
+ * target_class `ad4m://FlowInstance`. Also the discriminator predicate
19259
+ * `findAll` uses to isolate instance nodes.
19260
+ *
19261
+ * The human-readable flow name is still available on the paired
19262
+ * `SHACLFlow` (via `perspective.getFlow(record.flowUri.split('/').pop()!.replace(/Flow$/,''))`,
19263
+ * or more commonly via the `FlowInstance` wrapper's `flowName` getter).
19264
+ */
19265
+ this.flowUri = "";
19266
+ /**
19267
+ * URI of the subject expression this flow runs on.
19268
+ * Named `subject` (not `baseExpression`) because `Ad4mModel` reserves
19269
+ * `baseExpression` as a synthetic hydration field always set to the
19270
+ * instance's own URI — a subclass property with that name is shadowed
19271
+ * on read.
19272
+ */
19273
+ this.subject = "";
19274
+ /** Name of the state the flow is currently in. */
19275
+ this.currentState = "";
19276
+ // "When was this flow started?" is answered by `Ad4mModel`'s built-in
19277
+ // `createdAt`, synthesized on hydration from the earliest link timestamp
19278
+ // of the instance's own links (all written together during `mint_flow_instance`).
19279
+ }
19280
+ };
19281
+ __decorate([
19282
+ Property({ through: "ad4m://flow/flow_uri", required: true, identity: true }),
19283
+ __metadata("design:type", String)
19284
+ ], exports.FlowInstanceRecord.prototype, "flowUri", void 0);
19285
+ __decorate([
19286
+ Property({ through: "ad4m://flow/base", required: true }),
19287
+ __metadata("design:type", String)
19288
+ ], exports.FlowInstanceRecord.prototype, "subject", void 0);
19289
+ __decorate([
19290
+ Property({ through: "ad4m://flow/current_state", required: true }),
19291
+ __metadata("design:type", String)
19292
+ ], exports.FlowInstanceRecord.prototype, "currentState", void 0);
19293
+ exports.FlowInstanceRecord = __decorate([
19294
+ Model$1({ name: "FlowInstance" })
19295
+ ], exports.FlowInstanceRecord);
19296
+
19297
+ /**
19298
+ * `FlowInstance` — object-oriented wrapper for a running flow.
19299
+ *
19300
+ * Design authority: `docs/flow-interpretation-hints-design.md` §4.3.
19301
+ *
19302
+ * Wraps two on-graph objects:
19303
+ *
19304
+ * - `FlowInstanceRecord` — the raw @Model row minted by
19305
+ * {@link FlowInstance.start}; carries `flow`, `subject`, `currentState`,
19306
+ * and Ad4mModel's synthesised `createdAt`.
19307
+ * - `SHACLFlow` — the flow definition the record is bound to. Held so
19308
+ * `availableTransitions` / `currentState` object lookups don't require
19309
+ * a per-call round-trip.
19310
+ *
19311
+ * Construct via the class factories — {@link FlowInstance.start} for the
19312
+ * mint path and {@link FlowInstance.findAll} for the read path — rather
19313
+ * than the `wrap` escape hatch, which exists for tests that already own
19314
+ * a matched (record, shape) pair.
19315
+ *
19316
+ * # What's here vs. what's coming in §7 / slice 10.6
19317
+ *
19318
+ * Read surface (implemented today, PR #929):
19319
+ * - `uri`, `subject`, `flowName`, `currentStateName`, `startedAtMillis`
19320
+ * accessors.
19321
+ * - `currentState` — resolves the `FlowState` on the shape whose name
19322
+ * matches `record.currentState`.
19323
+ * - `availableTransitions` — filters `shape.transitions` by `fromState`.
19324
+ * - `proposals()` — queries `FlowTransitionProposal` records that
19325
+ * target this instance's URI.
19326
+ *
19327
+ * Mutations + subscriptions (`proposeTransition`, `accept`, `reject`,
19328
+ * `fireAction`, `onStateChange`, `onProposalAdded`, `onProposalResolved`)
19329
+ * land with the consensus-engine slice (§4.3 / slice 10.6). Rather than
19330
+ * ship them as `throw new Error("not yet")` stubs — which is a type-level
19331
+ * lie the caller only discovers at runtime — they are simply absent from
19332
+ * this class until the engine is wired.
19333
+ */
19334
+ /**
19335
+ * Extract the flow's human-readable name from its canonical URI.
19336
+ *
19337
+ * `SHACLFlow.flowUri` is `${namespace}${name}Flow` (e.g.
19338
+ * `coasys://DeliveryFlow`). This function strips the `Flow` suffix and
19339
+ * everything before the last URI-segment separator (`/` or `#`), leaving
19340
+ * the bare name. Returns `undefined` for URIs that don't match the
19341
+ * `…{name}Flow` shape — a stale FlowInstanceRecord whose flow URI came
19342
+ * from an older writer, for instance.
19343
+ */
19344
+ function flowNameFromUri(flowUri) {
19345
+ if (!flowUri.endsWith("Flow"))
19346
+ return undefined;
19347
+ const withoutSuffix = flowUri.slice(0, -"Flow".length);
19348
+ const sepIdx = Math.max(withoutSuffix.lastIndexOf("/"), withoutSuffix.lastIndexOf("#"));
19349
+ if (sepIdx < 0)
19350
+ return withoutSuffix || undefined;
19351
+ const name = withoutSuffix.slice(sepIdx + 1);
19352
+ return name || undefined;
19353
+ }
19354
+ class FlowInstance {
19355
+ /**
19356
+ * Private constructor — construct via {@link FlowInstance.start} or
19357
+ * {@link FlowInstance.findAll}. {@link FlowInstance.wrap} is the
19358
+ * escape hatch for tests / direct construction cases.
19359
+ */
19360
+ constructor(perspective,
19361
+ /** The flow definition this instance was minted against. */
19362
+ shape,
19363
+ /**
19364
+ * The on-graph record — carries `flow`, `subject`, `currentState`
19365
+ * and Ad4mModel's synthesised `createdAt`. Callers can reach into it
19366
+ * for anything the wrapper doesn't expose directly, but should prefer
19367
+ * the wrapper accessors so future refactors of the underlying shape
19368
+ * don't ripple through their code.
19369
+ */
19370
+ record) {
19371
+ this.perspective = perspective;
19372
+ this.shape = shape;
19373
+ this.record = record;
19374
+ }
19375
+ /**
19376
+ * Escape hatch used by {@link FlowInstance.start} and
19377
+ * {@link FlowInstance.findAll} — not meant for general use, but public
19378
+ * so tests that already own a `FlowInstanceRecord + SHACLFlow` pair
19379
+ * (e.g. from pre-populated fixtures) can build a wrapper without
19380
+ * going through the mint path.
19381
+ */
19382
+ static wrap(perspective, shape, record) {
19383
+ return new FlowInstance(perspective, shape, record);
19384
+ }
19385
+ /**
19386
+ * Mint a new `FlowInstance` on the given perspective (design doc §4.3).
19387
+ *
19388
+ * Idempotently registers the hardwired `FlowInstanceRecord` +
19389
+ * `FlowTransitionProposal` @Model classes on first call — the on-graph
19390
+ * shape matches the Rust-side hardwired SDNA (parity-locked in
19391
+ * `flow-instance.test.ts` / `flow-transition-proposal.test.ts`).
19392
+ *
19393
+ * The returned wrapper carries the parsed `SHACLFlow` alongside the
19394
+ * on-graph record, so `currentState` / `availableTransitions` /
19395
+ * `proposals` accessors work without further round-trips. The consensus
19396
+ * engine (slice 10.6) will read the record's `currentState` when it
19397
+ * fires transitions.
19398
+ *
19399
+ * @param perspective - The perspective the flow instance lives on
19400
+ * @param flowName - Name of a `SHACLFlow` already registered on the perspective
19401
+ * @param baseExpression - URI of the subject expression the flow runs on
19402
+ * @throws When the flow is unknown or has zero declared states (zero-state
19403
+ * flows fire via the forthcoming atomic-action path, §6.3).
19404
+ */
19405
+ static async start(perspective, flowName, baseExpression) {
19406
+ const flow = await perspective.getFlow(flowName);
19407
+ if (!flow)
19408
+ throw `Flow "${flowName}" not found`;
19409
+ if (flow.states.length === 0) {
19410
+ throw `Flow "${flowName}" has no states — FlowInstance.start is for stateful flows only; zero-state flows fire via the forthcoming atomic-action path (§6.3)`;
19411
+ }
19412
+ // Register the hardwired runtime classes if this is the first flow
19413
+ // instance on the perspective. registerAll is a single batched RPC and
19414
+ // no-ops when both classes are already present.
19415
+ await Ad4mModel.registerAll(perspective, [exports.FlowInstanceRecord, exports.FlowTransitionProposal]);
19416
+ // Property keys must be the FlowInstanceRecord @Model field names —
19417
+ // `subject` (not `baseExpression`, which collides with Ad4mModel's
19418
+ // synthetic hydration field and would be silently shadowed on read).
19419
+ // No explicit start-time field: Ad4mModel synthesises `createdAt` on
19420
+ // hydration from the earliest link timestamp on the instance's URI.
19421
+ // Convention: `SHACLFlow.states` is stored sorted ascending by `value`
19422
+ // (enforced by `fromLinks`), so `states[0]` is the initial state. A
19423
+ // flow author who wants a specific state as the entry point must give
19424
+ // it the lowest `value` in the set.
19425
+ //
19426
+ // Store the flow's URI, not the bare name — see FlowInstanceRecord's
19427
+ // docstring for the collision-across-modules argument (James PR #929 R5).
19428
+ const record = await exports.FlowInstanceRecord.create(perspective, {
19429
+ flowUri: flow.flowUri,
19430
+ subject: baseExpression,
19431
+ currentState: flow.states[0].name,
19432
+ });
19433
+ return FlowInstance.wrap(perspective, flow, record);
19434
+ }
19435
+ /**
19436
+ * Return every live `FlowInstance` on the perspective (design doc §4.3).
19437
+ *
19438
+ * Read-only path: never registers classes. On a perspective that has
19439
+ * never minted a flow instance, the `FlowInstanceRecord` SHACL shape
19440
+ * isn't installed yet — this returns `[]` in that case rather than
19441
+ * mutating the perspective. Registration is the responsibility of
19442
+ * {@link FlowInstance.start}, which is the write path. (Registering on
19443
+ * a read would sync a write to every peer in the neighbourhood —
19444
+ * exactly what a query must not do — James PR #929 R7.)
19445
+ *
19446
+ * Filter surface (all optional, all combinable):
19447
+ * - **`flowName`** — narrows by flow-name discriminator (e.g. "Delivery")
19448
+ * - **`subject`** — narrows by base-expression URI, i.e. "give me every
19449
+ * flow running on THIS expression"
19450
+ *
19451
+ * Both filters translate to a single SHACL `where`-filter round-trip
19452
+ * (no client-side filtering); combining them AND-joins server-side.
19453
+ * The string-arg shape (`FlowInstance.findAll(p, "Delivery")`) is
19454
+ * shorthand for `{ flowName: "Delivery" }`.
19455
+ *
19456
+ * Records whose `flow` value has no matching `SHACLFlow` on the
19457
+ * perspective (e.g. the flow was unregistered) are silently skipped —
19458
+ * the wrapper can't answer `currentState` / `availableTransitions`
19459
+ * without the shape, and callers routinely iterate the returned array
19460
+ * without null-checks.
19461
+ *
19462
+ * @example
19463
+ * ```typescript
19464
+ * const all = await FlowInstance.findAll(perspective);
19465
+ * const deliveries = await FlowInstance.findAll(perspective, "Delivery");
19466
+ * const onThisTask = await FlowInstance.findAll(perspective, {
19467
+ * subject: "ad4m://task/1",
19468
+ * });
19469
+ * const deliveriesOnTask = await FlowInstance.findAll(perspective, {
19470
+ * flowName: "Delivery",
19471
+ * subject: "ad4m://task/1",
19472
+ * });
19473
+ * ```
19474
+ */
19475
+ static async findAll(perspective, filter) {
19476
+ const { flowName, subject } = typeof filter === "string"
19477
+ ? { flowName: filter, subject: undefined }
19478
+ : { flowName: filter?.flowName, subject: filter?.subject };
19479
+ // Filter surface accepts a flow *name* for ergonomics — resolve it to
19480
+ // the canonical URI before the SHACL query, since the record stores
19481
+ // the URI (James PR #929 R5). Unknown name → no matches (short-circuit
19482
+ // with an empty result rather than issuing a bare-name query that
19483
+ // would silently return nothing anyway).
19484
+ const where = {};
19485
+ if (flowName !== undefined) {
19486
+ const flow = await perspective.getFlow(flowName);
19487
+ if (!flow)
19488
+ return [];
19489
+ where.flowUri = flow.flowUri;
19490
+ }
19491
+ if (subject !== undefined)
19492
+ where.subject = subject;
19493
+ // "Shape not found" on a perspective that has never minted a flow
19494
+ // instance is a no-op read, not an error — the executor throws for a
19495
+ // missing SHACL shape and there is no side-effect-free way to ask
19496
+ // "does this class exist". Return `[]` on that specific case; rethrow
19497
+ // anything else so real infra failures don't get swallowed.
19498
+ //
19499
+ // Regex covers every message the executor + client stack raises for
19500
+ // an unregistered class:
19501
+ // "No SHACL shape stored for class 'FlowInstance'." (executor RPC)
19502
+ // "Shape not found" (older Rust path)
19503
+ // "class not registered" / "not registered" (TS Ad4mModel guard)
19504
+ let records;
19505
+ try {
19506
+ records =
19507
+ Object.keys(where).length > 0
19508
+ ? await exports.FlowInstanceRecord.findAll(perspective, { where })
19509
+ : await exports.FlowInstanceRecord.findAll(perspective);
19510
+ }
19511
+ catch (e) {
19512
+ const msg = e instanceof Error ? e.message : String(e);
19513
+ if (/no shacl shape stored|shape not found|class not registered|not registered/i.test(msg)) {
19514
+ return [];
19515
+ }
19516
+ throw e;
19517
+ }
19518
+ // Pair each record with its parsed SHACLFlow. Cache lookups by
19519
+ // flow-URI so `getFlow` fires at most once per distinct flow —
19520
+ // matters when a perspective has hundreds of instances against
19521
+ // one shape.
19522
+ //
19523
+ // The URI stored on the record is `${namespace}${name}Flow`
19524
+ // (see SHACLFlow.flowUri) — recovering the name for `getFlow`
19525
+ // means stripping the namespace + the `Flow` suffix. Records that
19526
+ // don't parse this way are treated as stale and skipped.
19527
+ const shapesByUri = new Map();
19528
+ const wrappers = [];
19529
+ for (const record of records) {
19530
+ let shape = shapesByUri.get(record.flowUri);
19531
+ if (!shape) {
19532
+ const name = flowNameFromUri(record.flowUri);
19533
+ if (!name)
19534
+ continue;
19535
+ const loaded = await perspective.getFlow(name);
19536
+ if (!loaded || loaded.flowUri !== record.flowUri) {
19537
+ // Stale record — the flow it references was unregistered,
19538
+ // or a different flow now owns that name.
19539
+ continue;
19540
+ }
19541
+ shape = loaded;
19542
+ shapesByUri.set(record.flowUri, shape);
19543
+ }
19544
+ wrappers.push(FlowInstance.wrap(perspective, shape, record));
19545
+ }
19546
+ return wrappers;
19547
+ }
19548
+ // ── Read accessors ────────────────────────────────────────────────────
19549
+ /**
19550
+ * URI of the on-graph `FlowInstance` node — `ad4m://flow/instance/{id}`.
19551
+ *
19552
+ * Sourced from `Ad4mModel`'s synthesised `baseExpression`, which for
19553
+ * `FlowInstanceRecord` *is* the instance's own URI (the value
19554
+ * `FlowTransitionProposal.flowInstance` references).
19555
+ */
19556
+ get uri() {
19557
+ return this.record.baseExpression;
19558
+ }
19559
+ /**
19560
+ * URI of the base expression this flow runs on — matches the
19561
+ * `SHACLFlow.inputTypes` that {@link PerspectiveProxy.availableFlows}
19562
+ * would greenlight for this expression.
19563
+ */
19564
+ get subject() {
19565
+ return this.record.subject;
19566
+ }
19567
+ /**
19568
+ * Human-readable flow name — the display label. Sourced from the paired
19569
+ * `SHACLFlow.name`, not from the record (which stores the URI as its
19570
+ * canonical identity — see FlowInstanceRecord's docstring for why).
19571
+ */
19572
+ get flowName() {
19573
+ return this.shape.name;
19574
+ }
19575
+ /** Flow URI — the on-graph discriminator, collision-free across modules. */
19576
+ get flowUri() {
19577
+ return this.record.flowUri;
19578
+ }
19579
+ /** Name of the state this instance is currently in. */
19580
+ get currentStateName() {
19581
+ return this.record.currentState;
19582
+ }
19583
+ /**
19584
+ * ISO-8601 (epoch millis after Ad4mModel hydration) start time.
19585
+ * Returns `undefined` when hydration didn't produce a `createdAt`
19586
+ * — rare, but not fatal.
19587
+ */
19588
+ get startedAtMillis() {
19589
+ const v = this.record.createdAt;
19590
+ return typeof v === "number" ? v : undefined;
19591
+ }
19592
+ /**
19593
+ * The `FlowState` object on the shape matching `currentStateName`.
19594
+ * Throws when the record's state name is not declared on the flow —
19595
+ * that's a "stale FlowInstance whose flow was edited under it" bug,
19596
+ * not a silent-fail case.
19597
+ */
19598
+ get currentState() {
19599
+ const s = this.shape.states.find((x) => x.name === this.currentStateName);
19600
+ if (!s) {
19601
+ throw new Error(`FlowInstance ${this.uri}: currentState "${this.currentStateName}" is not declared on flow "${this.flowName}". ` +
19602
+ `Known states: ${this.shape.states.map((x) => x.name).join(", ") || "(none)"}`);
19603
+ }
19604
+ return s;
19605
+ }
19606
+ /**
19607
+ * Every `FlowTransition` on the shape whose `fromState` matches
19608
+ * `currentStateName`. Order preserved from the shape.
19609
+ *
19610
+ * Empty when the current state is terminal (no outgoing transitions).
19611
+ */
19612
+ get availableTransitions() {
19613
+ return this.shape.transitions.filter((t) => t.fromState === this.currentStateName);
19614
+ }
19615
+ /**
19616
+ * All `FlowTransitionProposal` records targeting this instance's URI.
19617
+ *
19618
+ * Uses the SDNA identity discriminator (`ad4m://flow/instance` predicate)
19619
+ * for the where-filter — one SPARQL round-trip, no client-side
19620
+ * filtering.
19621
+ *
19622
+ * Note: the consensus engine (slice 10.6) will start writing these; today
19623
+ * they only exist when a client wrote one directly (or a test seeded one).
19624
+ */
19625
+ async proposals() {
19626
+ return exports.FlowTransitionProposal.findAll(this.perspective, {
19627
+ where: { flowInstance: this.uri },
19628
+ });
19629
+ }
19630
+ }
19631
+
18149
19632
  /**
18150
19633
  * SPARQL binding helpers — typed shapes and parsers for `querySparql<T>()`.
18151
19634
  *
@@ -18918,6 +20401,7 @@ exports.ExpressionProofInput = ExpressionProofInput;
18918
20401
  exports.ExpressionRef = ExpressionRef;
18919
20402
  exports.ExpressionRendered = ExpressionRendered;
18920
20403
  exports.Flag = Flag;
20404
+ exports.FlowInstance = FlowInstance;
18921
20405
  exports.HasMany = HasMany;
18922
20406
  exports.HasOne = HasOne;
18923
20407
  exports.HostingUserInfo = HostingUserInfo;