@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.js CHANGED
@@ -23,6 +23,8 @@ class ApiClient {
23
23
  // ── WebSocket RPC core ──────────────────────────────────────────────────
24
24
  this._ws = null;
25
25
  this._wsCallbacks = new Set();
26
+ this._reconnectCallbacks = new Set();
27
+ this._hasConnectedOnce = false;
26
28
  this._pendingCalls = new Map();
27
29
  this._wsReady = null;
28
30
  this._wsReadyResolve = null;
@@ -30,6 +32,7 @@ class ApiClient {
30
32
  this._wsReconnectDelay = INITIAL_RECONNECT_DELAY_MS;
31
33
  this._wsClosed = false;
32
34
  this._wsPingTimer = null;
35
+ this._ignoredResponseIds = new Set();
33
36
  this.baseUrl = baseUrl;
34
37
  this.token = token;
35
38
  this._webSocketImpl = webSocketImpl;
@@ -64,7 +67,22 @@ class ApiClient {
64
67
  this._wsReadyResolve = resolve;
65
68
  });
66
69
  const url = this._getWsUrl();
67
- const WsImpl = this._webSocketImpl ?? WebSocket;
70
+ // Fallback order: injected impl → globalThis.WebSocket (browsers, Node ≥ 22) → require('ws') (Node ≤ 20).
71
+ // globalThis lookup avoids a ReferenceError on Node 18 where `WebSocket` is not a global.
72
+ const globalWs = globalThis.WebSocket;
73
+ let WsImpl;
74
+ if (this._webSocketImpl) {
75
+ WsImpl = this._webSocketImpl;
76
+ }
77
+ else if (globalWs) {
78
+ WsImpl = globalWs;
79
+ }
80
+ else {
81
+ // Lazy CommonJS require so bundlers targeting browsers don't try to bundle `ws`.
82
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
83
+ const req = eval('require');
84
+ WsImpl = req('ws');
85
+ }
68
86
  const ws = new WsImpl(url);
69
87
  this._ws = ws;
70
88
  ws.onopen = () => {
@@ -74,6 +92,18 @@ class ApiClient {
74
92
  this._wsReadyResolve = null;
75
93
  }
76
94
  this._startPing();
95
+ // Fire reconnect callbacks only on reconnect (not first connect)
96
+ if (this._hasConnectedOnce) {
97
+ for (const cb of this._reconnectCallbacks) {
98
+ try {
99
+ cb();
100
+ }
101
+ catch (e) {
102
+ console.error('Error in reconnect callback:', e);
103
+ }
104
+ }
105
+ }
106
+ this._hasConnectedOnce = true;
77
107
  };
78
108
  ws.onmessage = (event) => {
79
109
  let parsed;
@@ -102,6 +132,13 @@ class ApiClient {
102
132
  }
103
133
  return;
104
134
  }
135
+ // Discard ack responses to cancel requests we sent — they have
136
+ // an id that was never in _pendingCalls, so without this guard
137
+ // they'd leak into subscriber callbacks as spurious events.
138
+ if (id && this._ignoredResponseIds.has(id)) {
139
+ this._ignoredResponseIds.delete(id);
140
+ return;
141
+ }
105
142
  // Server-push event (no id, or id not in pending) → route to subscribers
106
143
  for (const cb of this._wsCallbacks)
107
144
  cb(parsed);
@@ -158,40 +195,130 @@ class ApiClient {
158
195
  if (this._wsReady)
159
196
  await this._wsReady;
160
197
  }
198
+ /**
199
+ * Like `_ready()`, but races the connection against an AbortSignal so
200
+ * that callers don't hang if the signal fires while connecting.
201
+ */
202
+ async _readyOrAbort(signal) {
203
+ if (signal?.aborted) {
204
+ throw new DOMException('Aborted', 'AbortError');
205
+ }
206
+ await new Promise((resolve, reject) => {
207
+ let settled = false;
208
+ const finish = (fn) => {
209
+ if (settled)
210
+ return;
211
+ settled = true;
212
+ if (signal && onAbort) {
213
+ signal.removeEventListener('abort', onAbort);
214
+ }
215
+ fn();
216
+ };
217
+ const onAbort = signal
218
+ ? () => finish(() => reject(new DOMException('Aborted', 'AbortError')))
219
+ : null;
220
+ if (onAbort) {
221
+ signal.addEventListener('abort', onAbort, { once: true });
222
+ }
223
+ this._ready().then(() => finish(resolve), (error) => finish(() => reject(error)));
224
+ });
225
+ }
161
226
  // ── RPC call method ─────────────────────────────────────────────────────
162
227
  /**
163
228
  * Send an RPC call over the WebSocket connection.
164
229
  * @param type - The operation type (e.g. 'agent.get', 'perspective.all')
165
230
  * @param params - Optional parameters to include in the message
166
- * @param timeoutMs - Optional per-call timeout override in ms. Defaults to
167
- * [[DEFAULT_TIMEOUT_MS]]. Use for long-running calls (LLM prompts,
168
- * holochain ops) that legitimately exceed the default.
231
+ * @param options - Optional call options: `signal` (AbortSignal for
232
+ * cancellation) and/or `timeoutMs` (per-call timeout override,
233
+ * defaults to [[DEFAULT_TIMEOUT_MS]] — use for long-running calls
234
+ * like LLM prompts or holochain ops that legitimately exceed it).
169
235
  * @returns Promise that resolves with the result from the server
170
236
  */
171
- async call(type, params, timeoutMs) {
172
- await this._ready();
237
+ async call(type, params, options) {
238
+ // Fast-path: if the caller already aborted, bail out before
239
+ // opening the socket. Matches fetch()'s behaviour.
240
+ const signal = options?.signal;
241
+ if (signal?.aborted) {
242
+ throw new DOMException('Aborted', 'AbortError');
243
+ }
244
+ await this._readyOrAbort(signal);
173
245
  const id = nextId();
174
246
  // Put params under a "params" key to avoid collision with
175
247
  // protocol fields "id" and "type" (e.g. params might contain
176
248
  // { id: modelId } or { type: "db" }).
177
249
  const message = { id, type, params: params || {} };
178
- const effectiveTimeout = timeoutMs ?? DEFAULT_TIMEOUT_MS;
250
+ const effectiveTimeout = options?.timeoutMs ?? DEFAULT_TIMEOUT_MS;
179
251
  return new Promise((resolve, reject) => {
252
+ let abortHandler = null;
253
+ const cleanup = () => {
254
+ if (signal && abortHandler) {
255
+ signal.removeEventListener('abort', abortHandler);
256
+ abortHandler = null;
257
+ }
258
+ };
180
259
  const timer = setTimeout(() => {
181
260
  this._pendingCalls.delete(id);
261
+ cleanup();
182
262
  reject(new RpcError(408, `RPC call '${type}' timed out after ${effectiveTimeout}ms`));
183
263
  }, effectiveTimeout);
264
+ // Wrap resolve/reject so we always clean up the abort listener.
184
265
  this._pendingCalls.set(id, {
185
- resolve: resolve,
186
- reject,
266
+ resolve: (value) => { cleanup(); resolve(value); },
267
+ reject: (reason) => { cleanup(); reject(reason); },
187
268
  timer,
188
269
  });
270
+ if (signal) {
271
+ abortHandler = () => {
272
+ // Drop the pending entry first so the late server
273
+ // reply (if any) routes to the event subscribers,
274
+ // not to a stale resolver.
275
+ this._pendingCalls.delete(id);
276
+ clearTimeout(timer);
277
+ cleanup();
278
+ // Best-effort `request.cancel` — the executor will
279
+ // race the cancellation token against the in-flight
280
+ // handler. If the socket is already gone there's
281
+ // nothing useful we can send; the client side is
282
+ // still aborted either way.
283
+ if (this._ws && this._ws.readyState === 1 /* OPEN */) {
284
+ try {
285
+ const cancelId = nextId();
286
+ this._ignoredResponseIds.add(cancelId);
287
+ // Safety-net eviction: if the executor's ack never
288
+ // arrives (e.g. the socket drops right after we
289
+ // send request.cancel), the normal cleanup path
290
+ // (deleting the id when its response lands) never
291
+ // fires and the entry would live in this set for
292
+ // the lifetime of the client. Bound it instead —
293
+ // DEFAULT_TIMEOUT_MS is already the ceiling every
294
+ // other in-flight call uses, so an ack that hasn't
295
+ // shown up by then isn't coming.
296
+ setTimeout(() => {
297
+ this._ignoredResponseIds.delete(cancelId);
298
+ }, DEFAULT_TIMEOUT_MS);
299
+ this._ws.send(JSON.stringify({
300
+ id: cancelId,
301
+ type: 'request.cancel',
302
+ params: { targetId: id },
303
+ }));
304
+ }
305
+ catch (e) {
306
+ // Swallow — the user-visible failure mode is the
307
+ // AbortError below; a socket send failure here
308
+ // doesn't change client semantics.
309
+ }
310
+ }
311
+ reject(new DOMException('Aborted', 'AbortError'));
312
+ };
313
+ signal.addEventListener('abort', abortHandler, { once: true });
314
+ }
189
315
  if (this._ws && this._ws.readyState === 1 /* OPEN */) {
190
316
  this._ws.send(JSON.stringify(message));
191
317
  }
192
318
  else {
193
319
  this._pendingCalls.delete(id);
194
320
  clearTimeout(timer);
321
+ cleanup();
195
322
  reject(new RpcError(503, 'WebSocket not connected'));
196
323
  }
197
324
  });
@@ -229,6 +356,13 @@ class ApiClient {
229
356
  this._wsReady = null;
230
357
  }
231
358
  }
359
+ /** Register a callback that fires after a successful WebSocket reconnect.
360
+ * Does NOT fire on the initial connection — only on reconnects.
361
+ * Returns an unsubscribe function. */
362
+ onReconnect(callback) {
363
+ this._reconnectCallbacks.add(callback);
364
+ return () => { this._reconnectCallbacks.delete(callback); };
365
+ }
232
366
  /** Close all open WebSocket connections and reject pending calls. */
233
367
  closeAll() {
234
368
  // Reject pending calls
@@ -239,6 +373,12 @@ class ApiClient {
239
373
  this._pendingCalls.clear();
240
374
  this._closeWs();
241
375
  this._wsCallbacks.clear();
376
+ this._reconnectCallbacks.clear();
377
+ // Reset the first-connect gate so a reused client (closeAll() →
378
+ // later call()/subscribe() reopening via _ensureWs) does not fire
379
+ // freshly registered onReconnect callbacks on the initial open of
380
+ // the new connection — see the contract on onReconnect().
381
+ this._hasConnectedOnce = false;
242
382
  }
243
383
  }
244
384
 
@@ -1286,6 +1426,13 @@ class SHACLShape {
1286
1426
  target: prop.path
1287
1427
  });
1288
1428
  // Constraints
1429
+ if (prop.ordering) {
1430
+ links.push({
1431
+ source: propShapeId,
1432
+ predicate: "ad4m://ordering",
1433
+ target: `literal:string:${prop.ordering}`
1434
+ });
1435
+ }
1289
1436
  if (prop.datatype) {
1290
1437
  links.push({
1291
1438
  source: propShapeId,
@@ -1532,6 +1679,10 @@ class SHACLShape {
1532
1679
  const datatypeLink = links.find(l => l.source === propShapeId && l.predicate === "sh://datatype");
1533
1680
  if (datatypeLink)
1534
1681
  prop.datatype = datatypeLink.target;
1682
+ const orderingLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://ordering");
1683
+ if (orderingLink) {
1684
+ prop.ordering = orderingLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
1685
+ }
1535
1686
  const nodeKindLink = links.find(l => l.source === propShapeId && l.predicate === "sh://nodeKind");
1536
1687
  if (nodeKindLink) {
1537
1688
  prop.nodeKind = nodeKindLink.target.replace('sh://', '');
@@ -1769,6 +1920,11 @@ class SHACLShape {
1769
1920
  transform: p.transform,
1770
1921
  interpretation_hint: p.interpretationHint,
1771
1922
  identity: p.identity,
1923
+ // The backend reads the ordering declaration back from the
1924
+ // `ad4m://ordering` link that `parse_shacl_to_links` writes from this
1925
+ // field. `ensureSubjectClass` ships `toJSON()`, so omitting it here
1926
+ // leaves `@HasMany({ ordering })` inert no matter what `toLinks()` does.
1927
+ ordering: p.ordering,
1772
1928
  })),
1773
1929
  constructor_actions: this.constructor_actions,
1774
1930
  destructor_actions: this.destructor_actions,
@@ -1816,6 +1972,7 @@ class SHACLShape {
1816
1972
  transform: p.transform,
1817
1973
  interpretationHint: p.interpretation_hint,
1818
1974
  identity: p.identity,
1975
+ ordering: p.ordering,
1819
1976
  });
1820
1977
  }
1821
1978
  if (json.constructor_actions) {
@@ -2100,10 +2257,24 @@ interpretationHint) {
2100
2257
  if (relMeta.filter === false) {
2101
2258
  relShape.filter = false;
2102
2259
  }
2260
+ // Ordering is declared in the type system so the executor can act on it
2261
+ // for every writer, not just this client.
2262
+ if (relMeta.ordering) {
2263
+ relShape.ordering = relMeta.ordering.strategy;
2264
+ }
2103
2265
  // AD4M-specific metadata
2104
2266
  if (relMeta.local !== undefined) {
2105
2267
  relShape.local = relMeta.local;
2106
2268
  }
2269
+ // Per-relation interpretation hint — sentence-level meaning that
2270
+ // steers the harness LLM's `_propose_link_child` `predicate` field
2271
+ // description. Read back on the Rust side by
2272
+ // `ShaclProperty.interpretation_hint` and rendered into the tool
2273
+ // schema alongside the predicate URI enum (so `basedOn` reads
2274
+ // "prior beliefs this intention derives from", not just "some link").
2275
+ if (relMeta.interpretationHint) {
2276
+ relShape.interpretationHint = relMeta.interpretationHint;
2277
+ }
2107
2278
  // Adder / Remover actions — only meaningful for relations backed
2108
2279
  // by a real link predicate. Getter-only relations are read-only.
2109
2280
  if (relMeta.predicate) {
@@ -2240,6 +2411,25 @@ interpretationHint) {
2240
2411
  }
2241
2412
  shape.addProperty(relShape);
2242
2413
  }
2414
+ // ── Ordering links ─────────────────────────────────────────────────
2415
+ // Ordering entries are stored on the *parent*, under one shared predicate,
2416
+ // so that reconstruction needs no extra query: they arrive with the
2417
+ // instance's own links. That only works if the instance query asks for them,
2418
+ // and it builds its predicate filter from the shape's declared paths — so a
2419
+ // class owning any ordered collection has to declare the predicate, or the
2420
+ // very links the ordering depends on are filtered out of the read that needs
2421
+ // them.
2422
+ //
2423
+ // One entry covers every ordered relation on the class; each entry names the
2424
+ // relation it belongs to.
2425
+ const hasOrderedRelation = Object.values(allRelationsMeta).some((m) => m.ordering);
2426
+ if (hasOrderedRelation) {
2427
+ shape.addProperty({
2428
+ name: '_collectionOrder',
2429
+ path: 'ad4m://collection_order',
2430
+ nodeKind: 'IRI',
2431
+ });
2432
+ }
2243
2433
  // Always set constructor and destructor actions on the shape, even
2244
2434
  // when empty. An empty array serialises to `literal:string:[]`
2245
2435
  // which the Rust executor parses as a valid (no-op) command list,
@@ -2829,35 +3019,57 @@ function resolveRelationArgs(first, second) {
2829
3019
  const opts = typeof first === 'function'
2830
3020
  ? { ...(second || {}), target: first }
2831
3021
  : first;
2832
- // getter is mutually exclusive with through, target, and where
3022
+ // `where` and `filter: false` contradict each other on every relation,
3023
+ // getter-backed ones included — checked before the getter path returns.
3024
+ if (opts.where && opts.filter === false) {
3025
+ throw new Error('Relation decorator: `where` and `filter: false` are contradictory. ' +
3026
+ '`where` adds filtering constraints; `filter: false` disables filtering.');
3027
+ }
3028
+ // getter is mutually exclusive with through
2833
3029
  if (opts.getter) {
2834
3030
  if (opts.through) {
2835
3031
  throw new Error('Relation decorator: `getter` and `through` are mutually exclusive. ' +
2836
3032
  'Use `getter` alone for custom read-only relations, or `through` ' +
2837
3033
  '(with optional `target`) for standard link-based relations.');
2838
3034
  }
2839
- if (opts.target) {
2840
- throw new Error('Relation decorator: `getter` and `target` are mutually exclusive. ' +
2841
- '`target` auto-generates a conformance getter from the model shape; ' +
2842
- 'providing both is contradictory.');
2843
- }
2844
- if (opts.where) {
2845
- throw new Error('Relation decorator: `where` and `getter` are mutually exclusive. ' +
2846
- 'Use `where` for DSL-based filtering, or `getter` for raw getter expression.');
2847
- }
3035
+ // `target` and `where` are NOT mutually exclusive with `getter`.
3036
+ //
3037
+ // `target` does two separable jobs: it auto-derives a conformance
3038
+ // getter, and it names the class the relation's values hydrate into.
3039
+ // Only the first conflicts with an explicit getter, and `buildSHACL`
3040
+ // already resolves that on its own — an explicit getter wins the getter
3041
+ // slot, while `sh:class` / `ad4m:targetClassName` are emitted from
3042
+ // `target` independently.
3043
+ //
3044
+ // Refusing the pair cost the one thing a custom getter is for. A getter
3045
+ // expresses a traversal the link-shaped DSL cannot — most usefully
3046
+ // through a reified edge, where the connection is a record rather than
3047
+ // a predicate:
3048
+ //
3049
+ // @HasMany({
3050
+ // getter: "SELECT ?target WHERE { \
3051
+ // ?citation <paper://cites_from> <Base> . \
3052
+ // ?citation <paper://cites_to> ?target . }",
3053
+ // target: () => Paper,
3054
+ // })
3055
+ // cited: Paper[] = [];
3056
+ //
3057
+ // Without `target` the relation has no target class, so `include` on it
3058
+ // resolves a shape named "" and fails — leaving a traversal that can
3059
+ // only ever return bare URIs. With it, the values hydrate like any other
3060
+ // relation, because getters are evaluated before include resolution.
3061
+ //
3062
+ // `where` is the same story: the executor applies post-getter where
3063
+ // filters specifically to getter-backed relations
3064
+ // (`apply_where_filter_to_relation`), and emitting `wherePredicates`
3065
+ // needs `target` to resolve the target's metadata — so the runtime is
3066
+ // built for all three together and only this check said otherwise.
2848
3067
  return opts;
2849
3068
  }
2850
3069
  // Default predicate when not provided
2851
3070
  if (!opts.through) {
2852
3071
  opts.through = 'ad4m://has_child';
2853
3072
  }
2854
- // where validation
2855
- if (opts.where) {
2856
- if (opts.filter === false) {
2857
- throw new Error('Relation decorator: `where` and `filter: false` are contradictory. ' +
2858
- '`where` adds filtering constraints; `filter: false` disables filtering.');
2859
- }
2860
- }
2861
3073
  return opts;
2862
3074
  }
2863
3075
  function HasMany(first, second) {
@@ -2877,6 +3089,10 @@ function HasMany(first, second) {
2877
3089
  ...(opts.filter !== undefined && { filter: opts.filter }),
2878
3090
  ...(opts.where && { where: opts.where }),
2879
3091
  ...(opts.datatype && { datatype: opts.datatype }),
3092
+ ...(opts.polymorphic && { polymorphic: opts.polymorphic }),
3093
+ ...(opts.instantiateAs && { instantiateAs: opts.instantiateAs }),
3094
+ ...(opts.ordering && { ordering: opts.ordering }),
3095
+ ...(opts.interpretationHint && { interpretationHint: opts.interpretationHint }),
2880
3096
  };
2881
3097
  const relKey = key;
2882
3098
  // Only add mutation methods when a predicate is available
@@ -2911,6 +3127,10 @@ function HasOne(first, second) {
2911
3127
  ...(opts.filter !== undefined && { filter: opts.filter }),
2912
3128
  ...(opts.where && { where: opts.where }),
2913
3129
  ...(opts.datatype && { datatype: opts.datatype }),
3130
+ ...(opts.polymorphic && { polymorphic: opts.polymorphic }),
3131
+ ...(opts.instantiateAs && { instantiateAs: opts.instantiateAs }),
3132
+ ...(opts.ordering && { ordering: opts.ordering }),
3133
+ ...(opts.interpretationHint && { interpretationHint: opts.interpretationHint }),
2914
3134
  };
2915
3135
  const relKey = key;
2916
3136
  if (opts.through) {
@@ -2920,15 +3140,23 @@ function HasOne(first, second) {
2920
3140
  readOnly: false,
2921
3141
  local: opts.local,
2922
3142
  })(target, key);
2923
- // Add prototype methods for add/remove/set (mirroring @HasMany)
2924
- target[`add${capitalize(relKey)}`] = async function (arg) {
2925
- return this.addRelationValue(relKey, arg);
3143
+ // Add prototype methods for add/remove/set (mirroring @HasMany).
3144
+ //
3145
+ // `batchId` is part of that mirroring: without it a to-one link
3146
+ // cannot join a write group, so anything that creates a record and
3147
+ // then points it at something has to commit twice and every
3148
+ // subscriber sees the state in between — a record whose to-one
3149
+ // relation is still empty. Anything rendering from a subscription
3150
+ // therefore has a frame in which the record exists and points at
3151
+ // nothing.
3152
+ target[`add${capitalize(relKey)}`] = async function (arg, batchId) {
3153
+ return this.addRelationValue(relKey, arg, batchId);
2926
3154
  };
2927
- target[`remove${capitalize(relKey)}`] = async function (arg) {
2928
- return this.removeRelationValue(relKey, arg);
3155
+ target[`remove${capitalize(relKey)}`] = async function (arg, batchId) {
3156
+ return this.removeRelationValue(relKey, arg, batchId);
2929
3157
  };
2930
- target[`set${capitalize(relKey)}`] = async function (arg) {
2931
- return this.setRelationValues(relKey, arg);
3158
+ target[`set${capitalize(relKey)}`] = async function (arg, batchId) {
3159
+ return this.setRelationValues(relKey, arg, batchId);
2932
3160
  };
2933
3161
  }
2934
3162
  else {
@@ -2952,6 +3180,10 @@ function BelongsToOne(first, second) {
2952
3180
  ...(opts.filter !== undefined && { filter: opts.filter }),
2953
3181
  ...(opts.where && { where: opts.where }),
2954
3182
  ...(opts.datatype && { datatype: opts.datatype }),
3183
+ ...(opts.polymorphic && { polymorphic: opts.polymorphic }),
3184
+ ...(opts.instantiateAs && { instantiateAs: opts.instantiateAs }),
3185
+ ...(opts.ordering && { ordering: opts.ordering }),
3186
+ ...(opts.interpretationHint && { interpretationHint: opts.interpretationHint }),
2955
3187
  };
2956
3188
  if (opts.through) {
2957
3189
  // Read-only property (the owning side manages the link)
@@ -2982,6 +3214,10 @@ function BelongsToMany(first, second) {
2982
3214
  ...(opts.filter !== undefined && { filter: opts.filter }),
2983
3215
  ...(opts.where && { where: opts.where }),
2984
3216
  ...(opts.datatype && { datatype: opts.datatype }),
3217
+ ...(opts.polymorphic && { polymorphic: opts.polymorphic }),
3218
+ ...(opts.instantiateAs && { instantiateAs: opts.instantiateAs }),
3219
+ ...(opts.ordering && { ordering: opts.ordering }),
3220
+ ...(opts.interpretationHint && { interpretationHint: opts.interpretationHint }),
2985
3221
  };
2986
3222
  // @BelongsToMany is the inverse/read-only side — do NOT generate add*/remove*/set*
2987
3223
  // prototype methods. Mutation must go through the owning side's @HasMany decorator.
@@ -3057,59 +3293,82 @@ function queryCacheSize() {
3057
3293
  return cache.size;
3058
3294
  }
3059
3295
 
3296
+ /**
3297
+ * Runtime shape check for a decoded `ModelQuery`. Deserialization paths use
3298
+ * this to guard against malformed guard arrays leaking into flow metadata
3299
+ * (an untyped `Array.isArray` would happily accept `[null]` or `[{}]`).
3300
+ * Only the mandatory `className: string` field is enforced — richer
3301
+ * validation stays with the runtime engine that will actually execute the
3302
+ * query.
3303
+ */
3304
+ function isModelQueryShape(v) {
3305
+ if (typeof v !== "object" ||
3306
+ v === null ||
3307
+ typeof v.className !== "string" ||
3308
+ v.className.length === 0) {
3309
+ return false;
3310
+ }
3311
+ const or = v.or;
3312
+ if (or !== undefined) {
3313
+ if (!Array.isArray(or) || !or.every(isModelQueryShape))
3314
+ return false;
3315
+ }
3316
+ return true;
3317
+ }
3318
+ /**
3319
+ * Runtime shape check for a decoded `ConsensusRule`. Enforces the one
3320
+ * mandatory field (`n: number` with a sane range) and, when `fromRole`
3321
+ * is present, that it's a valid ModelQuery. A malformed literal (e.g.
3322
+ * `{ n: "many" }` or `{ n: 1, fromRole: null }`) leaves the field unset
3323
+ * rather than becoming corrupt flow metadata that downstream engines
3324
+ * would trip over.
3325
+ */
3326
+ function isConsensusRuleShape(v) {
3327
+ if (typeof v !== "object" || v === null)
3328
+ return false;
3329
+ const n = v.n;
3330
+ if (typeof n !== "number" || !Number.isFinite(n) || n < 1 || !Number.isInteger(n)) {
3331
+ return false;
3332
+ }
3333
+ const fromRole = v.fromRole;
3334
+ if (fromRole !== undefined && !isModelQueryShape(fromRole))
3335
+ return false;
3336
+ return true;
3337
+ }
3060
3338
  /**
3061
3339
  * SHACL Flow - represents a state machine for AD4M expressions
3062
3340
  *
3063
3341
  * Flows define:
3064
- * - Which expressions can enter the flow (flowable condition)
3065
- * - What states exist and how to detect them (via link patterns)
3066
- * - How to transition between states (via actions)
3342
+ * - Which expressions can enter the flow (via `inputTypes`)
3343
+ * - What states exist and their per-state guards (via `requires`)
3344
+ * - How to transition between states (via transitions + consensus rules)
3345
+ *
3346
+ * State lives on the on-graph `FlowInstanceRecord.currentState` and is
3347
+ * read/written through the `FlowInstance` wrapper class
3348
+ * ({@link FlowInstance.start} / {@link FlowInstance.findAll}) — see design
3349
+ * doc §4.3/§5.
3067
3350
  *
3068
3351
  * @example
3069
3352
  * ```typescript
3070
3353
  * const todoFlow = new SHACLFlow('todo://TODO', 'todo://');
3071
3354
  *
3072
3355
  * // Any expression can become a TODO
3073
- * todoFlow.flowable = 'any';
3074
- *
3075
- * // Define states
3076
- * todoFlow.addState({
3077
- * name: 'ready',
3078
- * value: 0,
3079
- * stateCheck: { predicate: 'todo://state', target: 'todo://ready' }
3080
- * });
3081
- * todoFlow.addState({
3082
- * name: 'doing',
3083
- * value: 0.5,
3084
- * stateCheck: { predicate: 'todo://state', target: 'todo://doing' }
3085
- * });
3086
- * todoFlow.addState({
3087
- * name: 'done',
3088
- * value: 1,
3089
- * stateCheck: { predicate: 'todo://state', target: 'todo://done' }
3090
- * });
3356
+ * todoFlow.inputTypes = ['any'];
3091
3357
  *
3092
- * // Define start action
3093
- * todoFlow.startAction = [{
3094
- * action: 'addLink',
3095
- * source: 'this',
3096
- * predicate: 'todo://state',
3097
- * target: 'todo://ready'
3098
- * }];
3358
+ * todoFlow.addState({ name: 'ready', value: 0 });
3359
+ * todoFlow.addState({ name: 'doing', value: 0.5 });
3360
+ * todoFlow.addState({ name: 'done', value: 1 });
3099
3361
  *
3100
- * // Define transitions
3101
3362
  * todoFlow.addTransition({
3102
3363
  * actionName: 'Start',
3103
3364
  * fromState: 'ready',
3104
3365
  * toState: 'doing',
3105
- * actions: [
3106
- * { action: 'addLink', source: 'this', predicate: 'todo://state', target: 'todo://doing' },
3107
- * { action: 'removeLink', source: 'this', predicate: 'todo://state', target: 'todo://ready' }
3108
- * ]
3366
+ * actions: [],
3109
3367
  * });
3110
3368
  *
3111
- * // Store in perspective
3369
+ * // Register on the perspective and mint an instance on a subject.
3112
3370
  * await perspective.addFlow('TODO', todoFlow);
3371
+ * const instance = await FlowInstance.start(perspective, 'TODO', 'expr://123');
3113
3372
  * ```
3114
3373
  */
3115
3374
  class SHACLFlow {
@@ -3119,11 +3378,41 @@ class SHACLFlow {
3119
3378
  * @param namespace - Namespace for URIs (e.g., "todo://")
3120
3379
  */
3121
3380
  constructor(name, namespace) {
3122
- /** Condition for which expressions can start this flow */
3123
- this.flowable = "any";
3124
- /** Actions to execute when starting the flow */
3125
- this.startAction = [];
3126
- /** States in this flow */
3381
+ /**
3382
+ * Subject-class URIs the flow accepts as its base expression.
3383
+ *
3384
+ * Design doc §4.1: a flow's *typed input*. When an
3385
+ * expression whose class matches any URI in this array enters scope,
3386
+ * the flow-spawn engine considers it a candidate base. Superseded
3387
+ * the older link-level `flowable: LinkPattern` primitive — model-level
3388
+ * matching by subject class instead of link matching. Empty array =
3389
+ * flow declares no typed input. The `"any"` sentinel is accepted as
3390
+ * a wildcard for tests and legacy flows.
3391
+ */
3392
+ this.inputTypes = [];
3393
+ /**
3394
+ * Subject-class URIs the flow must produce (linked to the base) for a
3395
+ * run to count as complete.
3396
+ *
3397
+ * Design doc §4.1: a flow's *typed output*. Two jobs:
3398
+ * (a) documentation for stateful flows — records what a completed run
3399
+ * leaves in the graph; (b) **terminal condition** for zero-state flows —
3400
+ * a flow with no `FlowState`s completes when at least one instance of
3401
+ * each `outputTypes` entry exists in scope and is linked to the base,
3402
+ * and `consensusRule` fires. This is what makes "Like" a first-class
3403
+ * flow with no state machine.
3404
+ */
3405
+ this.outputTypes = [];
3406
+ /**
3407
+ * States in this flow.
3408
+ *
3409
+ * **Ordering convention (James PR #929 R9):** the array is stored sorted
3410
+ * ascending by `value`. `states[0]` is the initial state — the one
3411
+ * {@link FlowInstance.start} mints a fresh instance into. A flow author
3412
+ * who wants a specific state as the entry point must give it the lowest
3413
+ * `value` in the set. `fromLinks` enforces this sort, so link-order on
3414
+ * the graph never dictates the initial state.
3415
+ */
3127
3416
  this._states = [];
3128
3417
  /** Transitions between states */
3129
3418
  this._transitions = [];
@@ -3191,27 +3480,63 @@ class SHACLFlow {
3191
3480
  predicate: "ad4m://flowName",
3192
3481
  target: Literal.from(this.name).toUrl()
3193
3482
  });
3194
- // Flowable condition
3195
- if (this.flowable === "any") {
3483
+ // Top-level interpretation hint (optional, drives AI state suggestion).
3484
+ // Empty strings are treated as "unset" so a round-trip through the graph
3485
+ // doesn't materialise an empty-hint predicate that consumers would then
3486
+ // read back as a meaningful value.
3487
+ if (this.interpretationHint) {
3196
3488
  links.push({
3197
3489
  source: flowUri,
3198
- predicate: "ad4m://flowable",
3199
- target: "ad4m://any"
3490
+ predicate: "ad4m://interpretationHint",
3491
+ target: Literal.from(this.interpretationHint).toUrl()
3200
3492
  });
3201
3493
  }
3202
- else {
3494
+ // Typed I/O (flow-level, design §4.1). Both arrays are only
3495
+ // serialized when non-empty — an empty list is indistinguishable
3496
+ // from "unset" for a round-trip, and emitting one would give
3497
+ // downstream consumers a meaningless predicate to interpret.
3498
+ if (this.inputTypes.length > 0) {
3499
+ links.push({
3500
+ source: flowUri,
3501
+ predicate: "ad4m://inputTypes",
3502
+ target: `literal:string:${encodeURIComponent(JSON.stringify(this.inputTypes))}`
3503
+ });
3504
+ }
3505
+ if (this.outputTypes.length > 0) {
3506
+ links.push({
3507
+ source: flowUri,
3508
+ predicate: "ad4m://outputTypes",
3509
+ target: `literal:string:${encodeURIComponent(JSON.stringify(this.outputTypes))}`
3510
+ });
3511
+ }
3512
+ // Flow-level `creationHint` — same empty-string-is-unset guard as
3513
+ // `interpretationHint`, same reason (round-trip fidelity).
3514
+ if (this.creationHint) {
3203
3515
  links.push({
3204
3516
  source: flowUri,
3205
- predicate: "ad4m://flowable",
3206
- target: `literal:string:${encodeURIComponent(JSON.stringify(this.flowable))}`
3517
+ predicate: "ad4m://creationHint",
3518
+ target: Literal.from(this.creationHint).toUrl()
3207
3519
  });
3208
3520
  }
3209
- // Start action
3210
- if (this.startAction.length > 0) {
3521
+ // Flow-level `context` — background queries the LLM sees but not
3522
+ // guard evidence. Single JSON literal, consumers parse back.
3523
+ if (this.context && this.context.length > 0) {
3211
3524
  links.push({
3212
3525
  source: flowUri,
3213
- predicate: "ad4m://startAction",
3214
- target: `literal:string:${encodeURIComponent(JSON.stringify(this.startAction))}`
3526
+ predicate: "ad4m://context",
3527
+ target: `literal:string:${encodeURIComponent(JSON.stringify(this.context))}`
3528
+ });
3529
+ }
3530
+ // Flow-level `consensusRule` — default for state transitions when a
3531
+ // FlowState omits its own rule; also the terminal-firing rule for
3532
+ // zero-state flows. Serialized as one JSON literal (the shape is
3533
+ // fixed and cheap to parse; consistent with `context` / `requires`
3534
+ // so consumers only need one parser).
3535
+ if (this.consensusRule) {
3536
+ links.push({
3537
+ source: flowUri,
3538
+ predicate: "ad4m://consensusRule",
3539
+ target: `literal:string:${encodeURIComponent(JSON.stringify(this.consensusRule))}`
3215
3540
  });
3216
3541
  }
3217
3542
  // States
@@ -3241,12 +3566,45 @@ class SHACLFlow {
3241
3566
  predicate: "ad4m://stateValue",
3242
3567
  target: Literal.from(state.value).toUrl()
3243
3568
  });
3244
- // State check pattern
3245
- links.push({
3246
- source: stateUri,
3247
- predicate: "ad4m://stateCheck",
3248
- target: `literal:string:${encodeURIComponent(JSON.stringify(state.stateCheck))}`
3249
- });
3569
+ // Per-state interpretation hint (optional, drives AI state suggestion).
3570
+ // Empty strings treated as unset — same rationale as the flow-level hint.
3571
+ if (state.interpretationHint) {
3572
+ links.push({
3573
+ source: stateUri,
3574
+ predicate: "ad4m://interpretationHint",
3575
+ target: Literal.from(state.interpretationHint).toUrl()
3576
+ });
3577
+ }
3578
+ // Per-state `requires` guard — array of ModelQueries, AND-combined.
3579
+ // Serialized as one JSON string on `ad4m://requires`. Consumers
3580
+ // (state-transition engine, `flow.availableActions`) parse back.
3581
+ if (state.requires && state.requires.length > 0) {
3582
+ links.push({
3583
+ source: stateUri,
3584
+ predicate: "ad4m://requires",
3585
+ target: `literal:string:${encodeURIComponent(JSON.stringify(state.requires))}`
3586
+ });
3587
+ }
3588
+ // Per-state `semanticCheck` hint — optional English confirmation
3589
+ // that runs after `requires` matches, for states where structural
3590
+ // presence isn't sufficient evidence. Empty string = unset.
3591
+ if (state.semanticCheck) {
3592
+ links.push({
3593
+ source: stateUri,
3594
+ predicate: "ad4m://semanticCheck",
3595
+ target: Literal.from(state.semanticCheck).toUrl()
3596
+ });
3597
+ }
3598
+ // Per-state `consensusRule` override — one JSON literal on the
3599
+ // state, same predicate name as the flow-level rule but scoped by
3600
+ // source URI so the reader can tell them apart.
3601
+ if (state.consensusRule) {
3602
+ links.push({
3603
+ source: stateUri,
3604
+ predicate: "ad4m://consensusRule",
3605
+ target: `literal:string:${encodeURIComponent(JSON.stringify(state.consensusRule))}`
3606
+ });
3607
+ }
3250
3608
  }
3251
3609
  // Transitions
3252
3610
  for (const transition of this._transitions) {
@@ -3311,31 +3669,96 @@ class SHACLFlow {
3311
3669
  const namespace = withoutSuffix.slice(0, lastSlashOrColon + 1);
3312
3670
  const name = withoutSuffix.slice(lastSlashOrColon + 1);
3313
3671
  const flow = new SHACLFlow(name, namespace);
3314
- // Find flowable condition
3315
- const flowableLink = links.find(l => l.source === flowUri && l.predicate === "ad4m://flowable");
3316
- if (flowableLink) {
3317
- if (flowableLink.target === "ad4m://any") {
3318
- flow.flowable = "any";
3672
+ // Find top-level interpretation hint. Only accept a decoded value that
3673
+ // is a non-empty string — malformed literals (Literal.get() can return
3674
+ // an object, number, etc.) leave the field unset rather than becoming
3675
+ // corrupt flow metadata.
3676
+ const flowHintLink = links.find(l => l.source === flowUri && l.predicate === "ad4m://interpretationHint");
3677
+ if (flowHintLink) {
3678
+ try {
3679
+ const decoded = Literal.fromUrl(flowHintLink.target).get();
3680
+ if (typeof decoded === "string" && decoded.length > 0) {
3681
+ flow.interpretationHint = decoded;
3682
+ }
3319
3683
  }
3320
- else {
3321
- try {
3322
- const jsonStr = flowableLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
3323
- flow.flowable = JSON.parse(decodeURIComponent(jsonStr));
3684
+ catch {
3685
+ // Ignore parse errors — leave unset.
3686
+ }
3687
+ }
3688
+ // Find typed I/O (flow-level, design §4.1). Both arrays validated
3689
+ // element-wise — only accept string[] payloads. A malformed literal
3690
+ // (`[null]`, `[42]`, non-array) leaves the field as its default
3691
+ // empty array rather than corrupting flow metadata.
3692
+ const inputTypesLink = links.find(l => l.source === flowUri && l.predicate === "ad4m://inputTypes");
3693
+ if (inputTypesLink) {
3694
+ try {
3695
+ const jsonStr = inputTypesLink.target.replace(/^literal:\/\/string:|^literal:string:/, "");
3696
+ const parsed = JSON.parse(decodeURIComponent(jsonStr));
3697
+ if (Array.isArray(parsed) && parsed.every(v => typeof v === "string" && v.length > 0)) {
3698
+ flow.inputTypes = parsed;
3324
3699
  }
3325
- catch {
3326
- flow.flowable = "any";
3700
+ }
3701
+ catch {
3702
+ // Ignore parse errors — leave as default empty array.
3703
+ }
3704
+ }
3705
+ const outputTypesLink = links.find(l => l.source === flowUri && l.predicate === "ad4m://outputTypes");
3706
+ if (outputTypesLink) {
3707
+ try {
3708
+ const jsonStr = outputTypesLink.target.replace(/^literal:\/\/string:|^literal:string:/, "");
3709
+ const parsed = JSON.parse(decodeURIComponent(jsonStr));
3710
+ if (Array.isArray(parsed) && parsed.every(v => typeof v === "string" && v.length > 0)) {
3711
+ flow.outputTypes = parsed;
3327
3712
  }
3328
3713
  }
3714
+ catch {
3715
+ // Ignore parse errors — leave as default empty array.
3716
+ }
3329
3717
  }
3330
- // Find start action
3331
- const startActionLink = links.find(l => l.source === flowUri && l.predicate === "ad4m://startAction");
3332
- if (startActionLink) {
3718
+ // Find flow-level `creationHint`. Non-empty-string guard — same
3719
+ // rationale as `interpretationHint`.
3720
+ const creationHintLink = links.find(l => l.source === flowUri && l.predicate === "ad4m://creationHint");
3721
+ if (creationHintLink) {
3333
3722
  try {
3334
- const jsonStr = startActionLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
3335
- flow.startAction = JSON.parse(decodeURIComponent(jsonStr));
3723
+ const decoded = Literal.fromUrl(creationHintLink.target).get();
3724
+ if (typeof decoded === "string" && decoded.length > 0) {
3725
+ flow.creationHint = decoded;
3726
+ }
3336
3727
  }
3337
3728
  catch {
3338
- // Ignore parse errors
3729
+ // Ignore parse errors — leave unset.
3730
+ }
3731
+ }
3732
+ // Find flow-level `context` — same ModelQuery-shape guard as
3733
+ // FlowState.requires (rejects `[null]`, `[{}]`, non-string
3734
+ // `className`).
3735
+ const contextLink = links.find(l => l.source === flowUri && l.predicate === "ad4m://context");
3736
+ if (contextLink) {
3737
+ try {
3738
+ const jsonStr = contextLink.target.replace(/^literal:\/\/string:|^literal:string:/, "");
3739
+ const parsed = JSON.parse(decodeURIComponent(jsonStr));
3740
+ if (Array.isArray(parsed) && parsed.every(isModelQueryShape)) {
3741
+ flow.context = parsed;
3742
+ }
3743
+ }
3744
+ catch {
3745
+ // Ignore parse errors — leave unset.
3746
+ }
3747
+ }
3748
+ // Find flow-level `consensusRule`. Reject malformed literals
3749
+ // (missing `n`, non-integer `n`, invalid `fromRole`) so the runtime
3750
+ // engine never has to defensively re-validate a stored rule.
3751
+ const consensusRuleLink = links.find(l => l.source === flowUri && l.predicate === "ad4m://consensusRule");
3752
+ if (consensusRuleLink) {
3753
+ try {
3754
+ const jsonStr = consensusRuleLink.target.replace(/^literal:\/\/string:|^literal:string:/, "");
3755
+ const parsed = JSON.parse(decodeURIComponent(jsonStr));
3756
+ if (isConsensusRuleShape(parsed)) {
3757
+ flow.consensusRule = parsed;
3758
+ }
3759
+ }
3760
+ catch {
3761
+ // Ignore parse errors — leave unset.
3339
3762
  }
3340
3763
  }
3341
3764
  // Find states
@@ -3352,20 +3775,85 @@ class SHACLFlow {
3352
3775
  // Get state value
3353
3776
  const valueLink = links.find(l => l.source === stateUri && l.predicate === "ad4m://stateValue");
3354
3777
  const stateValue = valueLink ? Literal.fromUrl(valueLink.target).get() : 0;
3355
- // Get state check
3356
- const checkLink = links.find(l => l.source === stateUri && l.predicate === "ad4m://stateCheck");
3357
- let stateCheck = { predicate: "", target: "" };
3358
- if (checkLink) {
3778
+ // Get per-state interpretation hint (optional). Same non-empty-string
3779
+ // guard as the flow-level hint.
3780
+ const hintLink = links.find(l => l.source === stateUri && l.predicate === "ad4m://interpretationHint");
3781
+ let interpretationHint;
3782
+ if (hintLink) {
3359
3783
  try {
3360
- const jsonStr = checkLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
3361
- stateCheck = JSON.parse(decodeURIComponent(jsonStr));
3784
+ const decoded = Literal.fromUrl(hintLink.target).get();
3785
+ if (typeof decoded === "string" && decoded.length > 0) {
3786
+ interpretationHint = decoded;
3787
+ }
3362
3788
  }
3363
3789
  catch {
3364
- // Ignore parse errors
3790
+ // Ignore parse errors — leave unset.
3791
+ }
3792
+ }
3793
+ // Get per-state `requires` guard (optional) — one link carrying a
3794
+ // JSON-encoded ModelQuery[]. Reject arrays whose entries are not
3795
+ // ModelQuery-shaped (missing/non-string `className`, `null`, primitives).
3796
+ const requiresLink = links.find(l => l.source === stateUri && l.predicate === "ad4m://requires");
3797
+ let requires;
3798
+ if (requiresLink) {
3799
+ try {
3800
+ const jsonStr = requiresLink.target.replace(/^literal:\/\/string:|^literal:string:/, "");
3801
+ const parsed = JSON.parse(decodeURIComponent(jsonStr));
3802
+ if (Array.isArray(parsed) && parsed.every(isModelQueryShape)) {
3803
+ requires = parsed;
3804
+ }
3805
+ }
3806
+ catch {
3807
+ // Ignore parse errors — leave requires unset rather than crash
3365
3808
  }
3366
3809
  }
3367
- flow.addState({ name: stateName, value: stateValue, stateCheck });
3810
+ // Get per-state `semanticCheck` hint (optional). Non-empty-string guard.
3811
+ const semanticCheckLink = links.find(l => l.source === stateUri && l.predicate === "ad4m://semanticCheck");
3812
+ let semanticCheck;
3813
+ if (semanticCheckLink) {
3814
+ try {
3815
+ const decoded = Literal.fromUrl(semanticCheckLink.target).get();
3816
+ if (typeof decoded === "string" && decoded.length > 0) {
3817
+ semanticCheck = decoded;
3818
+ }
3819
+ }
3820
+ catch {
3821
+ // Ignore parse errors — leave unset.
3822
+ }
3823
+ }
3824
+ // Get per-state `consensusRule` override (optional). Same shape
3825
+ // guard as the flow-level rule; a malformed literal (missing `n`,
3826
+ // non-integer, invalid `fromRole`) leaves the field unset.
3827
+ const stateConsensusLink = links.find(l => l.source === stateUri && l.predicate === "ad4m://consensusRule");
3828
+ let consensusRule;
3829
+ if (stateConsensusLink) {
3830
+ try {
3831
+ const jsonStr = stateConsensusLink.target.replace(/^literal:\/\/string:|^literal:string:/, "");
3832
+ const parsed = JSON.parse(decodeURIComponent(jsonStr));
3833
+ if (isConsensusRuleShape(parsed)) {
3834
+ consensusRule = parsed;
3835
+ }
3836
+ }
3837
+ catch {
3838
+ // Ignore parse errors — leave unset.
3839
+ }
3840
+ }
3841
+ flow.addState({
3842
+ name: stateName,
3843
+ value: stateValue,
3844
+ ...(interpretationHint !== undefined ? { interpretationHint } : {}),
3845
+ ...(requires !== undefined ? { requires } : {}),
3846
+ ...(semanticCheck !== undefined ? { semanticCheck } : {}),
3847
+ ...(consensusRule !== undefined ? { consensusRule } : {}),
3848
+ });
3368
3849
  }
3850
+ // Perspective link storage does not preserve insertion order — `hasState`
3851
+ // links come back in arbitrary order from the graph, so `flow.states[0]`
3852
+ // was randomly one of the round-tripped states. Sort by `value` ascending
3853
+ // so the "initial state = states[0]" convention (used by
3854
+ // `FlowInstance.start`) survives a fromGraph round trip.
3855
+ // The `states` getter returns a defensive copy, so mutate `_states` directly.
3856
+ flow._states.sort((a, b) => a.value - b.value);
3369
3857
  // Find transitions
3370
3858
  const transitionLinks = links.filter(l => l.source === flowUri && l.predicate === "ad4m://hasTransition");
3371
3859
  for (const transitionLink of transitionLinks) {
@@ -3401,13 +3889,31 @@ class SHACLFlow {
3401
3889
  * Convert to JSON representation
3402
3890
  */
3403
3891
  toJSON() {
3892
+ // Per-state metadata is optional; strip empty strings / empty arrays so
3893
+ // json.states[i] agrees with what toLinks() would materialise (a state
3894
+ // constructed with `interpretationHint: ""` produces no predicate, so
3895
+ // JSON must not carry the empty field either).
3896
+ const sanitizedStates = this._states.map(s => ({
3897
+ name: s.name,
3898
+ value: s.value,
3899
+ ...(s.interpretationHint ? { interpretationHint: s.interpretationHint } : {}),
3900
+ ...(s.requires && s.requires.length > 0 ? { requires: s.requires } : {}),
3901
+ ...(s.semanticCheck ? { semanticCheck: s.semanticCheck } : {}),
3902
+ ...(s.consensusRule ? { consensusRule: s.consensusRule } : {})
3903
+ }));
3404
3904
  return {
3405
3905
  name: this.name,
3406
3906
  namespace: this.namespace,
3407
- flowable: this.flowable,
3408
- startAction: this.startAction,
3409
- states: this._states,
3410
- transitions: this._transitions
3907
+ states: sanitizedStates,
3908
+ transitions: this._transitions,
3909
+ // Empty strings / empty arrays treated as unset — same semantics
3910
+ // as the toLinks path, so JSON <-> links round-trips agree.
3911
+ ...(this.interpretationHint ? { interpretationHint: this.interpretationHint } : {}),
3912
+ ...(this.inputTypes.length > 0 ? { inputTypes: this.inputTypes } : {}),
3913
+ ...(this.outputTypes.length > 0 ? { outputTypes: this.outputTypes } : {}),
3914
+ ...(this.creationHint ? { creationHint: this.creationHint } : {}),
3915
+ ...(this.context && this.context.length > 0 ? { context: this.context } : {}),
3916
+ ...(this.consensusRule ? { consensusRule: this.consensusRule } : {})
3411
3917
  };
3412
3918
  }
3413
3919
  /**
@@ -3415,10 +3921,49 @@ class SHACLFlow {
3415
3921
  */
3416
3922
  static fromJSON(json) {
3417
3923
  const flow = new SHACLFlow(json.name, json.namespace);
3418
- flow.flowable = json.flowable || "any";
3419
- flow.startAction = json.startAction || [];
3924
+ // Non-empty-string guard — mirrors the toLinks-side reader.
3925
+ if (typeof json.interpretationHint === "string" && json.interpretationHint.length > 0) {
3926
+ flow.interpretationHint = json.interpretationHint;
3927
+ }
3928
+ // Typed I/O (design §4.1). Same string[]/ModelQuery[] shape guards
3929
+ // as the fromLinks path — malformed payloads leave defaults untouched.
3930
+ if (Array.isArray(json.inputTypes) &&
3931
+ json.inputTypes.every((v) => typeof v === "string" && v.length > 0)) {
3932
+ flow.inputTypes = json.inputTypes;
3933
+ }
3934
+ if (Array.isArray(json.outputTypes) &&
3935
+ json.outputTypes.every((v) => typeof v === "string" && v.length > 0)) {
3936
+ flow.outputTypes = json.outputTypes;
3937
+ }
3938
+ if (typeof json.creationHint === "string" && json.creationHint.length > 0) {
3939
+ flow.creationHint = json.creationHint;
3940
+ }
3941
+ if (Array.isArray(json.context) && json.context.every(isModelQueryShape)) {
3942
+ flow.context = json.context;
3943
+ }
3944
+ if (isConsensusRuleShape(json.consensusRule)) {
3945
+ flow.consensusRule = json.consensusRule;
3946
+ }
3420
3947
  for (const state of json.states || []) {
3421
- flow.addState(state);
3948
+ // Same validation as the toLinks path: reject malformed optional fields
3949
+ // rather than let them poison downstream consumers.
3950
+ const sanitized = {
3951
+ name: state.name,
3952
+ value: state.value,
3953
+ };
3954
+ if (typeof state.interpretationHint === "string" && state.interpretationHint.length > 0) {
3955
+ sanitized.interpretationHint = state.interpretationHint;
3956
+ }
3957
+ if (Array.isArray(state.requires) && state.requires.every(isModelQueryShape)) {
3958
+ sanitized.requires = state.requires;
3959
+ }
3960
+ if (typeof state.semanticCheck === "string" && state.semanticCheck.length > 0) {
3961
+ sanitized.semanticCheck = state.semanticCheck;
3962
+ }
3963
+ if (isConsensusRuleShape(state.consensusRule)) {
3964
+ sanitized.consensusRule = state.consensusRule;
3965
+ }
3966
+ flow.addState(sanitized);
3422
3967
  }
3423
3968
  for (const transition of json.transitions || []) {
3424
3969
  flow.addTransition(transition);
@@ -3438,7 +3983,7 @@ var __classPrivateFieldGet$a = (undefined && undefined.__classPrivateFieldGet) |
3438
3983
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
3439
3984
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
3440
3985
  };
3441
- var _QuerySubscriptionProxy_instances, _QuerySubscriptionProxy_uuid, _QuerySubscriptionProxy_subscriptionId, _QuerySubscriptionProxy_client, _QuerySubscriptionProxy_callbacks, _QuerySubscriptionProxy_keepaliveTimer, _QuerySubscriptionProxy_unsubscribe, _QuerySubscriptionProxy_latestResult, _QuerySubscriptionProxy_disposed, _QuerySubscriptionProxy_initialized, _QuerySubscriptionProxy_initResolve, _QuerySubscriptionProxy_initReject, _QuerySubscriptionProxy_initTimeoutId, _QuerySubscriptionProxy_query, _QuerySubscriptionProxy_notifyCallbacks, _PerspectiveProxy_handle, _PerspectiveProxy_client, _PerspectiveProxy_perspectiveLinkAddedCallbacks, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, _PerspectiveProxy_perspectiveSyncStateChangeCallbacks, _PerspectiveProxy_ensuredSubjectClasses;
3986
+ var _QuerySubscriptionProxy_instances, _QuerySubscriptionProxy_uuid, _QuerySubscriptionProxy_subscriptionId, _QuerySubscriptionProxy_client, _QuerySubscriptionProxy_callbacks, _QuerySubscriptionProxy_keepaliveTimer, _QuerySubscriptionProxy_unsubscribe, _QuerySubscriptionProxy_reconnectUnsub, _QuerySubscriptionProxy_latestResult, _QuerySubscriptionProxy_disposed, _QuerySubscriptionProxy_initialized, _QuerySubscriptionProxy_initResolve, _QuerySubscriptionProxy_initReject, _QuerySubscriptionProxy_initTimeoutId, _QuerySubscriptionProxy_query, _QuerySubscriptionProxy_generation, _QuerySubscriptionProxy_deliverResult, _QuerySubscriptionProxy_startKeepalive, _QuerySubscriptionProxy_notifyCallbacks, _PerspectiveProxy_handle, _PerspectiveProxy_client, _PerspectiveProxy_perspectiveLinkAddedCallbacks, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, _PerspectiveProxy_perspectiveSyncStateChangeCallbacks, _PerspectiveProxy_ensuredSubjectClasses;
3442
3987
  /** Extract namespace prefix from a URI (everything up to and including the last / or #) */
3443
3988
  function extractNamespaceFromUri(uri) {
3444
3989
  const hashIdx = uri.lastIndexOf('#');
@@ -3499,6 +4044,7 @@ class QuerySubscriptionProxy {
3499
4044
  _QuerySubscriptionProxy_callbacks.set(this, void 0);
3500
4045
  _QuerySubscriptionProxy_keepaliveTimer.set(this, void 0);
3501
4046
  _QuerySubscriptionProxy_unsubscribe.set(this, void 0);
4047
+ _QuerySubscriptionProxy_reconnectUnsub.set(this, void 0);
3502
4048
  _QuerySubscriptionProxy_latestResult.set(this, void 0);
3503
4049
  _QuerySubscriptionProxy_disposed.set(this, false);
3504
4050
  _QuerySubscriptionProxy_initialized.set(this, void 0);
@@ -3506,6 +4052,15 @@ class QuerySubscriptionProxy {
3506
4052
  _QuerySubscriptionProxy_initReject.set(this, void 0);
3507
4053
  _QuerySubscriptionProxy_initTimeoutId.set(this, void 0);
3508
4054
  _QuerySubscriptionProxy_query.set(this, void 0);
4055
+ // Monotonic token guarding the three concurrent writers of
4056
+ // `#unsubscribe`/`#subscriptionId` (full subscribe() from the keepalive
4057
+ // and init-timeout retry paths, and the reconnect swap handler). Each
4058
+ // writer bumps it on entry and re-checks after every await; a mismatch
4059
+ // means a newer writer took over while we were suspended, so the stale
4060
+ // continuation must back out instead of clobbering the newer state
4061
+ // (worst case otherwise: an overwritten-but-never-called unsubscribe
4062
+ // leaks its callback in ApiClient._wsCallbacks for the client lifetime).
4063
+ _QuerySubscriptionProxy_generation.set(this, 0);
3509
4064
  __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_uuid, uuid, "f");
3510
4065
  __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_query, query, "f");
3511
4066
  __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_client, client, "f");
@@ -3518,6 +4073,26 @@ class QuerySubscriptionProxy {
3518
4073
  }), "f");
3519
4074
  }
3520
4075
  async subscribe() {
4076
+ var _a;
4077
+ // Invalidate any suspended writer (older subscribe() or reconnect
4078
+ // swap parked on an await) — see #generation.
4079
+ const generation = __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_generation, (_a = __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_generation, "f"), ++_a), "f");
4080
+ // Remove any prior reconnect listener FIRST — before we touch
4081
+ // `#unsubscribe`. Rationale: `#unsubscribe()` calls into
4082
+ // `ApiClient.subscribe()`'s deleter, which closes the WebSocket
4083
+ // whenever this query owned the last `_wsCallbacks` entry (and no
4084
+ // RPCs are pending). The subsequent `subscribeQuery()` below then
4085
+ // re-opens a fresh socket, and that fresh `onopen` fires the
4086
+ // reconnect callback set. If the OLD reconnect listener is still
4087
+ // in that set, it re-enters this method, closes the socket again,
4088
+ // reopens again … an endless resubscribe loop. Clearing the
4089
+ // listener up-front breaks the cycle; a fresh listener is
4090
+ // installed at the end of a successful subscribe(), and a
4091
+ // full-retry recovery listener in the catch block on failure.
4092
+ if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_reconnectUnsub, "f")) {
4093
+ __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_reconnectUnsub, "f").call(this);
4094
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_reconnectUnsub, undefined, "f");
4095
+ }
3521
4096
  // Clean up previous subscription attempt if retrying
3522
4097
  if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_unsubscribe, "f")) {
3523
4098
  __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_unsubscribe, "f").call(this);
@@ -3537,19 +4112,22 @@ class QuerySubscriptionProxy {
3537
4112
  // Initialize the query subscription
3538
4113
  let initialResult;
3539
4114
  initialResult = await __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, "f").subscribeQuery(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_query, "f"));
4115
+ // A newer writer (another subscribe() or a reconnect swap) took
4116
+ // over while we awaited — back out without touching shared state,
4117
+ // and release the now-orphaned server-side subscription so it
4118
+ // doesn't linger until its keepalive TTL expires.
4119
+ if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_disposed, "f") || __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_generation, "f") !== generation) {
4120
+ __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, "f").disposeQuerySubscription(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_uuid, "f"), initialResult.subscriptionId)
4121
+ .catch(e => console.error('Error disposing superseded query subscription:', e));
4122
+ return;
4123
+ }
3540
4124
  __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_subscriptionId, initialResult.subscriptionId, "f");
3541
4125
  // Process the initial result immediately for fast UX.
3542
4126
  // The subscribeQuery() RPC call already returns the initial result,
3543
4127
  // so treat that as successful initialization instead of waiting for a
3544
4128
  // follow-up WebSocket update that may never arrive until the query changes.
3545
4129
  if (initialResult.result !== undefined) {
3546
- __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_latestResult, initialResult.result, "f");
3547
- __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_instances, "m", _QuerySubscriptionProxy_notifyCallbacks).call(this, initialResult.result);
3548
- if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initResolve, "f")) {
3549
- __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initResolve, "f").call(this, true);
3550
- __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initResolve, undefined, "f");
3551
- __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initReject, undefined, "f");
3552
- }
4130
+ __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_instances, "m", _QuerySubscriptionProxy_deliverResult).call(this, initialResult.result);
3553
4131
  }
3554
4132
  else {
3555
4133
  console.warn('⚠️ No initial result returned from subscribeQuery!');
@@ -3564,21 +4142,7 @@ class QuerySubscriptionProxy {
3564
4142
  }, 30000), "f");
3565
4143
  }
3566
4144
  // Subscribe to query updates
3567
- __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_unsubscribe, __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, "f").subscribeToQueryUpdates(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_subscriptionId, "f"), (updateResult) => {
3568
- // Clear timeout on first message
3569
- if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initTimeoutId, "f")) {
3570
- clearTimeout(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initTimeoutId, "f"));
3571
- __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initTimeoutId, undefined, "f");
3572
- }
3573
- // Resolve the initialization promise (only resolves once)
3574
- if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initResolve, "f")) {
3575
- __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initResolve, "f").call(this, true);
3576
- __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initResolve, undefined, "f"); // Prevent double-resolve
3577
- __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initReject, undefined, "f");
3578
- }
3579
- __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_latestResult, updateResult, "f");
3580
- __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_instances, "m", _QuerySubscriptionProxy_notifyCallbacks).call(this, updateResult);
3581
- }), "f");
4145
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_unsubscribe, __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, "f").subscribeToQueryUpdates(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_subscriptionId, "f"), (updateResult) => __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_instances, "m", _QuerySubscriptionProxy_deliverResult).call(this, updateResult)), "f");
3582
4146
  }
3583
4147
  catch (error) {
3584
4148
  console.error('Error setting up subscription:', error);
@@ -3588,36 +4152,117 @@ class QuerySubscriptionProxy {
3588
4152
  __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initResolve, undefined, "f");
3589
4153
  __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initReject, undefined, "f");
3590
4154
  }
4155
+ // Restore reconnect recovery before rethrowing. The listener was
4156
+ // removed at the top of this method; without re-installing one
4157
+ // here, a single failed resubscribe (e.g. subscribeQuery timing
4158
+ // out during a network flap) would leave the proxy permanently
4159
+ // dead: the keepalive loop stops itself on resubscribe failure,
4160
+ // and nothing else retries. The recovery listener runs the FULL
4161
+ // subscribe() (not the swap-in-place handler) because after a
4162
+ // failed attempt there is no keepalive loop left to feed the new
4163
+ // server subscription — subscribe() restarts it. This is
4164
+ // loop-safe: in this failed state the proxy owns no
4165
+ // `_wsCallbacks` entry (the old one was unsubscribed at the top
4166
+ // of this method and no new one got registered), so the
4167
+ // subscribe() it triggers has nothing to unsubscribe → the
4168
+ // socket never closes/reopens under it → no re-entrant onopen.
4169
+ if (!__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_disposed, "f") && __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_generation, "f") === generation && __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, "f").onReconnect) {
4170
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_reconnectUnsub, __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, "f").onReconnect(() => {
4171
+ if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_disposed, "f"))
4172
+ return;
4173
+ console.log('WebSocket reconnected — retrying failed subscription for query:', __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_query, "f"));
4174
+ this.subscribe().catch(e => {
4175
+ console.error('Error during subscription retry after reconnect:', e);
4176
+ });
4177
+ }), "f");
4178
+ }
3591
4179
  throw error; // Re-throw so caller knows it failed
3592
4180
  }
3593
- // Start keepalive loop using platform-agnostic setTimeout
3594
- const keepaliveLoop = async () => {
3595
- if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_disposed, "f"))
3596
- return;
3597
- try {
3598
- await __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, "f").keepAliveQuery(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_subscriptionId, "f"));
3599
- }
3600
- catch (e) {
3601
- console.error('Error in keepalive:', e);
3602
- // try to reinitialize the subscription
3603
- console.log('Reinitializing subscription for query:', __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_query, "f"));
4181
+ // Start keepalive loop
4182
+ __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_instances, "m", _QuerySubscriptionProxy_startKeepalive).call(this, generation);
4183
+ // Register for reconnect notification — on WebSocket reconnect,
4184
+ // immediately re-establish a fresh server-side subscription instead
4185
+ // of waiting up to 30s for the keepalive to fail.
4186
+ //
4187
+ // We deliberately do NOT call `this.subscribe()` here. Full subscribe
4188
+ // runs `#unsubscribe` first, which delegates to `ApiClient.subscribe`'s
4189
+ // deleter — that closes the WebSocket when this query owned the LAST
4190
+ // `_wsCallbacks` entry. The subsequent `subscribeQuery` reopens the
4191
+ // socket, whose fresh `onopen` fires every registered reconnect
4192
+ // callback again → recursion (CodeRabbit's original finding). And
4193
+ // during that close→reopen gap, RPCs in flight from OTHER proxies
4194
+ // fail with `503 WebSocket not connected` (observed in
4195
+ // integration-tests-mcp `should fire onWake when mention uses agent DID`
4196
+ // after PR #899's initial fix — the WakerSubscriptionManager tests
4197
+ // share a wakerClient across cases, so any dying reconnect handler
4198
+ // interferes with sibling subscriptions).
4199
+ //
4200
+ // The correct shape is a swap-in-place: get a new server-side
4201
+ // subscription ID via `subscribeQuery`, register a new client-side
4202
+ // callback FIRST, and only then unsubscribe the old one. That way
4203
+ // `_wsCallbacks.size` never dips to 0 during the transition, so the
4204
+ // socket doesn't close, no reconnect loop, and no cross-proxy 503s.
4205
+ // Any prior listener was already removed at the top of this method
4206
+ // (see the note there for why cleanup must run before `#unsubscribe`,
4207
+ // not here).
4208
+ if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, "f").onReconnect) {
4209
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_reconnectUnsub, __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, "f").onReconnect(async () => {
4210
+ var _a;
4211
+ if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_disposed, "f"))
4212
+ return;
4213
+ // The handler is a writer of `#unsubscribe`/`#subscriptionId`
4214
+ // too, so it takes its own generation — see #generation.
4215
+ const swapGeneration = __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_generation, (_a = __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_generation, "f"), ++_a), "f");
4216
+ console.log('WebSocket reconnected — re-establishing server subscription for query:', __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_query, "f"));
3604
4217
  try {
3605
- await this.subscribe();
3606
- console.log('Subscription reinitialized');
4218
+ const newInitial = await __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, "f").subscribeQuery(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_query, "f"));
4219
+ if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_disposed, "f") || __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_generation, "f") !== swapGeneration) {
4220
+ // A newer writer took over while we awaited — back out
4221
+ // and release the orphaned server-side subscription.
4222
+ __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, "f").disposeQuerySubscription(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_uuid, "f"), newInitial.subscriptionId)
4223
+ .catch(e => console.error('Error disposing superseded query subscription:', e));
4224
+ return;
4225
+ }
4226
+ const newSubId = newInitial.subscriptionId;
4227
+ // Register the NEW client-side callback BEFORE removing the
4228
+ // old one — keeps `_wsCallbacks.size >= 1` across the swap.
4229
+ const newUnsub = __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, "f").subscribeToQueryUpdates(newSubId, (updateResult) => __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_instances, "m", _QuerySubscriptionProxy_deliverResult).call(this, updateResult));
4230
+ const oldUnsub = __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_unsubscribe, "f");
4231
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_unsubscribe, newUnsub, "f");
4232
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_subscriptionId, newSubId, "f");
4233
+ if (oldUnsub)
4234
+ oldUnsub();
4235
+ // Our generation bump invalidated the running keepalive
4236
+ // loop — restart it under our generation so the new
4237
+ // server subscription keeps receiving keepalives.
4238
+ clearTimeout(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_keepaliveTimer, "f"));
4239
+ __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_instances, "m", _QuerySubscriptionProxy_startKeepalive).call(this, swapGeneration);
4240
+ // Deliver the fresh initial result if the server included one
4241
+ // (matches the eager-delivery path in the main subscribe() body).
4242
+ // #deliverResult also clears a still-pending init timeout and
4243
+ // resolves #initialized, keeping this path symmetric with the
4244
+ // update callback in subscribe() — without it, a swap landing
4245
+ // while initialization was pending would leave the 30s init
4246
+ // timer armed and trigger a spurious full resubscribe.
4247
+ if (newInitial.result !== undefined) {
4248
+ __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_instances, "m", _QuerySubscriptionProxy_deliverResult).call(this, newInitial.result);
4249
+ }
3607
4250
  }
3608
- catch (resubscribeError) {
3609
- console.error('Error during resubscription from keepalive:', resubscribeError);
3610
- // Don't schedule another keepalive on resubscribe failure
3611
- return;
4251
+ catch (error) {
4252
+ console.error('Error re-establishing subscription after reconnect:', error);
4253
+ // Our generation bump invalidated the running keepalive
4254
+ // loop; if nothing newer superseded us, restart it so
4255
+ // liveness is preserved — its keepAliveQuery against the
4256
+ // dead old subscription will fail and fall back to a
4257
+ // full subscribe(). The reconnect listener also remains
4258
+ // installed, so a later reconnect retries this handler.
4259
+ if (!__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_disposed, "f") && __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_generation, "f") === swapGeneration) {
4260
+ clearTimeout(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_keepaliveTimer, "f"));
4261
+ __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_instances, "m", _QuerySubscriptionProxy_startKeepalive).call(this, swapGeneration);
4262
+ }
3612
4263
  }
3613
- }
3614
- // Schedule next keepalive if not disposed
3615
- if (!__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_disposed, "f")) {
3616
- __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_keepaliveTimer, setTimeout(keepaliveLoop, 30000), "f");
3617
- }
3618
- };
3619
- // Start the first keepalive loop
3620
- __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_keepaliveTimer, setTimeout(keepaliveLoop, 30000), "f");
4264
+ }), "f");
4265
+ }
3621
4266
  }
3622
4267
  /** Get the subscription ID for this query subscription
3623
4268
  *
@@ -3690,11 +4335,19 @@ class QuerySubscriptionProxy {
3690
4335
  * will not receive any more updates. The instance should be discarded.
3691
4336
  */
3692
4337
  dispose() {
4338
+ var _a;
3693
4339
  __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_disposed, true, "f");
4340
+ // Invalidate any suspended writer so a mid-flight subscribe() or
4341
+ // reconnect swap backs out instead of resurrecting state.
4342
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_generation, (_a = __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_generation, "f"), _a++, _a), "f");
3694
4343
  clearTimeout(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_keepaliveTimer, "f"));
3695
4344
  if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_unsubscribe, "f")) {
3696
4345
  __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_unsubscribe, "f").call(this);
3697
4346
  }
4347
+ if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_reconnectUnsub, "f")) {
4348
+ __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_reconnectUnsub, "f").call(this);
4349
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_reconnectUnsub, undefined, "f");
4350
+ }
3698
4351
  __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_callbacks, "f").clear();
3699
4352
  if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initTimeoutId, "f")) {
3700
4353
  clearTimeout(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initTimeoutId, "f"));
@@ -3707,7 +4360,58 @@ class QuerySubscriptionProxy {
3707
4360
  }
3708
4361
  }
3709
4362
  }
3710
- _QuerySubscriptionProxy_uuid = new WeakMap(), _QuerySubscriptionProxy_subscriptionId = new WeakMap(), _QuerySubscriptionProxy_client = new WeakMap(), _QuerySubscriptionProxy_callbacks = new WeakMap(), _QuerySubscriptionProxy_keepaliveTimer = new WeakMap(), _QuerySubscriptionProxy_unsubscribe = new WeakMap(), _QuerySubscriptionProxy_latestResult = new WeakMap(), _QuerySubscriptionProxy_disposed = new WeakMap(), _QuerySubscriptionProxy_initialized = new WeakMap(), _QuerySubscriptionProxy_initResolve = new WeakMap(), _QuerySubscriptionProxy_initReject = new WeakMap(), _QuerySubscriptionProxy_initTimeoutId = new WeakMap(), _QuerySubscriptionProxy_query = new WeakMap(), _QuerySubscriptionProxy_instances = new WeakSet(), _QuerySubscriptionProxy_notifyCallbacks = function _QuerySubscriptionProxy_notifyCallbacks(result) {
4363
+ _QuerySubscriptionProxy_uuid = new WeakMap(), _QuerySubscriptionProxy_subscriptionId = new WeakMap(), _QuerySubscriptionProxy_client = new WeakMap(), _QuerySubscriptionProxy_callbacks = new WeakMap(), _QuerySubscriptionProxy_keepaliveTimer = new WeakMap(), _QuerySubscriptionProxy_unsubscribe = new WeakMap(), _QuerySubscriptionProxy_reconnectUnsub = new WeakMap(), _QuerySubscriptionProxy_latestResult = new WeakMap(), _QuerySubscriptionProxy_disposed = new WeakMap(), _QuerySubscriptionProxy_initialized = new WeakMap(), _QuerySubscriptionProxy_initResolve = new WeakMap(), _QuerySubscriptionProxy_initReject = new WeakMap(), _QuerySubscriptionProxy_initTimeoutId = new WeakMap(), _QuerySubscriptionProxy_query = new WeakMap(), _QuerySubscriptionProxy_generation = new WeakMap(), _QuerySubscriptionProxy_instances = new WeakSet(), _QuerySubscriptionProxy_deliverResult = function _QuerySubscriptionProxy_deliverResult(result) {
4364
+ if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initTimeoutId, "f")) {
4365
+ clearTimeout(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initTimeoutId, "f"));
4366
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initTimeoutId, undefined, "f");
4367
+ }
4368
+ // Resolve the initialization promise (only resolves once)
4369
+ if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initResolve, "f")) {
4370
+ __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initResolve, "f").call(this, true);
4371
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initResolve, undefined, "f"); // Prevent double-resolve
4372
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initReject, undefined, "f");
4373
+ }
4374
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_latestResult, result, "f");
4375
+ __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_instances, "m", _QuerySubscriptionProxy_notifyCallbacks).call(this, result);
4376
+ }, _QuerySubscriptionProxy_startKeepalive = function _QuerySubscriptionProxy_startKeepalive(generation) {
4377
+ const keepaliveLoop = async () => {
4378
+ // Generation check kills orphaned loops: a loop whose
4379
+ // keepAliveQuery was in flight while a newer writer ran is not
4380
+ // cancelled by clearTimeout and would otherwise reschedule
4381
+ // itself alongside the newer loop.
4382
+ if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_disposed, "f") || __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_generation, "f") !== generation)
4383
+ return;
4384
+ try {
4385
+ await __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, "f").keepAliveQuery(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_subscriptionId, "f"));
4386
+ }
4387
+ catch (e) {
4388
+ if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_disposed, "f") || __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_generation, "f") !== generation)
4389
+ return;
4390
+ console.error('Error in keepalive:', e);
4391
+ // try to reinitialize the subscription
4392
+ console.log('Reinitializing subscription for query:', __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_query, "f"));
4393
+ try {
4394
+ await this.subscribe();
4395
+ console.log('Subscription reinitialized');
4396
+ }
4397
+ catch (resubscribeError) {
4398
+ console.error('Error during resubscription from keepalive:', resubscribeError);
4399
+ // Don't schedule another keepalive on resubscribe failure.
4400
+ // Recovery is not lost: the failed subscribe() installed a
4401
+ // reconnect listener that retries the full subscribe.
4402
+ return;
4403
+ }
4404
+ // subscribe() succeeded and started its own keepalive loop
4405
+ // under a new generation — this loop is done.
4406
+ return;
4407
+ }
4408
+ // Schedule next keepalive if still the active generation
4409
+ if (!__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_disposed, "f") && __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_generation, "f") === generation) {
4410
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_keepaliveTimer, setTimeout(keepaliveLoop, 30000), "f");
4411
+ }
4412
+ };
4413
+ __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_keepaliveTimer, setTimeout(keepaliveLoop, 30000), "f");
4414
+ }, _QuerySubscriptionProxy_notifyCallbacks = function _QuerySubscriptionProxy_notifyCallbacks(result) {
3711
4415
  for (const callback of __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_callbacks, "f")) {
3712
4416
  try {
3713
4417
  callback(result);
@@ -3906,8 +4610,8 @@ class PerspectiveProxy {
3906
4610
  * });
3907
4611
  * ```
3908
4612
  */
3909
- async get(query) {
3910
- return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").queryLinks(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, query);
4613
+ async get(query, options) {
4614
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").queryLinks(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, query, options);
3911
4615
  }
3912
4616
  /**
3913
4617
  * Runs generic LLM interpretation over a conversation transcript, turning it
@@ -3922,8 +4626,38 @@ class PerspectiveProxy {
3922
4626
  * @param basePrefix URI namespace for new instance identities, e.g. `soa://ext/`
3923
4627
  * @param classes local names of the subject classes to extract into; omit for all
3924
4628
  */
3925
- async runInterpretation(transcript, basePrefix, classes) {
3926
- return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").runInterpretation(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, transcript, basePrefix, classes);
4629
+ async runInterpretation(transcript, basePrefix, classes, options) {
4630
+ // Grouped into an options bag rather than continuing the client's positional list.
4631
+ // The scopes were already unreachable from here for that reason, and a fourth, fifth and
4632
+ // sixth positional parameter would have made `undefined, undefined, { … }` the normal way
4633
+ // to ask for the only one of them most callers want.
4634
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").runInterpretation(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, transcript, basePrefix, classes, options?.existingScope, options?.mintScope, options?.observe);
4635
+ }
4636
+ /**
4637
+ * Harness-dispatched interpretation pass over this perspective (design v3
4638
+ * §6 — the tool-calling counterpart to {@link runInterpretation}). The LLM
4639
+ * sees a live per-class tool surface (`{Class}_query`, `{Class}_get`,
4640
+ * `{Class}_propose_create`, `{Class}_propose_link_child`, …) and drives
4641
+ * the extraction via tool calls; buffered proposals drain through the
4642
+ * same overlay gate the single-shot path uses.
4643
+ *
4644
+ * @param transcript ordered `{ speaker, text }` turns
4645
+ * @param basePrefix URI namespace new instance identities are minted under
4646
+ * @param maxToolCalls upper bound on tool calls the harness will make in
4647
+ * one pass (must be > 0 — use {@link runInterpretation} for the
4648
+ * classic single-shot path)
4649
+ * @param classes local names of the subject classes to extract into; omit for all
4650
+ * @param modelOverride optional model override; omit for the default LLM
4651
+ */
4652
+ async runInterpretationWithHarness(transcript, basePrefix, maxToolCalls, classes, modelOverride,
4653
+ // Optional live-debug observability. When both `observationId` and
4654
+ // `emitDebugEvents` are supplied, every dispatched tool call fires
4655
+ // `ToolCall` + `ToolResult` events on the `auto-processor-event`
4656
+ // topic keyed by `observationId`. Subscribe with
4657
+ // {@link addAutoProcessorEventListener} to render the harness loop
4658
+ // live in a UI. Absent = fast headless path (no telemetry cost).
4659
+ observationId, emitDebugEvents) {
4660
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").runInterpretationWithHarness(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, transcript, basePrefix, maxToolCalls, classes, modelOverride, undefined, observationId, emitDebugEvents);
3927
4661
  }
3928
4662
  /**
3929
4663
  * Register a neighbourhood auto-processor on this perspective. The executor
@@ -3934,6 +4668,24 @@ class PerspectiveProxy {
3934
4668
  async addAutoProcessor(config) {
3935
4669
  return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").addAutoProcessor(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, config);
3936
4670
  }
4671
+ /**
4672
+ * Stop an auto-processor by deleting its config.
4673
+ *
4674
+ * The registration is data — the watch loop reads the processor set back out of the
4675
+ * perspective's graph on every tick — so deleting the config is what stops it, and there is
4676
+ * nothing else to unregister. The config is `Shared`, so this stops the processor for the
4677
+ * neighbourhood rather than only for this peer.
4678
+ *
4679
+ * Resolves `true` when there was a processor to remove and `false` when there was not; a
4680
+ * processor another peer has already removed is not an error.
4681
+ *
4682
+ * The processor's `InterpretationRun` nodes stay: they are the record of what it did and the
4683
+ * processed-turn cursor, so a processor later registered under the same id resumes where this
4684
+ * one left off rather than re-reading every turn.
4685
+ */
4686
+ async removeAutoProcessor(processorId) {
4687
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").removeAutoProcessor(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, processorId);
4688
+ }
3937
4689
  /**
3938
4690
  * Pending interpretation overlays on this perspective — LLM suggestions the
3939
4691
  * §4 divergence gate staged rather than applied, awaiting human accept/reject.
@@ -3994,8 +4746,8 @@ class PerspectiveProxy {
3994
4746
  * `);
3995
4747
  * ```
3996
4748
  */
3997
- async infer(query) {
3998
- return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").queryProlog(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, query);
4749
+ async infer(query, options) {
4750
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").queryProlog(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, query, options);
3999
4751
  }
4000
4752
  /**
4001
4753
  * Executes a SPARQL query against the perspective's link cache.
@@ -4005,19 +4757,25 @@ class PerspectiveProxy {
4005
4757
  * Mutating operations (DELETE, UPDATE, INSERT, CREATE, DROP, DEFINE, etc.) are
4006
4758
  * blocked for security reasons. Use the perspective's add/remove methods to modify links.
4007
4759
  *
4008
- * @param query - SPARQL query string (read-only operations only)
4009
- * @returns Query results as parsed JSON
4010
- *
4011
- * Executes a SPARQL query against the perspective's RDF (Oxigraph) store.
4760
+ * **Cancellation:** Pass `{ signal }` from an `AbortController` to abort
4761
+ * an in-flight query. The executor receives `request.cancel` over the
4762
+ * WebSocket and short-circuits the JSON reply. Caveat: Oxigraph itself
4763
+ * cannot be interrupted mid-evaluation, so an already-running scan will
4764
+ * keep its blocking thread busy until it completes; what's saved is the
4765
+ * serialise + network + client-deserialise tax on the result. Aborted
4766
+ * calls reject with `DOMException('Aborted', 'AbortError')` — match
4767
+ * `fetch()` for handling. Cached results bypass the round-trip entirely
4768
+ * and are returned synchronously, ignoring the signal.
4012
4769
  *
4013
- * @param query - SPARQL query string
4770
+ * @param query - SPARQL query string (read-only operations only)
4771
+ * @param options - Optional call options (e.g. AbortSignal for cancellation)
4014
4772
  * @returns Query results as parsed JSON
4015
4773
  */
4016
- async querySparql(query) {
4774
+ async querySparql(query, options) {
4017
4775
  const cached = getCachedResult(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, query);
4018
4776
  if (cached !== undefined)
4019
4777
  return cached;
4020
- const result = await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").querySparql(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, query);
4778
+ const result = await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").querySparql(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, query, options);
4021
4779
  setCachedResult(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, query, result);
4022
4780
  return result;
4023
4781
  }
@@ -4032,8 +4790,43 @@ class PerspectiveProxy {
4032
4790
  * @param queryJson - Structured query as JSON string
4033
4791
  * @returns Object with `instances` array and `totalCount`
4034
4792
  */
4035
- async modelQuery(className, queryJson) {
4036
- return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").modelQuery(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, className, queryJson);
4793
+ async modelQuery(className, queryJson, options) {
4794
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").modelQuery(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, className, queryJson, options);
4795
+ }
4796
+ /** Resolve each URI to the names of every subject class it is an instance of.
4797
+ *
4798
+ * The counterpart of {@link isSubjectInstance}, which asks the same question
4799
+ * one class at a time. Without this, finding the class of an arbitrary URI
4800
+ * meant looping over every registered class — a round trip each — and doing
4801
+ * it again for every URI.
4802
+ *
4803
+ * Class membership in AD4M is structural — a URI belongs to a class when it
4804
+ * carries that class's flags and required properties — so membership is **not
4805
+ * exclusive**: an instance conforms to its parent classes, and to any
4806
+ * unrelated class whose required set happens to be a subset of what it
4807
+ * carries. Every match is returned.
4808
+ *
4809
+ * The list is ordered **most specific first**, meaning by the number of
4810
+ * triples the class requires — a subclass requires everything its parent does
4811
+ * and more — with ties broken alphabetically so that every peer answers
4812
+ * identically. A caller that can only act on one class should take
4813
+ * `classes[0]`, but that head is only a heuristic: it is arbitrary between two
4814
+ * unrelated classes requiring the same number of triples, which is exactly
4815
+ * the case the full list exists to expose.
4816
+ *
4817
+ * A URI is **absent from the result** when no *registered* class matched it.
4818
+ * That covers two situations, and nothing here separates them: the URI may
4819
+ * not be a subject instance at all, or it may be an instance of a class this
4820
+ * perspective has not registered. Absence is used rather than an empty list
4821
+ * because an empty list would claim the stronger thing — that the URI belongs
4822
+ * to no class — which this cannot know.
4823
+ *
4824
+ * @param uris The expression URIs to classify.
4825
+ */
4826
+ async subjectClassesOf(uris) {
4827
+ if (uris.length === 0)
4828
+ return {};
4829
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").subjectClassesOf(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, uris);
4037
4830
  }
4038
4831
  /**
4039
4832
  * Evaluate property getters for a batch of instances in a single RPC call.
@@ -4369,116 +5162,48 @@ class PerspectiveProxy {
4369
5162
  }
4370
5163
  });
4371
5164
  }
4372
- /** Returns all Social DNA flows that can be started from the given expression */
5165
+ /**
5166
+ * Returns all Social DNA flows that can be started from the given expression.
5167
+ *
5168
+ * Post-`flowable` retirement: a flow is a candidate iff its `inputTypes`
5169
+ * declaration is compatible with the expression. Matching rules:
5170
+ * - Empty `inputTypes` or one containing the `"any"` wildcard → always
5171
+ * matches (same behaviour as the legacy `flowable === "any"` case).
5172
+ * - Otherwise, at least one of the expression's registered subject-class
5173
+ * URIs (resolved via {@link subjectClassesOf}) must appear in
5174
+ * `inputTypes`. This is the concrete-type match the design doc's §5
5175
+ * spawn engine calls for; without it, a flow declaring
5176
+ * `inputTypes: ["Task"]` was previously *never* returned by
5177
+ * `availableFlows("some-task-uri")` — the entire point of typed
5178
+ * flows was silently unreachable (James PR #929 J#3).
5179
+ *
5180
+ * The expression is classified against the perspective's registered
5181
+ * classes only. An expression whose class is not registered on this
5182
+ * perspective matches no typed flow (absence, not falsehood — same
5183
+ * discipline as {@link subjectClassesOf}); typed flows requiring
5184
+ * unknown classes are still returned to their untyped-caller peers.
5185
+ */
4373
5186
  async availableFlows(exprAddr) {
4374
5187
  const allFlowNames = await this.sdnaFlows();
5188
+ if (allFlowNames.length === 0)
5189
+ return [];
5190
+ const classesOf = await this.subjectClassesOf([exprAddr]);
5191
+ const exprClasses = classesOf[exprAddr] ?? [];
4375
5192
  const available = [];
4376
5193
  for (const name of allFlowNames) {
4377
5194
  const flow = await this.getFlow(name);
4378
5195
  if (!flow)
4379
5196
  continue;
4380
- if (flow.flowable === "any") {
5197
+ if (flow.inputTypes.length === 0 || flow.inputTypes.includes("any")) {
4381
5198
  available.push(name);
5199
+ continue;
4382
5200
  }
4383
- else {
4384
- // Check if the expression matches the flowable link pattern
4385
- const pattern = flow.flowable;
4386
- const source = pattern.source || exprAddr;
4387
- const links = await this.get(new LinkQuery({
4388
- source,
4389
- predicate: pattern.predicate,
4390
- target: pattern.target
4391
- }));
4392
- if (links.length > 0) {
4393
- available.push(name);
4394
- }
5201
+ if (exprClasses.some(cls => flow.inputTypes.includes(cls))) {
5202
+ available.push(name);
4395
5203
  }
4396
5204
  }
4397
5205
  return available;
4398
5206
  }
4399
- /** Starts the Social DNA flow @param flowName on the expression @param exprAddr */
4400
- async startFlow(flowName, exprAddr) {
4401
- const flow = await this.getFlow(flowName);
4402
- if (!flow)
4403
- throw `Flow "${flowName}" not found`;
4404
- if (flow.startAction.length === 0)
4405
- throw `Flow "${flowName}" has no start action`;
4406
- await this.executeAction(flow.startAction, exprAddr, undefined);
4407
- }
4408
- /** Returns all expressions in the given state of given Social DNA flow */
4409
- async expressionsInFlowState(flowName, flowState) {
4410
- const flow = await this.getFlow(flowName);
4411
- if (!flow)
4412
- return [];
4413
- // Find the state with the matching value
4414
- const state = flow.states.find(s => s.value === flowState);
4415
- if (!state)
4416
- return [];
4417
- // Query for expressions matching this state's check pattern
4418
- const pattern = state.stateCheck;
4419
- const links = await this.get(new LinkQuery({
4420
- predicate: pattern.predicate,
4421
- target: pattern.target
4422
- }));
4423
- // Return the sources (expression addresses) - use source if pattern has no explicit source
4424
- return links.map(l => pattern.source ? l.data.target : l.data.source);
4425
- }
4426
- /** Returns the given expression's flow state with regard to given Social DNA flow */
4427
- async flowState(flowName, exprAddr) {
4428
- const flow = await this.getFlow(flowName);
4429
- if (!flow)
4430
- throw `Flow "${flowName}" not found`;
4431
- // Check each state to find which one the expression is in
4432
- for (const state of flow.states) {
4433
- const pattern = state.stateCheck;
4434
- const source = pattern.source || exprAddr;
4435
- const links = await this.get(new LinkQuery({
4436
- source,
4437
- predicate: pattern.predicate,
4438
- target: pattern.target
4439
- }));
4440
- if (links.length > 0)
4441
- return state.value;
4442
- }
4443
- throw `Expression "${exprAddr}" is not in any state of flow "${flowName}"`;
4444
- }
4445
- /** Returns available action names, with regard to Social DNA flow and expression's flow state */
4446
- async flowActions(flowName, exprAddr) {
4447
- const flow = await this.getFlow(flowName);
4448
- if (!flow)
4449
- return [];
4450
- // Determine current state
4451
- let currentStateName = null;
4452
- for (const state of flow.states) {
4453
- const pattern = state.stateCheck;
4454
- const source = pattern.source || exprAddr;
4455
- const links = await this.get(new LinkQuery({
4456
- source,
4457
- predicate: pattern.predicate,
4458
- target: pattern.target
4459
- }));
4460
- if (links.length > 0) {
4461
- currentStateName = state.name;
4462
- break;
4463
- }
4464
- }
4465
- if (!currentStateName)
4466
- return [];
4467
- // Return transitions available from current state
4468
- return flow.transitions
4469
- .filter(t => t.fromState === currentStateName)
4470
- .map(t => t.actionName);
4471
- }
4472
- /** Runs given Social DNA flow action */
4473
- async runFlowAction(flowName, exprAddr, actionName) {
4474
- const flow = await this.getFlow(flowName);
4475
- if (!flow)
4476
- throw `Flow "${flowName}" not found`;
4477
- const transition = flow.transitions.find(t => t.actionName === actionName);
4478
- if (!transition)
4479
- throw `Action "${actionName}" not found in flow "${flowName}"`;
4480
- await this.executeAction(transition.actions, exprAddr, undefined);
4481
- }
4482
5207
  /** Returns the perspective's Social DNA code
4483
5208
  * This will return all SDNA code elements in an array.
4484
5209
  */
@@ -4658,111 +5383,45 @@ class PerspectiveProxy {
4658
5383
  await this.addLinks(allLinks);
4659
5384
  }
4660
5385
  /**
4661
- * Retrieve a SHACL shape by name from this Perspective
5386
+ * Retrieve a SHACL shape by name from this Perspective (one RPC call).
5387
+ * The executor resolves the full shape (including property sub-shapes)
5388
+ * in-process and returns link triples for client-side reconstruction.
4662
5389
  */
4663
5390
  async getShacl(name) {
4664
- // Find the shape URI from the name mapping
4665
- const nameMapping = Literal.fromUrl(`literal:string:shacl://${name}`);
4666
- const shapeUriLinks = await this.get(new LinkQuery({
4667
- source: nameMapping.toUrl(),
4668
- predicate: "ad4m://shacl_shape_uri"
4669
- }));
4670
- if (shapeUriLinks.length === 0) {
5391
+ const result = await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").getShacl(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, name);
5392
+ if (!result)
4671
5393
  return null;
4672
- }
4673
- const shapeUri = shapeUriLinks[0].data.target;
4674
- // First get property shape URIs so we can query everything in one go
4675
- const propertyLinks = await this.get(new LinkQuery({
4676
- source: shapeUri,
4677
- predicate: "sh://property"
4678
- }));
4679
- // Fetch all links from the shape and its property shapes. These reads are
4680
- // independent of each other, so fire them concurrently rather than one RPC
4681
- // round trip at a time — over a remote (non-loopback) connection, a shape with
4682
- // a dozen properties otherwise pays a dozen sequential round trips just to load.
4683
- const sourceUris = [shapeUri, ...propertyLinks.map(l => l.data.target)];
4684
- const linksByUri = await Promise.all(sourceUris.map(uri => this.get(new LinkQuery({ source: uri }))));
4685
- // Dedupe by (source, predicate, target): a perspective that's accumulated duplicate
4686
- // SDNA links (e.g. from repeated registration attempts, or executor-side sync bugs)
4687
- // would otherwise feed the same triple into SHACLShape.fromLinks more than once —
4688
- // harmless for scalar fields like targetClass (first match wins) but can surface as
4689
- // visibly duplicated properties for repeated sh://property links. Cheap: this is an
4690
- // in-memory pass over data already fetched, no extra round trips.
4691
- const seenLinks = new Set();
4692
- const allLinks = [];
4693
- for (const links of linksByUri) {
4694
- for (const l of links) {
4695
- const key = `${l.data.source} ${l.data.predicate} ${l.data.target}`;
4696
- if (seenLinks.has(key))
4697
- continue;
4698
- seenLinks.add(key);
4699
- allLinks.push({
4700
- source: l.data.source,
4701
- predicate: l.data.predicate,
4702
- target: l.data.target
4703
- });
4704
- }
4705
- }
4706
- const shapeLinks = allLinks;
4707
- return SHACLShape.fromLinks(shapeLinks, shapeUri);
5394
+ return SHACLShape.fromLinks(result.links, result.shapeUri);
4708
5395
  }
4709
5396
  /**
4710
- * List the names of every SHACL shape stored in this Perspective, without fetching
4711
- * each shape's full definition (properties, target class, etc.) — just the cheap
4712
- * `ad4m://has_shacl` enumeration, one round trip regardless of how many shapes exist.
4713
- * Use this to check which shapes are actually worth resolving via `getShacl()` before
4714
- * paying for each one's full (multi-round-trip) fetch.
5397
+ * List the names of every SHACL shape stored in this Perspective (one RPC call).
4715
5398
  */
4716
5399
  async getShaclNames() {
4717
- const nameLinks = await this.get(new LinkQuery({
4718
- source: "ad4m://self",
4719
- predicate: "ad4m://has_shacl"
4720
- }));
4721
- // Dedupe: a perspective with duplicate `has_shacl` links (see the dedup note in
4722
- // getShacl()) would otherwise report the same name more than once, causing callers
4723
- // to redundantly resolve (or redundantly disambiguate) it multiple times.
4724
- const names = nameLinks.map((nameLink) => {
4725
- const name = Literal.fromUrl(nameLink.data.target).get();
4726
- return name.replace('shacl://', '');
4727
- });
4728
- return [...new Set(names)];
5400
+ return __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").getShaclNames(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid);
4729
5401
  }
4730
5402
  /**
4731
- * Resolve just a shape's `sh:targetClass` by name, without fetching its properties —
4732
- * two round trips (name → shapeUri, then shapeUri's own direct triples) instead of
4733
- * `getShacl()`'s full walk (which also fetches every property sub-shape). Use this to
4734
- * disambiguate a shape name that collides with another app's `@Model({ name })` string
4735
- * (the bare `shacl://{name}` mapping ad4m-core uses is namespace-blind — see
4736
- * `getShaclNames()` callers for why that matters) before paying for a full fetch.
5403
+ * Resolve a shape's `sh:targetClass` by name (one RPC call).
5404
+ *
5405
+ * `PerspectiveClient.getShaclTargetClass` now returns `undefined` on
5406
+ * "not found" already (see review r3897752023 — the null→undefined
5407
+ * coercion used to happen here and be duplicated one layer down),
5408
+ * so this method is a pure passthrough.
4737
5409
  */
4738
5410
  async getShaclTargetClass(name) {
4739
- const nameMapping = Literal.fromUrl(`literal:string:shacl://${name}`);
4740
- const shapeUriLinks = await this.get(new LinkQuery({
4741
- source: nameMapping.toUrl(),
4742
- predicate: "ad4m://shacl_shape_uri"
4743
- }));
4744
- if (shapeUriLinks.length === 0) {
4745
- return undefined;
4746
- }
4747
- const shapeUri = shapeUriLinks[0].data.target;
4748
- const shapeOwnLinks = await this.get(new LinkQuery({ source: shapeUri }));
4749
- return shapeOwnLinks.find(l => l.data.predicate === "sh://targetClass")?.data.target;
5411
+ return __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").getShaclTargetClass(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, name);
4750
5412
  }
4751
5413
  /**
4752
- * Get all SHACL shapes stored in this Perspective
5414
+ * Get all SHACL shapes stored in this Perspective (one RPC call).
5415
+ * The executor resolves all shapes in-process and returns them in bulk.
4753
5416
  */
4754
5417
  async getAllShacl() {
4755
- const shapeNames = await this.getShaclNames();
4756
- // Each shape is fetched independently of the others — resolve them concurrently.
4757
- // Sequentially awaiting getShacl() per shape means a perspective with N SDNA
4758
- // models pays N times getShacl()'s own multi-round-trip cost one after another;
4759
- // over a remote connection with real per-call latency that compounds into the
4760
- // dominant cost of switching into a perspective at all.
4761
- const results = await Promise.all(shapeNames.map(async (shapeName) => {
4762
- const shape = await this.getShacl(shapeName);
4763
- return shape ? { name: shapeName, shape } : null;
4764
- }));
4765
- return results.filter((s) => s !== null);
5418
+ const entries = await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").getAllShacl(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid);
5419
+ return entries
5420
+ .map(({ name, shapeUri, links }) => {
5421
+ const shape = SHACLShape.fromLinks(links, shapeUri);
5422
+ return shape ? { name, shape } : null;
5423
+ })
5424
+ .filter((s) => s !== null);
4766
5425
  }
4767
5426
  /**
4768
5427
  * **Recommended way to add Flow definitions.**
@@ -4777,28 +5436,26 @@ class PerspectiveProxy {
4777
5436
  * ```typescript
4778
5437
  * import { SHACLFlow } from '@coasys/ad4m';
4779
5438
  *
4780
- * const todoFlow = new SHACLFlow('TODO', 'todo://');
4781
- * todoFlow.flowable = 'any';
4782
- *
4783
- * // Define states
4784
- * todoFlow.addState({ name: 'ready', value: 0, stateCheck: { predicate: 'todo://state', target: 'todo://ready' }});
4785
- * todoFlow.addState({ name: 'done', value: 1, stateCheck: { predicate: 'todo://state', target: 'todo://done' }});
4786
- *
4787
- * // Define start action
4788
- * todoFlow.startAction = [{ action: 'addLink', source: 'this', predicate: 'todo://state', target: 'todo://ready' }];
4789
- *
4790
- * // Define transitions
4791
- * todoFlow.addTransition({
4792
- * actionName: 'Complete',
4793
- * fromState: 'ready',
4794
- * toState: 'done',
4795
- * actions: [
4796
- * { action: 'addLink', source: 'this', predicate: 'todo://state', target: 'todo://done' },
4797
- * { action: 'removeLink', source: 'this', predicate: 'todo://state', target: 'todo://ready' }
4798
- * ]
4799
- * });
5439
+ * const deliveryFlow = new SHACLFlow('Delivery', 'delivery://');
5440
+ * deliveryFlow.inputTypes = ['Task'];
5441
+ * deliveryFlow.interpretationHint =
5442
+ * 'Advance a Task through delivery: Identified → Scoped → InProgress → Review → Done.';
5443
+ *
5444
+ * deliveryFlow.addState({ name: 'Identified', value: 0 });
5445
+ * deliveryFlow.addState({ name: 'Scoped', value: 1 });
5446
+ * deliveryFlow.addState({ name: 'InProgress', value: 2 });
5447
+ * deliveryFlow.addState({ name: 'Review', value: 3 });
5448
+ * deliveryFlow.addState({ name: 'Done', value: 4 });
5449
+ *
5450
+ * deliveryFlow.addTransition({ actionName: 'Scope', fromState: 'Identified', toState: 'Scoped', actions: [] });
5451
+ * deliveryFlow.addTransition({ actionName: 'Start', fromState: 'Scoped', toState: 'InProgress', actions: [] });
5452
+ * deliveryFlow.addTransition({ actionName: 'Submit', fromState: 'InProgress', toState: 'Review', actions: [] });
5453
+ * deliveryFlow.addTransition({ actionName: 'Accept', fromState: 'Review', toState: 'Done', actions: [] });
4800
5454
  *
4801
- * await perspective.addFlow('TODO', todoFlow);
5455
+ * // Optional: n distinct DIDs must co-sign a proposal before it fires.
5456
+ * deliveryFlow.consensusRule = { n: 2 };
5457
+ *
5458
+ * await perspective.addFlow('Delivery', deliveryFlow);
4802
5459
  * ```
4803
5460
  */
4804
5461
  async addFlow(name, flow) {
@@ -4843,7 +5500,7 @@ class PerspectiveProxy {
4843
5500
  return null;
4844
5501
  }
4845
5502
  const flowUri = flowUriLinks[0].data.target;
4846
- // Fetch flow-level links (hasState, hasTransition, flowable, startAction)
5503
+ // Fetch flow-level links (hasState, hasTransition, startAction, inputTypes/outputTypes/…)
4847
5504
  const flowLevelLinks = await this.get(new LinkQuery({ source: flowUri }));
4848
5505
  // Collect state and transition URIs, then fetch their child links
4849
5506
  const childUris = flowLevelLinks
@@ -4909,7 +5566,9 @@ class PerspectiveProxy {
4909
5566
  * with the properties of the subject class.
4910
5567
  * @param exprAddr The address of the expression to be turned into a subject instance
4911
5568
  * @param initialValues Optional initial values for properties. If provided, these will be
4912
- * merged with constructor actions for better performance.
5569
+ * merged with constructor actions for better performance. A collection property accepts
5570
+ * an array value and stores one entry per element; scalar properties store arrays/objects
5571
+ * as a single JSON value.
4913
5572
  * @param batchId Optional batch ID for grouping operations. If provided, returns the expression address
4914
5573
  * instead of the subject proxy since the subject won't exist until the batch is committed.
4915
5574
  * @returns A proxy object for the created subject, or just the expression address if in batch mode
@@ -5696,7 +6355,7 @@ class PerspectiveClient {
5696
6355
  async publishSnapshotByUUID(uuid) {
5697
6356
  return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.publishSnapshot', { uuid });
5698
6357
  }
5699
- async queryLinks(uuid, query) {
6358
+ async queryLinks(uuid, query, options) {
5700
6359
  const params = { uuid };
5701
6360
  if (query.source)
5702
6361
  params.source = query.source;
@@ -5710,14 +6369,14 @@ class PerspectiveClient {
5710
6369
  params.untilDate = query.untilDate instanceof Date ? query.untilDate.toISOString() : String(query.untilDate);
5711
6370
  if (query.limit !== undefined)
5712
6371
  params.limit = query.limit;
5713
- return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.queryLinks', params);
6372
+ return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.queryLinks', params, options);
5714
6373
  }
5715
- async queryProlog(uuid, query) {
5716
- const result = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.queryProlog', { uuid, query });
6374
+ async queryProlog(uuid, query, options) {
6375
+ const result = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.queryProlog', { uuid, query }, options);
5717
6376
  return JSON.parse(result);
5718
6377
  }
5719
- async querySparql(uuid, query) {
5720
- const result = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.querySparql', { uuid, engine: 'sparql', query });
6378
+ async querySparql(uuid, query, options) {
6379
+ const result = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.querySparql', { uuid, engine: 'sparql', query }, options);
5721
6380
  return JSON.parse(result);
5722
6381
  }
5723
6382
  async subscribeQuery(uuid, query) {
@@ -5757,10 +6416,13 @@ class PerspectiveClient {
5757
6416
  }
5758
6417
  return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.disposeQuery', { uuid, subscriptionId });
5759
6418
  }
5760
- async modelQuery(uuid, className, queryJson) {
5761
- const resultJson = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.modelQuery', { uuid, class_name: className, query_json: queryJson });
6419
+ async modelQuery(uuid, className, queryJson, options) {
6420
+ const resultJson = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.modelQuery', { uuid, class_name: className, query_json: queryJson }, options);
5762
6421
  return JSON.parse(resultJson);
5763
6422
  }
6423
+ async subjectClassesOf(uuid, uris) {
6424
+ return await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.subjectClassesOf', { uuid, uris });
6425
+ }
5764
6426
  async evaluateGetters(uuid, className, instanceIds, propertyNames) {
5765
6427
  const resultJson = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.evaluateGetters', {
5766
6428
  uuid,
@@ -5818,9 +6480,55 @@ class PerspectiveClient {
5818
6480
  * `mintScope.id` via its predicate (upserts of pre-existing instances
5819
6481
  * are NOT re-parented — same rule as the watcher).
5820
6482
  */
5821
- async runInterpretation(uuid, transcript, basePrefix, classes, existingScope, mintScope) {
6483
+ async runInterpretation(uuid, transcript, basePrefix, classes, existingScope, mintScope, observe) {
5822
6484
  const RUN_INTERPRETATION_TIMEOUT_MS = 20 * 60 * 1000;
5823
- return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.runInterpretation', { uuid, transcript, basePrefix, classes, existingScope, mintScope }, RUN_INTERPRETATION_TIMEOUT_MS);
6485
+ return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.runInterpretation', {
6486
+ uuid, transcript, basePrefix, classes, existingScope, mintScope,
6487
+ // Spread rather than always-present, so a client talking to a pre-#903
6488
+ // executor sends exactly the params it sent before. `serde` would ignore
6489
+ // the extra keys anyway; keeping the wire identical means a bug report
6490
+ // from an older node cannot be about these.
6491
+ ...(observe ? {
6492
+ observationId: observe.observationId,
6493
+ emitDebugEvents: observe.emitDebugEvents ?? false,
6494
+ } : {}),
6495
+ }, { timeoutMs: RUN_INTERPRETATION_TIMEOUT_MS });
6496
+ }
6497
+ /**
6498
+ * Tool-calling counterpart to {@link runInterpretation}. The LLM sees a
6499
+ * live per-class tool surface (`{Class}_query`, `{Class}_propose_create`,
6500
+ * `{Class}_propose_link_child`, …) and drives the extraction via tool
6501
+ * calls; buffered proposals drain through the same overlay gate the
6502
+ * single-shot path uses.
6503
+ *
6504
+ * `maxToolCalls` bounds the loop and MUST be > 0 — zero would collapse
6505
+ * the harness to a no-op final-answer step; use {@link runInterpretation}
6506
+ * for the classic single-shot path.
6507
+ *
6508
+ * Same 20-minute RPC timeout as the single-shot path — an LLM loop
6509
+ * that calls several tools can legitimately take longer than one plain
6510
+ * generation.
6511
+ */
6512
+ async runInterpretationWithHarness(uuid, transcript, basePrefix, maxToolCalls, classes, modelOverride, existingScope,
6513
+ // Optional live-debug event surface — same shape/semantics as the
6514
+ // single-shot `runInterpretation`. `observationId` names the
6515
+ // `processor_id` + `batch_key` on emitted `ToolCall` / `ToolResult`
6516
+ // events so a subscribed UI can correlate them to this pass.
6517
+ // `emitDebugEvents` is a dead-letter without an observationId
6518
+ // (nothing to key against); the server gates on both.
6519
+ observationId, emitDebugEvents) {
6520
+ const RUN_INTERPRETATION_TIMEOUT_MS = 20 * 60 * 1000;
6521
+ return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.runInterpretationWithHarness', {
6522
+ uuid,
6523
+ transcript,
6524
+ basePrefix,
6525
+ maxToolCalls,
6526
+ classes,
6527
+ modelOverride,
6528
+ existingScope,
6529
+ observationId,
6530
+ emitDebugEvents,
6531
+ }, { timeoutMs: RUN_INTERPRETATION_TIMEOUT_MS });
5824
6532
  }
5825
6533
  /**
5826
6534
  * Register a neighbourhood auto-processor on this perspective. The executor's
@@ -5833,6 +6541,10 @@ class PerspectiveClient {
5833
6541
  async addAutoProcessor(uuid, config) {
5834
6542
  return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.addAutoProcessor', { uuid, ...config });
5835
6543
  }
6544
+ /** Delete an auto-processor's config. `false` when there was none to delete. */
6545
+ async removeAutoProcessor(uuid, processorId) {
6546
+ return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.removeAutoProcessor', { uuid, processorId });
6547
+ }
5836
6548
  /** Pending interpretation overlays (LLM suggestions awaiting human accept/reject). */
5837
6549
  async interpretationOverlays(uuid) {
5838
6550
  return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.interpretationOverlays', { uuid });
@@ -5915,6 +6627,43 @@ class PerspectiveClient {
5915
6627
  async getSubjectData(uuid, subjectClass, expressionAddress) {
5916
6628
  return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.getSubjectData', { uuid, subjectClass, expressionAddress });
5917
6629
  }
6630
+ // ── SHACL resolution (server-side) ─────────────────────────────────────────
6631
+ // These methods delegate shape resolution to the executor, which reads links
6632
+ // from its local store in-process. Each call replaces the multi-round-trip
6633
+ // `queryLinks` sequences the old PerspectiveProxy methods performed.
6634
+ /** List the names of every SHACL shape stored in a perspective (one RPC call). */
6635
+ async getShaclNames(uuid) {
6636
+ return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.getShaclNames', { uuid });
6637
+ }
6638
+ /**
6639
+ * Resolve a shape's `sh:targetClass` by name (one RPC call).
6640
+ *
6641
+ * Returns `undefined` when the shape (or its `sh://targetClass` edge) is
6642
+ * absent — unified with `PerspectiveProxy.getShaclTargetClass` so callers
6643
+ * see a single "not found" representation across both layers. The
6644
+ * executor wire format is still `null` (see `perspective.getShaclTargetClass`
6645
+ * in `perspectives_ws.rs`); this method maps that at the boundary rather
6646
+ * than pushing the null one layer further up. PR #935 review r3897752023.
6647
+ */
6648
+ async getShaclTargetClass(uuid, name) {
6649
+ const result = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.getShaclTargetClass', { uuid, name });
6650
+ return result ?? undefined;
6651
+ }
6652
+ /**
6653
+ * Retrieve a single SHACL shape's link triples by name (one RPC call).
6654
+ * Returns `{shapeUri, links}` for reconstruction via `SHACLShape.fromLinks()`,
6655
+ * or `null` if no shape with that name exists.
6656
+ */
6657
+ async getShacl(uuid, name) {
6658
+ return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.getShacl', { uuid, name });
6659
+ }
6660
+ /**
6661
+ * Retrieve all SHACL shapes in one call. Returns an array of
6662
+ * `{name, shapeUri, links}` — one entry per shape (one RPC call).
6663
+ */
6664
+ async getAllShacl(uuid) {
6665
+ return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.getAllShacl', { uuid });
6666
+ }
5918
6667
  // ExpressionClient functions, needed for Subjects:
5919
6668
  async getExpression(expressionURI) {
5920
6669
  return await __classPrivateFieldGet$9(this, _PerspectiveClient_expressionClient, "f").get(expressionURI);
@@ -6036,6 +6785,11 @@ class PerspectiveClient {
6036
6785
  async commitBatch(uuid, batchId) {
6037
6786
  return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.commitBatch', { uuid, batchId });
6038
6787
  }
6788
+ /** Register a callback that fires after a successful WebSocket reconnect.
6789
+ * Passes through to ApiClient.onReconnect(). Returns an unsubscribe function. */
6790
+ onReconnect(callback) {
6791
+ return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").onReconnect(callback);
6792
+ }
6039
6793
  }
6040
6794
  _PerspectiveClient_apiClient = new WeakMap(), _PerspectiveClient_perspectiveAddedCallbacks = new WeakMap(), _PerspectiveClient_perspectiveUpdatedCallbacks = new WeakMap(), _PerspectiveClient_perspectiveRemovedCallbacks = new WeakMap(), _PerspectiveClient_perspectiveSyncStateChangeCallbacks = new WeakMap(), _PerspectiveClient_expressionClient = new WeakMap(), _PerspectiveClient_neighbourhoodClient = new WeakMap(), _PerspectiveClient_aiClient = new WeakMap(), _PerspectiveClient_unsubscribers = new WeakMap(), _PerspectiveClient_linkUnsubscribers = new WeakMap(), _PerspectiveClient_querySubscriptionUnsubscribers = new WeakMap();
6041
6795
 
@@ -14214,9 +14968,12 @@ class AIClient {
14214
14968
  async embed(modelId, text) {
14215
14969
  const aiEmbed = await __classPrivateFieldGet$2(this, _AIClient_apiClient, "f").call('ai.embed', { modelId, text });
14216
14970
  const compressed = base64Js.toByteArray(aiEmbed);
14217
- // Decode to a string via TextDecoder rather than pako's `{ to: 'string' }`
14218
- // option: newer @types/pako dropped that overload, which broke the build.
14219
- const decompressed = JSON.parse(new TextDecoder().decode(pako.inflate(compressed)));
14971
+ // NB: pako v1 accepts `{ to: 'string' }`, pako v2 wants `{ toText: true }`,
14972
+ // pako v3 also drops that overload from its bundled types. Call the
14973
+ // version-agnostic form (returns Uint8Array) and decode explicitly so
14974
+ // this works regardless of which pako major the lockfile pins.
14975
+ const inflated = pako.inflate(compressed);
14976
+ const decompressed = JSON.parse(new TextDecoder('utf-8').decode(inflated));
14220
14977
  return decompressed;
14221
14978
  }
14222
14979
  async openTranscriptionStream(modelId, streamCallback, params) {
@@ -15899,6 +16656,110 @@ function normalizeValue(value) {
15899
16656
  * Rust endpoint. Recursively converts included relation values (which come
15900
16657
  * back as plain JSON objects) into proper model class instances.
15901
16658
  */
16659
+ /**
16660
+ * Key under which the executor returns a polymorphically-hydrated instance's
16661
+ * concrete class.
16662
+ *
16663
+ * Half of a wire contract: the writer is `SUBJECT_CLASS_KEY` in
16664
+ * `rust-executor/src/perspectives/model_query/relations.rs`, and the two are
16665
+ * separate literals in separate languages. Renaming one alone does not fail to
16666
+ * compile — it degrades to every instance staying plain JSON, which looks
16667
+ * identical to a relation that declared no classes to build.
16668
+ * `tests/js/tests/model/model-polymorphic.test.ts` drives both ends against one
16669
+ * executor, so the drift fails a test rather than a user's query.
16670
+ *
16671
+ * The executor also returns `__subjectClasses`, the whole set this one names the
16672
+ * head of. Nothing here reads it — it rides onto the instance with every other
16673
+ * JSON key, for a caller that wants to know a choice was made.
16674
+ */
16675
+ const SUBJECT_CLASS_KEY = '__subjectClass';
16676
+ /**
16677
+ * Turn on `polymorphic` for every relation that declares it, at every depth of
16678
+ * an include map.
16679
+ *
16680
+ * A relation being heterogeneous is a fact about the data, not about one query,
16681
+ * so the declaration lives on the model and the call site writes
16682
+ * `include: { children: true }`. That has to hold just as much one level down:
16683
+ * in `include: { posts: { include: { children: true } } }`, `children` is a
16684
+ * relation on `Post`, so the walk carries the class it is reading against down
16685
+ * with it. Without that, a nested include of an untyped polymorphic relation
16686
+ * reaches the executor with no shape to resolve and fails the query outright.
16687
+ *
16688
+ * An explicit `polymorphic: false` at any level still wins — `undefined` is the
16689
+ * only state the default fills in.
16690
+ *
16691
+ * The walk stops descending *through* a polymorphic relation, because there is
16692
+ * nothing to descend into: its targets are of several classes by definition, so
16693
+ * no single class's metadata could say what a deeper include means. The
16694
+ * executor resolves those nested includes against each concrete class instead.
16695
+ */
16696
+ function applyPolymorphicIncludeDefaults(includes, ctor) {
16697
+ const relMeta = getRelationsMetadata(ctor);
16698
+ for (const [relName, val] of Object.entries(includes)) {
16699
+ // `$`-prefixed keys are projections, not relations.
16700
+ if (relName.startsWith('$'))
16701
+ continue;
16702
+ const meta = relMeta[relName];
16703
+ if (!meta)
16704
+ continue;
16705
+ let subQuery = val;
16706
+ if (meta.polymorphic) {
16707
+ if (val === true) {
16708
+ subQuery = { polymorphic: true };
16709
+ includes[relName] = subQuery;
16710
+ }
16711
+ else if (typeof val === 'object' && val !== null && subQuery.polymorphic === undefined) {
16712
+ subQuery.polymorphic = true;
16713
+ }
16714
+ // The classes this call site can build are also the classes it wants its
16715
+ // targets read as, so the declaration answers both questions and the call
16716
+ // site repeats neither. Sent as part of the query rather than applied to
16717
+ // the results: a preference in the request is reproducible by anyone who
16718
+ // sends it, where one applied afterwards would make the same data read
16719
+ // differently depending on which classes the caller happened to import.
16720
+ //
16721
+ // It ranks and does not narrow — a target matching none of them still
16722
+ // arrives — so declaring what you can construct never costs you a member
16723
+ // of a relation that is heterogeneous by definition.
16724
+ if (typeof subQuery === 'object' &&
16725
+ subQuery !== null &&
16726
+ subQuery.polymorphic &&
16727
+ subQuery.preferClasses === undefined &&
16728
+ meta.instantiateAs) {
16729
+ const names = (meta.instantiateAs() ?? [])
16730
+ .map((cls) => cls?.className)
16731
+ .filter((name) => typeof name === 'string');
16732
+ if (names.length)
16733
+ subQuery.preferClasses = names;
16734
+ }
16735
+ }
16736
+ if (typeof subQuery !== 'object' || subQuery === null)
16737
+ continue;
16738
+ const nested = subQuery.include;
16739
+ if (!nested || subQuery.polymorphic)
16740
+ continue;
16741
+ // The thunk is only evaluated here, at query time, so a self-referential or
16742
+ // circularly-imported target that is not yet defined costs the nested
16743
+ // default rather than the whole query.
16744
+ let TargetClass;
16745
+ try {
16746
+ TargetClass = meta.target?.();
16747
+ }
16748
+ catch (e) {
16749
+ // A class not yet initialised throws `ReferenceError` from the temporal
16750
+ // dead zone, which is the expected cost of an import cycle and not worth
16751
+ // saying anything about. Anything else — a thunk closing over nothing,
16752
+ // typically — is a broken declaration that would otherwise cost the nested
16753
+ // default in silence, so it gets said out loud.
16754
+ const circularImport = e instanceof ReferenceError;
16755
+ const say = circularImport ? console.debug : console.warn;
16756
+ say(`prepareModelQueryParams: target class unavailable for include '${relName}':`, e);
16757
+ continue;
16758
+ }
16759
+ if (TargetClass)
16760
+ applyPolymorphicIncludeDefaults(nested, TargetClass);
16761
+ }
16762
+ }
15902
16763
  function jsonToModelInstance(ModelClass, perspective, json, include, properties) {
15903
16764
  const instance = new ModelClass(perspective, json.id || json.baseExpression);
15904
16765
  // When a properties projection is active, remove own properties set by the
@@ -15945,9 +16806,62 @@ function jsonToModelInstance(ModelClass, perspective, json, include, properties)
15945
16806
  if (!includeVal)
15946
16807
  continue;
15947
16808
  const meta = relMeta[relName];
15948
- if (!meta?.target)
16809
+ // A polymorphic relation may legitimately declare no target at all —
16810
+ // that is the case it exists for — so it must not be gated on one.
16811
+ if (!meta)
15949
16812
  continue;
15950
- const TargetClass = meta.target();
16813
+ if (!meta.target && !meta.polymorphic)
16814
+ continue;
16815
+ const TargetClass = meta.target?.();
16816
+ // For a polymorphic relation the executor sends each child's concrete
16817
+ // class back on the instance, because it had to know it in order to
16818
+ // hydrate against the right shape at all. What it cannot send is the
16819
+ // constructor, so `instantiateAs` names the classes this side can build
16820
+ // and the name → class map is derived from them: `@Model` records each
16821
+ // class's name on the class itself, so listing the classes and listing
16822
+ // their names would be the same list written twice, free to disagree.
16823
+ //
16824
+ // Built on first use rather than at decoration time, because the thunk
16825
+ // exists to be called late: a class defined further round a circular
16826
+ // import graph is not there yet when the decorator runs.
16827
+ let byClassName;
16828
+ // May resolve to nothing: a polymorphic relation is allowed to declare no
16829
+ // target at all, and the list may not name the class that arrived — it
16830
+ // says what this call site can construct, not what the relation may hold.
16831
+ // The item then stays plain JSON — correct data, carrying its class name
16832
+ // for a caller that wants to dispatch on it — rather than being forced
16833
+ // through a constructor that does not exist.
16834
+ const resolveChildClass = (item) => {
16835
+ if (!meta.polymorphic)
16836
+ return TargetClass;
16837
+ const concrete = item?.[SUBJECT_CLASS_KEY];
16838
+ // No concrete class means this was not read polymorphically after all —
16839
+ // an explicit `polymorphic: false` at the call site — so the relation's
16840
+ // own declared target is the right shape.
16841
+ if (typeof concrete !== 'string')
16842
+ return TargetClass;
16843
+ if (meta.instantiateAs) {
16844
+ if (!byClassName) {
16845
+ byClassName = {};
16846
+ for (const cls of meta.instantiateAs() ?? []) {
16847
+ const name = cls?.className;
16848
+ if (typeof name === 'string')
16849
+ byClassName[name] = cls;
16850
+ }
16851
+ }
16852
+ if (byClassName[concrete])
16853
+ return byClassName[concrete];
16854
+ }
16855
+ // The declared target is not a fallback, and having named no classes to
16856
+ // build does not make it one. Where a relation both declares a target
16857
+ // and reads polymorphically, a child of some third class was hydrated
16858
+ // against *its own* shape, so constructing the declared class over that
16859
+ // JSON produces an instance that answers `instanceof` for a class it is
16860
+ // not, carrying fields that class never declared — the exact
16861
+ // mislabelling polymorphic reads exist to prevent. It fits only when it
16862
+ // is the class the executor named.
16863
+ return TargetClass?.className === concrete ? TargetClass : undefined;
16864
+ };
15951
16865
  const nestedInclude = typeof includeVal === 'object' && includeVal !== null
15952
16866
  ? includeVal.include
15953
16867
  : undefined;
@@ -15957,14 +16871,18 @@ function jsonToModelInstance(ModelClass, perspective, json, include, properties)
15957
16871
  const raw = instance[relName];
15958
16872
  if (Array.isArray(raw)) {
15959
16873
  instance[relName] = raw.map((item) => {
15960
- if (typeof item === 'object' && item !== null && item.id) {
15961
- return jsonToModelInstance(TargetClass, perspective, item, nestedInclude, nestedProperties);
16874
+ const ChildClass = resolveChildClass(item);
16875
+ if (ChildClass && typeof item === 'object' && item !== null && item.id) {
16876
+ return jsonToModelInstance(ChildClass, perspective, item, nestedInclude, nestedProperties);
15962
16877
  }
15963
16878
  return item;
15964
16879
  });
15965
16880
  }
15966
16881
  else if (typeof raw === 'object' && raw !== null && raw.id) {
15967
- instance[relName] = jsonToModelInstance(TargetClass, perspective, raw, nestedInclude, nestedProperties);
16882
+ const ChildClass = resolveChildClass(raw);
16883
+ if (ChildClass) {
16884
+ instance[relName] = jsonToModelInstance(ChildClass, perspective, raw, nestedInclude, nestedProperties);
16885
+ }
15968
16886
  }
15969
16887
  }
15970
16888
  }
@@ -16212,6 +17130,7 @@ class Ad4mModel {
16212
17130
  ...(options.target !== undefined && { target: options.target }),
16213
17131
  ...(options.filter !== undefined && { filter: options.filter }),
16214
17132
  ...(options.where !== undefined && { where: options.where }),
17133
+ ...(options.ordering !== undefined && { ordering: options.ordering }),
16215
17134
  };
16216
17135
  }
16217
17136
  // Fallback: If both structures are empty but a JSON schema is attached, derive from it
@@ -16479,10 +17398,22 @@ class Ad4mModel {
16479
17398
  const current = normalizeValue(this[field]);
16480
17399
  const original = this._snapshot[field];
16481
17400
  if (Array.isArray(current) || Array.isArray(original)) {
16482
- // Order-insensitive comparison (sorted) so reordering alone
16483
- // doesn't mark a relation as dirty.
16484
- const a = Array.isArray(current) ? [...current].sort() : [];
16485
- const b = Array.isArray(original) ? [...original].sort() : [];
17401
+ // For an ordered relation the sequence *is* the state, so a reorder is
17402
+ // the whole change and must mark the field dirty — sorting first would
17403
+ // make `save()` a no-op for the one edit the ordering feature exists to
17404
+ // support.
17405
+ //
17406
+ // Everything else compares order-insensitively, because an unordered
17407
+ // relation is a set: the executor returns its members by link timestamp,
17408
+ // and a caller who assigned the same members in another order has not
17409
+ // changed anything.
17410
+ const ordered = !!metadata.relations[field]?.ordering;
17411
+ const a = Array.isArray(current) ? [...current] : [];
17412
+ const b = Array.isArray(original) ? [...original] : [];
17413
+ if (!ordered) {
17414
+ a.sort();
17415
+ b.sort();
17416
+ }
16486
17417
  if (a.length !== b.length || a.some((v, i) => v !== b[i])) {
16487
17418
  changed.push(field);
16488
17419
  }
@@ -16622,8 +17553,17 @@ class Ad4mModel {
16622
17553
  normalIncludes[key] = val;
16623
17554
  }
16624
17555
  }
16625
- if (Object.keys(normalIncludes).length > 0)
17556
+ // A relation declared `polymorphic` reads that way by default, so the
17557
+ // caller writes `include: { children: true }` and still gets each child
17558
+ // hydrated as the class it actually is. Declaring it on the model rather
17559
+ // than repeating it at every call site is the point — the relation being
17560
+ // heterogeneous is a fact about the data, not about one query — but an
17561
+ // explicit `polymorphic: false` at the call site still wins. Applied at
17562
+ // every depth, since a nested include is a fact about the data too.
17563
+ if (Object.keys(normalIncludes).length > 0) {
17564
+ applyPolymorphicIncludeDefaults(normalIncludes, this);
16626
17565
  queryInput.include = normalIncludes;
17566
+ }
16627
17567
  if (Object.keys(projections).length > 0) {
16628
17568
  // Tag each projection with its target class name so the executor can
16629
17569
  // resolve the target shape through its in-memory cache when applying
@@ -16689,11 +17629,11 @@ class Ad4mModel {
16689
17629
  *
16690
17630
  * @internal
16691
17631
  */
16692
- static async executeModelQuery(perspective, query = {}, classNameOverride) {
17632
+ static async executeModelQuery(perspective, query = {}, classNameOverride, options) {
16693
17633
  // Delegate query input building to the shared prepareModelQueryParams
16694
17634
  // helper. The executor resolves the shape from SHACL server-side.
16695
17635
  const { className, queryJson } = this.prepareModelQueryParams(query, classNameOverride);
16696
- const result = await perspective.modelQuery(className, queryJson);
17636
+ const result = await perspective.modelQuery(className, queryJson, options);
16697
17637
  // Convert JSON instances to model class instances, recursively constructing
16698
17638
  // class instances for any included relations resolved by Rust.
16699
17639
  const instances = result.instances.map((json) => {
@@ -16734,12 +17674,12 @@ class Ad4mModel {
16734
17674
  * });
16735
17675
  * ```
16736
17676
  */
16737
- static async findAll(perspective, query) {
17677
+ static async findAll(perspective, query, options) {
16738
17678
  const q = (query ?? {});
16739
17679
  if (q.properties && q.properties.length === 0) {
16740
17680
  throw new Error("properties[] must not be empty — omit the field to return all properties, or specify at least one field name");
16741
17681
  }
16742
- const { results } = await this.executeModelQuery(perspective, q);
17682
+ const { results } = await this.executeModelQuery(perspective, q, undefined, options);
16743
17683
  return results;
16744
17684
  }
16745
17685
  /**
@@ -16762,9 +17702,9 @@ class Ad4mModel {
16762
17702
  * }
16763
17703
  * ```
16764
17704
  */
16765
- static async findOne(perspective, query) {
17705
+ static async findOne(perspective, query, options) {
16766
17706
  const limitedQuery = { ...(query ?? {}), limit: 1 };
16767
- const results = await this.findAll(perspective, limitedQuery);
17707
+ const results = await this.findAll(perspective, limitedQuery, options);
16768
17708
  return results[0] ?? null;
16769
17709
  }
16770
17710
  /**
@@ -16784,8 +17724,8 @@ class Ad4mModel {
16784
17724
  * console.log(`Showing 10 of ${totalCount} dessert recipes`);
16785
17725
  * ```
16786
17726
  */
16787
- static async findAllAndCount(perspective, query) {
16788
- const out = await this.executeModelQuery(perspective, (query ?? {}));
17727
+ static async findAllAndCount(perspective, query, options) {
17728
+ const out = await this.executeModelQuery(perspective, (query ?? {}), undefined, options);
16789
17729
  return out;
16790
17730
  }
16791
17731
  /**
@@ -16805,9 +17745,9 @@ class Ad4mModel {
16805
17745
  * console.log(`Page ${page.pageNumber} of recipes, ${page.results.length} items`);
16806
17746
  * ```
16807
17747
  */
16808
- static async paginate(perspective, pageSize, pageNumber, query) {
17748
+ static async paginate(perspective, pageSize, pageNumber, query, options) {
16809
17749
  const paginationQuery = { ...(query ?? {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
16810
- const { results, totalCount } = await this.executeModelQuery(perspective, paginationQuery);
17750
+ const { results, totalCount } = await this.executeModelQuery(perspective, paginationQuery, undefined, options);
16811
17751
  return { results: results, totalCount, pageSize, pageNumber };
16812
17752
  }
16813
17753
  /**
@@ -16835,8 +17775,8 @@ class Ad4mModel {
16835
17775
  * });
16836
17776
  * ```
16837
17777
  */
16838
- static async count(perspective, query) {
16839
- const { totalCount } = await this.executeModelQuery(perspective, { ...(query ?? {}), limit: 0 });
17778
+ static async count(perspective, query, options) {
17779
+ const { totalCount } = await this.executeModelQuery(perspective, { ...(query ?? {}), limit: 0 }, undefined, options);
16840
17780
  return totalCount;
16841
17781
  }
16842
17782
  async setProperty(key, value, batchId) {
@@ -16990,7 +17930,18 @@ class Ad4mModel {
16990
17930
  for (const [key, value] of Object.entries(this)) {
16991
17931
  if (value !== undefined && value !== null && !(Array.isArray(value) && value.length > 0) && !value?.action) {
16992
17932
  const propMeta = metadata.properties[key];
16993
- if (propMeta && effectiveLiteralStorage(propMeta).kind !== "deterministic") {
17933
+ // Only offer keys with a declared, settable model property. This
17934
+ // excludes ORM bookkeeping fields (_baseExpression, _perspective —
17935
+ // enumerable instance fields, not model properties), HasMany
17936
+ // relations (tracked in a separate registry, never in
17937
+ // `metadata.properties`), and read-only properties/flags
17938
+ // (readOnly: true). None of these have an `ad4m://setter` on the
17939
+ // Rust side, which otherwise logs a "declares no setter" warning
17940
+ // per key on every save().
17941
+ if (!propMeta || propMeta.readOnly) {
17942
+ continue;
17943
+ }
17944
+ if (effectiveLiteralStorage(propMeta).kind !== "deterministic") {
16994
17945
  deferredExpressionProps.push(key);
16995
17946
  continue;
16996
17947
  }
@@ -17099,13 +18050,36 @@ class Ad4mModel {
17099
18050
  await this.setRelationValues(key, value, batchId);
17100
18051
  }
17101
18052
  else if (value !== undefined && value !== null && value !== "") {
18053
+ // A scalar handed to a relation field is a single-member relation.
18054
+ //
18055
+ // This used to `continue` — "Skip, it's a relation, not a regular
18056
+ // property" — so `Model.create(p, { source: 'uri://x' })` typechecked,
18057
+ // ran, resolved, and wrote no link. The record was created with the
18058
+ // relation empty and nothing anywhere said so, which surfaces later as
18059
+ // a *reader* complaining about a malformed instance: a Relationship
18060
+ // with no endpoints, a Placement pointing at nothing. Both look like
18061
+ // rendering bugs from the outside, because the record exists and the
18062
+ // thing that should reference it does not.
18063
+ //
18064
+ // The array form is the documented path and stays correct; the problem
18065
+ // is that the scalar form is plausible, typechecks against a field
18066
+ // declared `string`, and fails silently. Coercing matches what a caller
18067
+ // reaching for it meant. A value `setRelationValues` cannot use now
18068
+ // fails there, loudly, instead of vanishing here.
18069
+ //
18070
+ // Deliberately outside the `setProperties` gate, mirroring the array
18071
+ // branch above. `create` passes `setProperties: false` when the class
18072
+ // has a constructor, because `create_subject` writes the values map —
18073
+ // but a relation carries `ad4m://adder`, not `ad4m://setter`, so
18074
+ // `create_subject` drops it (see the warning added in 3ee2b5bc6).
18075
+ // Relations have to be written here in both cases or they are lost by
18076
+ // both paths at once.
18077
+ const relationMeta = this.getRelationOptions(key);
18078
+ if (relationMeta) {
18079
+ await this.setRelationValues(key, [value], batchId);
18080
+ continue;
18081
+ }
17102
18082
  if (setProperties) {
17103
- // Check if this is a relation property (has relation metadata)
17104
- const relationMeta = this.getRelationOptions(key);
17105
- if (relationMeta) {
17106
- // Skip - it's a relation, not a regular property
17107
- continue;
17108
- }
17109
18083
  // Skip flag properties — they are immutable after creation
17110
18084
  const propMeta = this.getPropertyMetadata(key);
17111
18085
  if (propMeta?.flag) {
@@ -17935,13 +18909,13 @@ class PerspectiveHandle {
17935
18909
  * const runs = await InterpretationRun.findAll(perspective);
17936
18910
  * const configs = await AutoProcessorConfig.findAll(perspective);
17937
18911
  */
17938
- var __decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
18912
+ var __decorate$1 = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
17939
18913
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
17940
18914
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
17941
18915
  else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
17942
18916
  return c > 3 && r && Object.defineProperty(target, key, r), r;
17943
18917
  };
17944
- var __metadata = (undefined && undefined.__metadata) || function (k, v) {
18918
+ var __metadata$1 = (undefined && undefined.__metadata) || function (k, v) {
17945
18919
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
17946
18920
  };
17947
18921
  // ── AutoProcessorConfig ─────────────────────────────────────────────────────
@@ -17980,71 +18954,67 @@ let AutoProcessorConfig = class AutoProcessorConfig extends Ad4mModel {
17980
18954
  // `batchMax` + `claimTtlMs` — the Rust SDNA takes the same shape.
17981
18955
  }
17982
18956
  };
17983
- __decorate([
18957
+ __decorate$1([
17984
18958
  Property({ through: "ad4m://processor_id", required: true, identity: true }),
17985
- __metadata("design:type", String)
18959
+ __metadata$1("design:type", String)
17986
18960
  ], AutoProcessorConfig.prototype, "processorId", void 0);
17987
- __decorate([
18961
+ __decorate$1([
17988
18962
  Property({ through: "ad4m://source_scope_query", required: true }),
17989
- __metadata("design:type", String)
18963
+ __metadata$1("design:type", String)
17990
18964
  ], AutoProcessorConfig.prototype, "sourceScopeQuery", void 0);
17991
- __decorate([
18965
+ __decorate$1([
17992
18966
  Optional({ through: "ad4m://base_prefix" }),
17993
- __metadata("design:type", String)
18967
+ __metadata$1("design:type", String)
17994
18968
  ], AutoProcessorConfig.prototype, "basePrefix", void 0);
17995
- __decorate([
18969
+ __decorate$1([
17996
18970
  HasMany({ through: "ad4m://interpretation_class", datatype: "xsd:string" }),
17997
- __metadata("design:type", Array)
18971
+ __metadata$1("design:type", Array)
17998
18972
  ], AutoProcessorConfig.prototype, "interpretationClasses", void 0);
17999
- __decorate([
18973
+ __decorate$1([
18000
18974
  Property({ through: "ad4m://debounce_ms", required: true }),
18001
- __metadata("design:type", String)
18975
+ __metadata$1("design:type", String)
18002
18976
  ], AutoProcessorConfig.prototype, "debounceMs", void 0);
18003
- __decorate([
18977
+ __decorate$1([
18004
18978
  Optional({ through: "ad4m://batch_min" }),
18005
- __metadata("design:type", String)
18979
+ __metadata$1("design:type", String)
18006
18980
  ], AutoProcessorConfig.prototype, "batchMin", void 0);
18007
- __decorate([
18981
+ __decorate$1([
18008
18982
  Property({ through: "ad4m://batch_max", required: true }),
18009
- __metadata("design:type", String)
18983
+ __metadata$1("design:type", String)
18010
18984
  ], AutoProcessorConfig.prototype, "batchMax", void 0);
18011
- __decorate([
18985
+ __decorate$1([
18012
18986
  Optional({ through: "ad4m://max_wait_ms" }),
18013
- __metadata("design:type", String)
18987
+ __metadata$1("design:type", String)
18014
18988
  ], AutoProcessorConfig.prototype, "maxWaitMs", void 0);
18015
- __decorate([
18989
+ __decorate$1([
18016
18990
  Property({ through: "ad4m://claim_ttl_ms", required: true }),
18017
- __metadata("design:type", String)
18991
+ __metadata$1("design:type", String)
18018
18992
  ], AutoProcessorConfig.prototype, "claimTtlMs", void 0);
18019
- __decorate([
18993
+ __decorate$1([
18020
18994
  Optional({ through: "ad4m://source_window_ms" }),
18021
- __metadata("design:type", String)
18995
+ __metadata$1("design:type", String)
18022
18996
  ], AutoProcessorConfig.prototype, "sourceWindowMs", void 0);
18023
- __decorate([
18997
+ __decorate$1([
18024
18998
  Optional({ through: "ad4m://dedup_strategy" }),
18025
- __metadata("design:type", String)
18999
+ __metadata$1("design:type", String)
18026
19000
  ], AutoProcessorConfig.prototype, "dedupStrategy", void 0);
18027
- __decorate([
19001
+ __decorate$1([
18028
19002
  Optional({ through: "ad4m://existing_scope" }),
18029
- __metadata("design:type", String)
19003
+ __metadata$1("design:type", String)
18030
19004
  ], AutoProcessorConfig.prototype, "existingScope", void 0);
18031
- __decorate([
19005
+ __decorate$1([
18032
19006
  Optional({ through: "ad4m://mint_scope" }),
18033
- __metadata("design:type", String)
19007
+ __metadata$1("design:type", String)
18034
19008
  ], AutoProcessorConfig.prototype, "mintScope", void 0);
18035
- __decorate([
18036
- Optional({ through: "ad4m://debug_mode", resolveLanguage: "literal" }),
18037
- __metadata("design:type", String)
18038
- ], AutoProcessorConfig.prototype, "debugMode", void 0);
18039
- __decorate([
18040
- Optional({ through: "ad4m://persist_debug", resolveLanguage: "literal" }),
18041
- __metadata("design:type", String)
18042
- ], AutoProcessorConfig.prototype, "persistDebug", void 0);
18043
- __decorate([
19009
+ __decorate$1([
19010
+ Optional({ through: "ad4m://max_tool_calls" }),
19011
+ __metadata$1("design:type", String)
19012
+ ], AutoProcessorConfig.prototype, "maxToolCalls", void 0);
19013
+ __decorate$1([
18044
19014
  Optional({ through: "ad4m://emit_debug_events", resolveLanguage: "literal" }),
18045
- __metadata("design:type", String)
19015
+ __metadata$1("design:type", String)
18046
19016
  ], AutoProcessorConfig.prototype, "emitDebugEvents", void 0);
18047
- AutoProcessorConfig = __decorate([
19017
+ AutoProcessorConfig = __decorate$1([
18048
19018
  Model$1({ name: "AutoProcessor" })
18049
19019
  ], AutoProcessorConfig);
18050
19020
  // ── InterpretationRun ───────────────────────────────────────────────────────
@@ -18068,39 +19038,39 @@ let InterpretationRun = class InterpretationRun extends Ad4mModel {
18068
19038
  this.sources = [];
18069
19039
  }
18070
19040
  };
18071
- __decorate([
19041
+ __decorate$1([
18072
19042
  Property({ through: "ad4m://interp/run_id", required: true, identity: true }),
18073
- __metadata("design:type", String)
19043
+ __metadata$1("design:type", String)
18074
19044
  ], InterpretationRun.prototype, "runId", void 0);
18075
- __decorate([
19045
+ __decorate$1([
18076
19046
  Optional({ through: "ad4m://interp/model" }),
18077
- __metadata("design:type", String)
19047
+ __metadata$1("design:type", String)
18078
19048
  ], InterpretationRun.prototype, "model", void 0);
18079
- __decorate([
19049
+ __decorate$1([
18080
19050
  Optional({ through: "ad4m://interp/prompt_version" }),
18081
- __metadata("design:type", String)
19051
+ __metadata$1("design:type", String)
18082
19052
  ], InterpretationRun.prototype, "promptVersion", void 0);
18083
- __decorate([
19053
+ __decorate$1([
18084
19054
  Optional({ through: "ad4m://interp/ran_at" }),
18085
- __metadata("design:type", String)
19055
+ __metadata$1("design:type", String)
18086
19056
  ], InterpretationRun.prototype, "ranAt", void 0);
18087
- __decorate([
19057
+ __decorate$1([
18088
19058
  Optional({ through: "ad4m://interp/processor" }),
18089
- __metadata("design:type", String)
19059
+ __metadata$1("design:type", String)
18090
19060
  ], InterpretationRun.prototype, "processor", void 0);
18091
- __decorate([
19061
+ __decorate$1([
18092
19062
  HasMany({ through: "ad4m://interp/sources", datatype: "xsd:string" }),
18093
- __metadata("design:type", Array)
19063
+ __metadata$1("design:type", Array)
18094
19064
  ], InterpretationRun.prototype, "sources", void 0);
18095
- __decorate([
19065
+ __decorate$1([
18096
19066
  Optional({ through: "ad4m://interp/debug_prompt", resolveLanguage: "literal" }),
18097
- __metadata("design:type", String)
19067
+ __metadata$1("design:type", String)
18098
19068
  ], InterpretationRun.prototype, "debugPrompt", void 0);
18099
- __decorate([
19069
+ __decorate$1([
18100
19070
  Optional({ through: "ad4m://interp/debug_response", resolveLanguage: "literal" }),
18101
- __metadata("design:type", String)
19071
+ __metadata$1("design:type", String)
18102
19072
  ], InterpretationRun.prototype, "debugResponse", void 0);
18103
- InterpretationRun = __decorate([
19073
+ InterpretationRun = __decorate$1([
18104
19074
  Model$1({ name: "InterpretationRun" })
18105
19075
  ], InterpretationRun);
18106
19076
  // ── InterpretationOverlay ───────────────────────────────────────────────────
@@ -18130,18 +19100,531 @@ let InterpretationOverlay = class InterpretationOverlay extends Ad4mModel {
18130
19100
  this.kind = "";
18131
19101
  }
18132
19102
  };
18133
- __decorate([
19103
+ __decorate$1([
18134
19104
  Property({ through: "ad4m://interp/kind", required: true }),
18135
- __metadata("design:type", String)
19105
+ __metadata$1("design:type", String)
18136
19106
  ], InterpretationOverlay.prototype, "kind", void 0);
18137
- __decorate([
19107
+ __decorate$1([
18138
19108
  Optional({ through: "ad4m://interp/run" }),
18139
- __metadata("design:type", String)
19109
+ __metadata$1("design:type", String)
18140
19110
  ], InterpretationOverlay.prototype, "run", void 0);
18141
- InterpretationOverlay = __decorate([
19111
+ InterpretationOverlay = __decorate$1([
18142
19112
  Model$1({ name: "InterpretationOverlay" })
18143
19113
  ], InterpretationOverlay);
18144
19114
 
19115
+ /**
19116
+ * TypeScript @Model classes mirroring the Rust-side hardwired SDNA for the
19117
+ * flow runtime. Apps can import these to query the perspective graph for
19118
+ * pending flow-transition proposals without knowing the raw link predicates.
19119
+ *
19120
+ * Registration:
19121
+ * await FlowTransitionProposal.register(perspective);
19122
+ *
19123
+ * Querying:
19124
+ * const pending = await FlowTransitionProposal.findAll(perspective);
19125
+ *
19126
+ * Slice 5/7 of the flow-implementation arc (design doc §4.2). The Rust
19127
+ * engine does not yet mint these — that lands with the consensus firing
19128
+ * work in a later PR arc. This class defines the on-graph shape so:
19129
+ * - clients can build UI over proposals immediately (Deliberation demo);
19130
+ * - the SDNA-parity test locks TS/Rust drift the moment the JSON exists
19131
+ * (`rust-executor/src/perspectives/hardwired_sdna/flow_transition_proposal.json`);
19132
+ * - the engine can start writing into this shape when consensus lands
19133
+ * without touching the client-side surface.
19134
+ */
19135
+ var __decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
19136
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
19137
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
19138
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
19139
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
19140
+ };
19141
+ var __metadata = (undefined && undefined.__metadata) || function (k, v) {
19142
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
19143
+ };
19144
+ // ── FlowTransitionProposal ──────────────────────────────────────────────────
19145
+ // Mirrors the Rust hardwired `flow_transition_proposal.json` SDNA (once wired
19146
+ // on the engine side; see file header). One node per proposed transition; the
19147
+ // URI is `ad4m://flow/proposal/<uuid>` when the engine mints it, but the class
19148
+ // carries no URI-format constraint — apps constructing proposals directly may
19149
+ // choose any URI they can defend as unique.
19150
+ let FlowTransitionProposal = class FlowTransitionProposal extends Ad4mModel {
19151
+ constructor() {
19152
+ super(...arguments);
19153
+ /**
19154
+ * URI of the running `FlowInstance` this proposal targets. First-declared
19155
+ * property so `buildSHACL` derives the shape namespace from its `through`
19156
+ * prefix — `ad4m://flow/instance` → `ad4m://` → target_class
19157
+ * `ad4m://FlowTransitionProposal`. Also the identity predicate: the
19158
+ * discriminator `findAll` uses to isolate proposal nodes.
19159
+ */
19160
+ this.flowInstance = "";
19161
+ /** Name of the state the flow instance is currently in. */
19162
+ this.fromState = "";
19163
+ /** Name of the state the proposal wants to transition to. */
19164
+ this.toState = "";
19165
+ /** DID of the agent that issued the proposal. */
19166
+ this.proposer = "";
19167
+ /**
19168
+ * URIs of instances offered as evidence that `toState.requires` is now
19169
+ * satisfied. Multiple links, one per cited instance; ordering is not
19170
+ * significant.
19171
+ */
19172
+ this.evidence = [];
19173
+ /**
19174
+ * JSON blob: `{ [uri]: sha256_hex }` — one entry per evidence URI, hashing
19175
+ * the canonicalized graph-visible properties (sorted by property URI,
19176
+ * multi-values sorted lexicographically) at proposal time. Downstream
19177
+ * verifiers use it to detect edits to cited instances after the proposal
19178
+ * was written. Stored as an opaque string because SHACL properties carry
19179
+ * no rich-object type; the engine parses it back into a map.
19180
+ */
19181
+ this.evidenceHashes = "";
19182
+ // "When was this proposal written?" is answered by `Ad4mModel`'s built-in
19183
+ // `createdAt`, synthesized on hydration from the earliest link timestamp
19184
+ // of the proposal's own links (all written together during create_subject).
19185
+ }
19186
+ };
19187
+ __decorate([
19188
+ Property({ through: "ad4m://flow/instance", required: true, identity: true }),
19189
+ __metadata("design:type", String)
19190
+ ], FlowTransitionProposal.prototype, "flowInstance", void 0);
19191
+ __decorate([
19192
+ Property({ through: "ad4m://flow/from_state", required: true }),
19193
+ __metadata("design:type", String)
19194
+ ], FlowTransitionProposal.prototype, "fromState", void 0);
19195
+ __decorate([
19196
+ Property({ through: "ad4m://flow/to_state", required: true }),
19197
+ __metadata("design:type", String)
19198
+ ], FlowTransitionProposal.prototype, "toState", void 0);
19199
+ __decorate([
19200
+ Property({ through: "ad4m://flow/proposer", required: true }),
19201
+ __metadata("design:type", String)
19202
+ ], FlowTransitionProposal.prototype, "proposer", void 0);
19203
+ __decorate([
19204
+ HasMany({ through: "ad4m://flow/evidence", datatype: "xsd:string" }),
19205
+ __metadata("design:type", Array)
19206
+ ], FlowTransitionProposal.prototype, "evidence", void 0);
19207
+ __decorate([
19208
+ Property({ through: "ad4m://flow/evidence_hashes", required: true }),
19209
+ __metadata("design:type", String)
19210
+ ], FlowTransitionProposal.prototype, "evidenceHashes", void 0);
19211
+ __decorate([
19212
+ Optional({ through: "ad4m://flow/run_uri" }),
19213
+ __metadata("design:type", String)
19214
+ ], FlowTransitionProposal.prototype, "runUri", void 0);
19215
+ __decorate([
19216
+ Optional({ through: "ad4m://flow/rationale" }),
19217
+ __metadata("design:type", String)
19218
+ ], FlowTransitionProposal.prototype, "rationale", void 0);
19219
+ FlowTransitionProposal = __decorate([
19220
+ Model$1({ name: "FlowTransitionProposal" })
19221
+ ], FlowTransitionProposal);
19222
+ // ── FlowInstanceRecord ──────────────────────────────────────────────────────
19223
+ // On-graph node minted by the engine when a flow is started on a specific
19224
+ // base expression. Its URI is the value that `FlowTransitionProposal.flowInstance`
19225
+ // references. Mirrors `rust-executor/src/perspectives/hardwired_sdna/flow_instance.json`.
19226
+ //
19227
+ // Design authority: `docs/flow-interpretation-hints-design.md` §4.3.
19228
+ //
19229
+ // This class is the raw on-graph record (@Model over the SDNA shape). The
19230
+ // object-oriented handle callers work with is `FlowInstance` in
19231
+ // `./FlowInstance.ts` — it wraps `FlowInstanceRecord + SHACLFlow definition`
19232
+ // and exposes `currentState`, `availableTransitions`, `proposals`, etc.
19233
+ // Renamed from `FlowInstance` → `FlowInstanceRecord` on 2026-08-27 per
19234
+ // Nico's PR #929 review R2 (the `FlowInstance` name is reserved for the
19235
+ // wrapper the design has always specified in §4.3).
19236
+ //
19237
+ // The SDNA name (`@Model({ name: "FlowInstance" })`) stays unchanged — that
19238
+ // keys the on-graph class, not the TS export. Renaming the TS class only
19239
+ // changes the JS import surface; the graph shape is identical, and Rust
19240
+ // hardwired_sdna/flow_instance.json + all the parity tests still lock down
19241
+ // the same `ad4m://FlowInstance` target class.
19242
+ let FlowInstanceRecord = class FlowInstanceRecord extends Ad4mModel {
19243
+ constructor() {
19244
+ super(...arguments);
19245
+ /**
19246
+ * URI of the `SHACLFlow` this instance runs — the flow's canonical
19247
+ * identity, collision-free across social-DNA modules from different
19248
+ * communities (bare names WILL collide once shared flows are adopted
19249
+ * cross-team — James PR #929 R5). Sourced from `SHACLFlow.flowUri`
19250
+ * (which is `${namespace}${name}Flow`, e.g. `coasys://DeliveryFlow`).
19251
+ *
19252
+ * First-declared property so `buildSHACL` derives the shape namespace
19253
+ * from its `through` prefix — `ad4m://flow/flow_uri` → `ad4m://` →
19254
+ * target_class `ad4m://FlowInstance`. Also the discriminator predicate
19255
+ * `findAll` uses to isolate instance nodes.
19256
+ *
19257
+ * The human-readable flow name is still available on the paired
19258
+ * `SHACLFlow` (via `perspective.getFlow(record.flowUri.split('/').pop()!.replace(/Flow$/,''))`,
19259
+ * or more commonly via the `FlowInstance` wrapper's `flowName` getter).
19260
+ */
19261
+ this.flowUri = "";
19262
+ /**
19263
+ * URI of the subject expression this flow runs on.
19264
+ * Named `subject` (not `baseExpression`) because `Ad4mModel` reserves
19265
+ * `baseExpression` as a synthetic hydration field always set to the
19266
+ * instance's own URI — a subclass property with that name is shadowed
19267
+ * on read.
19268
+ */
19269
+ this.subject = "";
19270
+ /** Name of the state the flow is currently in. */
19271
+ this.currentState = "";
19272
+ // "When was this flow started?" is answered by `Ad4mModel`'s built-in
19273
+ // `createdAt`, synthesized on hydration from the earliest link timestamp
19274
+ // of the instance's own links (all written together during `mint_flow_instance`).
19275
+ }
19276
+ };
19277
+ __decorate([
19278
+ Property({ through: "ad4m://flow/flow_uri", required: true, identity: true }),
19279
+ __metadata("design:type", String)
19280
+ ], FlowInstanceRecord.prototype, "flowUri", void 0);
19281
+ __decorate([
19282
+ Property({ through: "ad4m://flow/base", required: true }),
19283
+ __metadata("design:type", String)
19284
+ ], FlowInstanceRecord.prototype, "subject", void 0);
19285
+ __decorate([
19286
+ Property({ through: "ad4m://flow/current_state", required: true }),
19287
+ __metadata("design:type", String)
19288
+ ], FlowInstanceRecord.prototype, "currentState", void 0);
19289
+ FlowInstanceRecord = __decorate([
19290
+ Model$1({ name: "FlowInstance" })
19291
+ ], FlowInstanceRecord);
19292
+
19293
+ /**
19294
+ * `FlowInstance` — object-oriented wrapper for a running flow.
19295
+ *
19296
+ * Design authority: `docs/flow-interpretation-hints-design.md` §4.3.
19297
+ *
19298
+ * Wraps two on-graph objects:
19299
+ *
19300
+ * - `FlowInstanceRecord` — the raw @Model row minted by
19301
+ * {@link FlowInstance.start}; carries `flow`, `subject`, `currentState`,
19302
+ * and Ad4mModel's synthesised `createdAt`.
19303
+ * - `SHACLFlow` — the flow definition the record is bound to. Held so
19304
+ * `availableTransitions` / `currentState` object lookups don't require
19305
+ * a per-call round-trip.
19306
+ *
19307
+ * Construct via the class factories — {@link FlowInstance.start} for the
19308
+ * mint path and {@link FlowInstance.findAll} for the read path — rather
19309
+ * than the `wrap` escape hatch, which exists for tests that already own
19310
+ * a matched (record, shape) pair.
19311
+ *
19312
+ * # What's here vs. what's coming in §7 / slice 10.6
19313
+ *
19314
+ * Read surface (implemented today, PR #929):
19315
+ * - `uri`, `subject`, `flowName`, `currentStateName`, `startedAtMillis`
19316
+ * accessors.
19317
+ * - `currentState` — resolves the `FlowState` on the shape whose name
19318
+ * matches `record.currentState`.
19319
+ * - `availableTransitions` — filters `shape.transitions` by `fromState`.
19320
+ * - `proposals()` — queries `FlowTransitionProposal` records that
19321
+ * target this instance's URI.
19322
+ *
19323
+ * Mutations + subscriptions (`proposeTransition`, `accept`, `reject`,
19324
+ * `fireAction`, `onStateChange`, `onProposalAdded`, `onProposalResolved`)
19325
+ * land with the consensus-engine slice (§4.3 / slice 10.6). Rather than
19326
+ * ship them as `throw new Error("not yet")` stubs — which is a type-level
19327
+ * lie the caller only discovers at runtime — they are simply absent from
19328
+ * this class until the engine is wired.
19329
+ */
19330
+ /**
19331
+ * Extract the flow's human-readable name from its canonical URI.
19332
+ *
19333
+ * `SHACLFlow.flowUri` is `${namespace}${name}Flow` (e.g.
19334
+ * `coasys://DeliveryFlow`). This function strips the `Flow` suffix and
19335
+ * everything before the last URI-segment separator (`/` or `#`), leaving
19336
+ * the bare name. Returns `undefined` for URIs that don't match the
19337
+ * `…{name}Flow` shape — a stale FlowInstanceRecord whose flow URI came
19338
+ * from an older writer, for instance.
19339
+ */
19340
+ function flowNameFromUri(flowUri) {
19341
+ if (!flowUri.endsWith("Flow"))
19342
+ return undefined;
19343
+ const withoutSuffix = flowUri.slice(0, -"Flow".length);
19344
+ const sepIdx = Math.max(withoutSuffix.lastIndexOf("/"), withoutSuffix.lastIndexOf("#"));
19345
+ if (sepIdx < 0)
19346
+ return withoutSuffix || undefined;
19347
+ const name = withoutSuffix.slice(sepIdx + 1);
19348
+ return name || undefined;
19349
+ }
19350
+ class FlowInstance {
19351
+ /**
19352
+ * Private constructor — construct via {@link FlowInstance.start} or
19353
+ * {@link FlowInstance.findAll}. {@link FlowInstance.wrap} is the
19354
+ * escape hatch for tests / direct construction cases.
19355
+ */
19356
+ constructor(perspective,
19357
+ /** The flow definition this instance was minted against. */
19358
+ shape,
19359
+ /**
19360
+ * The on-graph record — carries `flow`, `subject`, `currentState`
19361
+ * and Ad4mModel's synthesised `createdAt`. Callers can reach into it
19362
+ * for anything the wrapper doesn't expose directly, but should prefer
19363
+ * the wrapper accessors so future refactors of the underlying shape
19364
+ * don't ripple through their code.
19365
+ */
19366
+ record) {
19367
+ this.perspective = perspective;
19368
+ this.shape = shape;
19369
+ this.record = record;
19370
+ }
19371
+ /**
19372
+ * Escape hatch used by {@link FlowInstance.start} and
19373
+ * {@link FlowInstance.findAll} — not meant for general use, but public
19374
+ * so tests that already own a `FlowInstanceRecord + SHACLFlow` pair
19375
+ * (e.g. from pre-populated fixtures) can build a wrapper without
19376
+ * going through the mint path.
19377
+ */
19378
+ static wrap(perspective, shape, record) {
19379
+ return new FlowInstance(perspective, shape, record);
19380
+ }
19381
+ /**
19382
+ * Mint a new `FlowInstance` on the given perspective (design doc §4.3).
19383
+ *
19384
+ * Idempotently registers the hardwired `FlowInstanceRecord` +
19385
+ * `FlowTransitionProposal` @Model classes on first call — the on-graph
19386
+ * shape matches the Rust-side hardwired SDNA (parity-locked in
19387
+ * `flow-instance.test.ts` / `flow-transition-proposal.test.ts`).
19388
+ *
19389
+ * The returned wrapper carries the parsed `SHACLFlow` alongside the
19390
+ * on-graph record, so `currentState` / `availableTransitions` /
19391
+ * `proposals` accessors work without further round-trips. The consensus
19392
+ * engine (slice 10.6) will read the record's `currentState` when it
19393
+ * fires transitions.
19394
+ *
19395
+ * @param perspective - The perspective the flow instance lives on
19396
+ * @param flowName - Name of a `SHACLFlow` already registered on the perspective
19397
+ * @param baseExpression - URI of the subject expression the flow runs on
19398
+ * @throws When the flow is unknown or has zero declared states (zero-state
19399
+ * flows fire via the forthcoming atomic-action path, §6.3).
19400
+ */
19401
+ static async start(perspective, flowName, baseExpression) {
19402
+ const flow = await perspective.getFlow(flowName);
19403
+ if (!flow)
19404
+ throw `Flow "${flowName}" not found`;
19405
+ if (flow.states.length === 0) {
19406
+ throw `Flow "${flowName}" has no states — FlowInstance.start is for stateful flows only; zero-state flows fire via the forthcoming atomic-action path (§6.3)`;
19407
+ }
19408
+ // Register the hardwired runtime classes if this is the first flow
19409
+ // instance on the perspective. registerAll is a single batched RPC and
19410
+ // no-ops when both classes are already present.
19411
+ await Ad4mModel.registerAll(perspective, [FlowInstanceRecord, FlowTransitionProposal]);
19412
+ // Property keys must be the FlowInstanceRecord @Model field names —
19413
+ // `subject` (not `baseExpression`, which collides with Ad4mModel's
19414
+ // synthetic hydration field and would be silently shadowed on read).
19415
+ // No explicit start-time field: Ad4mModel synthesises `createdAt` on
19416
+ // hydration from the earliest link timestamp on the instance's URI.
19417
+ // Convention: `SHACLFlow.states` is stored sorted ascending by `value`
19418
+ // (enforced by `fromLinks`), so `states[0]` is the initial state. A
19419
+ // flow author who wants a specific state as the entry point must give
19420
+ // it the lowest `value` in the set.
19421
+ //
19422
+ // Store the flow's URI, not the bare name — see FlowInstanceRecord's
19423
+ // docstring for the collision-across-modules argument (James PR #929 R5).
19424
+ const record = await FlowInstanceRecord.create(perspective, {
19425
+ flowUri: flow.flowUri,
19426
+ subject: baseExpression,
19427
+ currentState: flow.states[0].name,
19428
+ });
19429
+ return FlowInstance.wrap(perspective, flow, record);
19430
+ }
19431
+ /**
19432
+ * Return every live `FlowInstance` on the perspective (design doc §4.3).
19433
+ *
19434
+ * Read-only path: never registers classes. On a perspective that has
19435
+ * never minted a flow instance, the `FlowInstanceRecord` SHACL shape
19436
+ * isn't installed yet — this returns `[]` in that case rather than
19437
+ * mutating the perspective. Registration is the responsibility of
19438
+ * {@link FlowInstance.start}, which is the write path. (Registering on
19439
+ * a read would sync a write to every peer in the neighbourhood —
19440
+ * exactly what a query must not do — James PR #929 R7.)
19441
+ *
19442
+ * Filter surface (all optional, all combinable):
19443
+ * - **`flowName`** — narrows by flow-name discriminator (e.g. "Delivery")
19444
+ * - **`subject`** — narrows by base-expression URI, i.e. "give me every
19445
+ * flow running on THIS expression"
19446
+ *
19447
+ * Both filters translate to a single SHACL `where`-filter round-trip
19448
+ * (no client-side filtering); combining them AND-joins server-side.
19449
+ * The string-arg shape (`FlowInstance.findAll(p, "Delivery")`) is
19450
+ * shorthand for `{ flowName: "Delivery" }`.
19451
+ *
19452
+ * Records whose `flow` value has no matching `SHACLFlow` on the
19453
+ * perspective (e.g. the flow was unregistered) are silently skipped —
19454
+ * the wrapper can't answer `currentState` / `availableTransitions`
19455
+ * without the shape, and callers routinely iterate the returned array
19456
+ * without null-checks.
19457
+ *
19458
+ * @example
19459
+ * ```typescript
19460
+ * const all = await FlowInstance.findAll(perspective);
19461
+ * const deliveries = await FlowInstance.findAll(perspective, "Delivery");
19462
+ * const onThisTask = await FlowInstance.findAll(perspective, {
19463
+ * subject: "ad4m://task/1",
19464
+ * });
19465
+ * const deliveriesOnTask = await FlowInstance.findAll(perspective, {
19466
+ * flowName: "Delivery",
19467
+ * subject: "ad4m://task/1",
19468
+ * });
19469
+ * ```
19470
+ */
19471
+ static async findAll(perspective, filter) {
19472
+ const { flowName, subject } = typeof filter === "string"
19473
+ ? { flowName: filter, subject: undefined }
19474
+ : { flowName: filter?.flowName, subject: filter?.subject };
19475
+ // Filter surface accepts a flow *name* for ergonomics — resolve it to
19476
+ // the canonical URI before the SHACL query, since the record stores
19477
+ // the URI (James PR #929 R5). Unknown name → no matches (short-circuit
19478
+ // with an empty result rather than issuing a bare-name query that
19479
+ // would silently return nothing anyway).
19480
+ const where = {};
19481
+ if (flowName !== undefined) {
19482
+ const flow = await perspective.getFlow(flowName);
19483
+ if (!flow)
19484
+ return [];
19485
+ where.flowUri = flow.flowUri;
19486
+ }
19487
+ if (subject !== undefined)
19488
+ where.subject = subject;
19489
+ // "Shape not found" on a perspective that has never minted a flow
19490
+ // instance is a no-op read, not an error — the executor throws for a
19491
+ // missing SHACL shape and there is no side-effect-free way to ask
19492
+ // "does this class exist". Return `[]` on that specific case; rethrow
19493
+ // anything else so real infra failures don't get swallowed.
19494
+ //
19495
+ // Regex covers every message the executor + client stack raises for
19496
+ // an unregistered class:
19497
+ // "No SHACL shape stored for class 'FlowInstance'." (executor RPC)
19498
+ // "Shape not found" (older Rust path)
19499
+ // "class not registered" / "not registered" (TS Ad4mModel guard)
19500
+ let records;
19501
+ try {
19502
+ records =
19503
+ Object.keys(where).length > 0
19504
+ ? await FlowInstanceRecord.findAll(perspective, { where })
19505
+ : await FlowInstanceRecord.findAll(perspective);
19506
+ }
19507
+ catch (e) {
19508
+ const msg = e instanceof Error ? e.message : String(e);
19509
+ if (/no shacl shape stored|shape not found|class not registered|not registered/i.test(msg)) {
19510
+ return [];
19511
+ }
19512
+ throw e;
19513
+ }
19514
+ // Pair each record with its parsed SHACLFlow. Cache lookups by
19515
+ // flow-URI so `getFlow` fires at most once per distinct flow —
19516
+ // matters when a perspective has hundreds of instances against
19517
+ // one shape.
19518
+ //
19519
+ // The URI stored on the record is `${namespace}${name}Flow`
19520
+ // (see SHACLFlow.flowUri) — recovering the name for `getFlow`
19521
+ // means stripping the namespace + the `Flow` suffix. Records that
19522
+ // don't parse this way are treated as stale and skipped.
19523
+ const shapesByUri = new Map();
19524
+ const wrappers = [];
19525
+ for (const record of records) {
19526
+ let shape = shapesByUri.get(record.flowUri);
19527
+ if (!shape) {
19528
+ const name = flowNameFromUri(record.flowUri);
19529
+ if (!name)
19530
+ continue;
19531
+ const loaded = await perspective.getFlow(name);
19532
+ if (!loaded || loaded.flowUri !== record.flowUri) {
19533
+ // Stale record — the flow it references was unregistered,
19534
+ // or a different flow now owns that name.
19535
+ continue;
19536
+ }
19537
+ shape = loaded;
19538
+ shapesByUri.set(record.flowUri, shape);
19539
+ }
19540
+ wrappers.push(FlowInstance.wrap(perspective, shape, record));
19541
+ }
19542
+ return wrappers;
19543
+ }
19544
+ // ── Read accessors ────────────────────────────────────────────────────
19545
+ /**
19546
+ * URI of the on-graph `FlowInstance` node — `ad4m://flow/instance/{id}`.
19547
+ *
19548
+ * Sourced from `Ad4mModel`'s synthesised `baseExpression`, which for
19549
+ * `FlowInstanceRecord` *is* the instance's own URI (the value
19550
+ * `FlowTransitionProposal.flowInstance` references).
19551
+ */
19552
+ get uri() {
19553
+ return this.record.baseExpression;
19554
+ }
19555
+ /**
19556
+ * URI of the base expression this flow runs on — matches the
19557
+ * `SHACLFlow.inputTypes` that {@link PerspectiveProxy.availableFlows}
19558
+ * would greenlight for this expression.
19559
+ */
19560
+ get subject() {
19561
+ return this.record.subject;
19562
+ }
19563
+ /**
19564
+ * Human-readable flow name — the display label. Sourced from the paired
19565
+ * `SHACLFlow.name`, not from the record (which stores the URI as its
19566
+ * canonical identity — see FlowInstanceRecord's docstring for why).
19567
+ */
19568
+ get flowName() {
19569
+ return this.shape.name;
19570
+ }
19571
+ /** Flow URI — the on-graph discriminator, collision-free across modules. */
19572
+ get flowUri() {
19573
+ return this.record.flowUri;
19574
+ }
19575
+ /** Name of the state this instance is currently in. */
19576
+ get currentStateName() {
19577
+ return this.record.currentState;
19578
+ }
19579
+ /**
19580
+ * ISO-8601 (epoch millis after Ad4mModel hydration) start time.
19581
+ * Returns `undefined` when hydration didn't produce a `createdAt`
19582
+ * — rare, but not fatal.
19583
+ */
19584
+ get startedAtMillis() {
19585
+ const v = this.record.createdAt;
19586
+ return typeof v === "number" ? v : undefined;
19587
+ }
19588
+ /**
19589
+ * The `FlowState` object on the shape matching `currentStateName`.
19590
+ * Throws when the record's state name is not declared on the flow —
19591
+ * that's a "stale FlowInstance whose flow was edited under it" bug,
19592
+ * not a silent-fail case.
19593
+ */
19594
+ get currentState() {
19595
+ const s = this.shape.states.find((x) => x.name === this.currentStateName);
19596
+ if (!s) {
19597
+ throw new Error(`FlowInstance ${this.uri}: currentState "${this.currentStateName}" is not declared on flow "${this.flowName}". ` +
19598
+ `Known states: ${this.shape.states.map((x) => x.name).join(", ") || "(none)"}`);
19599
+ }
19600
+ return s;
19601
+ }
19602
+ /**
19603
+ * Every `FlowTransition` on the shape whose `fromState` matches
19604
+ * `currentStateName`. Order preserved from the shape.
19605
+ *
19606
+ * Empty when the current state is terminal (no outgoing transitions).
19607
+ */
19608
+ get availableTransitions() {
19609
+ return this.shape.transitions.filter((t) => t.fromState === this.currentStateName);
19610
+ }
19611
+ /**
19612
+ * All `FlowTransitionProposal` records targeting this instance's URI.
19613
+ *
19614
+ * Uses the SDNA identity discriminator (`ad4m://flow/instance` predicate)
19615
+ * for the where-filter — one SPARQL round-trip, no client-side
19616
+ * filtering.
19617
+ *
19618
+ * Note: the consensus engine (slice 10.6) will start writing these; today
19619
+ * they only exist when a client wrote one directly (or a test seeded one).
19620
+ */
19621
+ async proposals() {
19622
+ return FlowTransitionProposal.findAll(this.perspective, {
19623
+ where: { flowInstance: this.uri },
19624
+ });
19625
+ }
19626
+ }
19627
+
18145
19628
  /**
18146
19629
  * SPARQL binding helpers — typed shapes and parsers for `querySparql<T>()`.
18147
19630
  *
@@ -18881,4 +20364,4 @@ const fileToDataUri = ifExpr(exists(path('file_storage://data_base64')))
18881
20364
  .then(concat(literal('data:'), coalesce(path('file_storage://file_type'), literal('image/png')), literal(';base64,'), path('file_storage://data_base64')))
18882
20365
  .else(focus());
18883
20366
 
18884
- export { AIClient, Model as AIModel, AIModelLoadingStatus, AIPromptExamples, AIPromptExamplesInput, AITask, AITaskInput, Ad4mClient, Ad4mModel, Agent, AgentClient, AgentExpression, AgentSignature, AgentStatus, Apps, AuthInfo, AuthInfoInput, AutoProcessorConfig, BelongsToMany, BelongsToOne, Capability, CapabilityInput, ComputeLogEntry, EntanglementProof, EntanglementProofInput, ExceptionInfo, ExceptionType, Expression, ExpressionGeneric, ExpressionGenericInput, ExpressionProof, ExpressionProofInput, ExpressionRef, ExpressionRendered, Flag, HasMany, HasOne, HostingUserInfo, IDBCache, Icon, ImportResult, ImportStats, InteractionCall, InteractionMeta, InteractionParameter, InterpretationOverlay, InterpretationRun, LanguageExpression, LanguageHandle, LanguageLanguageInput, LanguageMeta, LanguageMetaInput, LanguageMetaInternal, LanguageRef, Link, LinkExpression, LinkExpressionInput, LinkExpressionMutations, LinkExpressionUpdated, LinkInput, LinkMutations, LinkQuery, Literal, LocalModel, LocalModelInput, Model$1 as Model, ModelApi, ModelApiInput, ModelInput, ModelQueryBuilder, Neighbourhood, NeighbourhoodExpression, NeighbourhoodProxy, Notification, NotificationInput, NullCache, OnlineAgent, Optional, PaymentRequestResult, Perspective, PerspectiveDiff, PerspectiveDiffExpression, PerspectiveExpression, PerspectiveHandle, PerspectiveInput, PerspectiveProxy, PerspectiveState, PerspectiveUnsignedInput, Property, QuerySubscriptionProxy, ReadOnly, Resource, ResourceInput, RpcError as RestError, RpcError, RuntimeInfo, SHACLFlow, SHACLShape, SMART_LITERAL_CONTENT_PREDICATE, SentMessage, SmartLiteral, TokenizerSource, TokenizerSourceInput, TriggeredNotification, UserCreationResult, UserStatistics, VerificationRequestResult, VoiceActivityParamsInput, WakerSubscriptionManager, buildConformanceFilter, buildModelFromJSONSchema, buildPaginationSubquery, buildSDNA, buildSHACL, buildSPARQLQuery, buildWhereCondition, capSentence, clearQueryCache, coalesce, compileWhereClause, concat, createPersistentCache, determineNamespace, determinePredicate, effectiveLiteralStorage, escapeQueryString, exists, exprRef2String, fileToDataUri, fn, focus, formatList, formatQueryValue, formatSPARQLValue, getCachedResult, getDefaultValueForType, getMemoizedSHACL, getPropertiesMetadata, getPropertyOption, getRelationsMetadata, hasJsOnlyWhereFilters, ifExpr, invalidatePerspectiveCache, isArrayType, isExpression, isIncludeProjection, isLink, isNodeExpression, isNumericType, isObjectType, isSchemaType, linkEqual, literal, looksLikeUri, normalizeNamespaceString, normalizeSchemaType, normalizeValue, parseExprUrl, parseLit, parseLitBoolean, parseLitNumber, parseSparqlCount, path, queryCacheSize, resolveParentPredicate, setCachedResult, setPropertyRegistryEntry, setRelationRegistryEntry, typeDefsString, valueToLiteralIri };
20367
+ export { AIClient, Model as AIModel, AIModelLoadingStatus, AIPromptExamples, AIPromptExamplesInput, AITask, AITaskInput, Ad4mClient, Ad4mModel, Agent, AgentClient, AgentExpression, AgentSignature, AgentStatus, Apps, AuthInfo, AuthInfoInput, AutoProcessorConfig, BelongsToMany, BelongsToOne, Capability, CapabilityInput, ComputeLogEntry, EntanglementProof, EntanglementProofInput, ExceptionInfo, ExceptionType, Expression, ExpressionGeneric, ExpressionGenericInput, ExpressionProof, ExpressionProofInput, ExpressionRef, ExpressionRendered, Flag, FlowInstance, FlowInstanceRecord, FlowTransitionProposal, HasMany, HasOne, HostingUserInfo, IDBCache, Icon, ImportResult, ImportStats, InteractionCall, InteractionMeta, InteractionParameter, InterpretationOverlay, InterpretationRun, LanguageExpression, LanguageHandle, LanguageLanguageInput, LanguageMeta, LanguageMetaInput, LanguageMetaInternal, LanguageRef, Link, LinkExpression, LinkExpressionInput, LinkExpressionMutations, LinkExpressionUpdated, LinkInput, LinkMutations, LinkQuery, Literal, LocalModel, LocalModelInput, Model$1 as Model, ModelApi, ModelApiInput, ModelInput, ModelQueryBuilder, Neighbourhood, NeighbourhoodExpression, NeighbourhoodProxy, Notification, NotificationInput, NullCache, OnlineAgent, Optional, PaymentRequestResult, Perspective, PerspectiveDiff, PerspectiveDiffExpression, PerspectiveExpression, PerspectiveHandle, PerspectiveInput, PerspectiveProxy, PerspectiveState, PerspectiveUnsignedInput, Property, QuerySubscriptionProxy, ReadOnly, Resource, ResourceInput, RpcError as RestError, RpcError, RuntimeInfo, SHACLFlow, SHACLShape, SMART_LITERAL_CONTENT_PREDICATE, SentMessage, SmartLiteral, TokenizerSource, TokenizerSourceInput, TriggeredNotification, UserCreationResult, UserStatistics, VerificationRequestResult, VoiceActivityParamsInput, WakerSubscriptionManager, buildConformanceFilter, buildModelFromJSONSchema, buildPaginationSubquery, buildSDNA, buildSHACL, buildSPARQLQuery, buildWhereCondition, capSentence, clearQueryCache, coalesce, compileWhereClause, concat, createPersistentCache, determineNamespace, determinePredicate, effectiveLiteralStorage, escapeQueryString, exists, exprRef2String, fileToDataUri, fn, focus, formatList, formatQueryValue, formatSPARQLValue, getCachedResult, getDefaultValueForType, getMemoizedSHACL, getPropertiesMetadata, getPropertyOption, getRelationsMetadata, hasJsOnlyWhereFilters, ifExpr, invalidatePerspectiveCache, isArrayType, isExpression, isIncludeProjection, isLink, isNodeExpression, isNumericType, isObjectType, isSchemaType, linkEqual, literal, looksLikeUri, normalizeNamespaceString, normalizeSchemaType, normalizeValue, parseExprUrl, parseLit, parseLitBoolean, parseLitNumber, parseSparqlCount, path, queryCacheSize, resolveParentPredicate, setCachedResult, setPropertyRegistryEntry, setRelationRegistryEntry, typeDefsString, valueToLiteralIri };