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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (279) hide show
  1. package/lib/index.cjs +2409 -625
  2. package/lib/index.js +2406 -626
  3. package/lib/src/Literal.js +8 -0
  4. package/lib/src/ai/AIClient.js +6 -3
  5. package/lib/src/apiClient.d.ts +40 -4
  6. package/lib/src/apiClient.js +149 -9
  7. package/lib/src/generated/api/RunInterpretationRequest.d.ts +16 -0
  8. package/lib/src/index.d.ts +3 -1
  9. package/lib/src/index.js +2 -0
  10. package/lib/src/model/Ad4mModel.d.ts +34 -16
  11. package/lib/src/model/Ad4mModel.js +302 -63
  12. package/lib/src/model/Ad4mModel.test.js +480 -735
  13. package/lib/src/model/ModelQueryBuilder.js +2 -2
  14. package/lib/src/model/decorators.d.ts +199 -12
  15. package/lib/src/model/decorators.js +88 -32
  16. package/lib/src/model/json-schema.js +7 -21
  17. package/lib/src/model/model-manifest.d.ts +41 -0
  18. package/lib/src/model/model-manifest.js +11 -0
  19. package/lib/src/model/query-common.d.ts +2 -2
  20. package/lib/src/model/query-sparql.d.ts +62 -0
  21. package/lib/src/model/query-sparql.js +78 -15
  22. package/lib/src/model/query-sparql.test.js +92 -10
  23. package/lib/src/model/query-utils.d.ts +7 -2
  24. package/lib/src/model/query-utils.js +21 -11
  25. package/lib/src/model/shacl-gen.js +77 -15
  26. package/lib/src/model/types.d.ts +32 -8
  27. package/lib/src/neighbourhood/NeighbourhoodProxy.test.js +33 -33
  28. package/lib/src/perspectives/AutoProcessor.d.ts +198 -2
  29. package/lib/src/perspectives/FlowInstance.d.ts +187 -0
  30. package/lib/src/perspectives/FlowInstance.js +336 -0
  31. package/lib/src/perspectives/FlowModels.d.ts +94 -0
  32. package/lib/src/perspectives/FlowModels.js +182 -0
  33. package/lib/src/perspectives/InterpretationModels.d.ts +41 -3
  34. package/lib/src/perspectives/InterpretationModels.js +60 -26
  35. package/lib/src/perspectives/PerspectiveClient.d.ts +88 -7
  36. package/lib/src/perspectives/PerspectiveClient.js +138 -11
  37. package/lib/src/perspectives/PerspectiveProxy.d.ts +150 -57
  38. package/lib/src/perspectives/PerspectiveProxy.js +411 -287
  39. package/lib/src/perspectives/SparqlBindings.d.ts +24 -3
  40. package/lib/src/perspectives/SparqlBindings.js +57 -6
  41. package/lib/src/shacl/SHACLFlow.d.ts +273 -47
  42. package/lib/src/shacl/SHACLFlow.js +397 -88
  43. package/lib/src/shacl/SHACLShape.d.ts +19 -3
  44. package/lib/src/shacl/SHACLShape.js +30 -1
  45. package/lib/src/shacl/SHACLShape.test.js +82 -0
  46. package/lib/src/shacl/index.d.ts +1 -1
  47. package/lib/src/shacl/index.js +1 -1
  48. package/package.json +3 -3
  49. package/src/Literal.ts +7 -0
  50. package/src/ai/AIClient.ts +6 -3
  51. package/src/apiClient.test.ts +227 -0
  52. package/src/apiClient.ts +185 -9
  53. package/src/generated/api/RunInterpretationRequest.ts +19 -3
  54. package/src/index.ts +3 -1
  55. package/src/model/Ad4mModel.test.ts +729 -22
  56. package/src/model/Ad4mModel.ts +305 -66
  57. package/src/model/ModelQueryBuilder.ts +2 -2
  58. package/src/model/decorators.ts +278 -44
  59. package/src/model/json-schema.ts +10 -25
  60. package/src/model/query-common.ts +2 -2
  61. package/src/model/query-sparql.test.ts +114 -13
  62. package/src/model/query-sparql.ts +83 -14
  63. package/src/model/query-utils.ts +22 -12
  64. package/src/model/relation-filtering.test.ts +70 -20
  65. package/src/model/shacl-gen.ts +78 -13
  66. package/src/model/shacl-roundtrip.test.ts +134 -2
  67. package/src/model/types.ts +30 -8
  68. package/src/perspectives/AutoProcessor.ts +204 -2
  69. package/src/perspectives/FlowInstance.ts +369 -0
  70. package/src/perspectives/FlowModels.ts +157 -0
  71. package/src/perspectives/InterpretationModels.ts +91 -21
  72. package/src/perspectives/PerspectiveClient.test.ts +67 -6
  73. package/src/perspectives/PerspectiveClient.ts +190 -14
  74. package/src/perspectives/PerspectiveProxy.test.ts +406 -0
  75. package/src/perspectives/PerspectiveProxy.ts +494 -308
  76. package/src/perspectives/SparqlBindings.test.ts +134 -0
  77. package/src/perspectives/SparqlBindings.ts +57 -6
  78. package/src/perspectives/shacl-rpc.test.ts +258 -0
  79. package/src/shacl/SHACLFlow.test.ts +762 -35
  80. package/src/shacl/SHACLFlow.ts +680 -112
  81. package/src/shacl/SHACLShape.test.ts +30 -4
  82. package/src/shacl/SHACLShape.ts +59 -6
  83. package/src/shacl/index.ts +1 -1
  84. package/lib/src/generated/rest/AIModelLoadingStatus.d.ts +0 -7
  85. package/lib/src/generated/rest/AIModelLoadingStatus.js +0 -2
  86. package/lib/src/generated/rest/AddAgentInfosRequest.d.ts +0 -3
  87. package/lib/src/generated/rest/AddAgentInfosRequest.js +0 -2
  88. package/lib/src/generated/rest/AddLinkExpressionRequest.d.ts +0 -6
  89. package/lib/src/generated/rest/AddLinkExpressionRequest.js +0 -1
  90. package/lib/src/generated/rest/AddLinkRequest.d.ts +0 -6
  91. package/lib/src/generated/rest/AddLinkRequest.js +0 -1
  92. package/lib/src/generated/rest/AddLinksBulkRequest.d.ts +0 -6
  93. package/lib/src/generated/rest/AddLinksBulkRequest.js +0 -1
  94. package/lib/src/generated/rest/AddSdnaRequest.d.ts +0 -6
  95. package/lib/src/generated/rest/AddSdnaRequest.js +0 -2
  96. package/lib/src/generated/rest/ApplyTemplateRequest.d.ts +0 -4
  97. package/lib/src/generated/rest/ApplyTemplateRequest.js +0 -2
  98. package/lib/src/generated/rest/AuthInfoInput.d.ts +0 -10
  99. package/lib/src/generated/rest/AuthInfoInput.js +0 -1
  100. package/lib/src/generated/rest/BroadcastRequest.d.ts +0 -6
  101. package/lib/src/generated/rest/BroadcastRequest.js +0 -1
  102. package/lib/src/generated/rest/CapabilityInput.d.ts +0 -5
  103. package/lib/src/generated/rest/CapabilityInput.js +0 -1
  104. package/lib/src/generated/rest/CommitBatchRequest.d.ts +0 -3
  105. package/lib/src/generated/rest/CommitBatchRequest.js +0 -2
  106. package/lib/src/generated/rest/ComputeLogEntry.d.ts +0 -9
  107. package/lib/src/generated/rest/ComputeLogEntry.js +0 -2
  108. package/lib/src/generated/rest/CreateExpressionRequest.d.ts +0 -4
  109. package/lib/src/generated/rest/CreateExpressionRequest.js +0 -2
  110. package/lib/src/generated/rest/CreatePerspectiveRequest.d.ts +0 -3
  111. package/lib/src/generated/rest/CreatePerspectiveRequest.js +0 -2
  112. package/lib/src/generated/rest/CreateSubjectRequest.d.ts +0 -6
  113. package/lib/src/generated/rest/CreateSubjectRequest.js +0 -2
  114. package/lib/src/generated/rest/CreateUserRequest.d.ts +0 -4
  115. package/lib/src/generated/rest/CreateUserRequest.js +0 -2
  116. package/lib/src/generated/rest/CreateUserResponse.d.ts +0 -5
  117. package/lib/src/generated/rest/CreateUserResponse.js +0 -2
  118. package/lib/src/generated/rest/DecoratedExpressionProof.d.ts +0 -6
  119. package/lib/src/generated/rest/DecoratedExpressionProof.js +0 -2
  120. package/lib/src/generated/rest/DecoratedLinkExpression.d.ts +0 -10
  121. package/lib/src/generated/rest/DecoratedLinkExpression.js +0 -1
  122. package/lib/src/generated/rest/DisposeQueryRequest.d.ts +0 -3
  123. package/lib/src/generated/rest/DisposeQueryRequest.js +0 -2
  124. package/lib/src/generated/rest/EmailTestRequest.d.ts +0 -6
  125. package/lib/src/generated/rest/EmailTestRequest.js +0 -2
  126. package/lib/src/generated/rest/EmbedRequest.d.ts +0 -4
  127. package/lib/src/generated/rest/EmbedRequest.js +0 -2
  128. package/lib/src/generated/rest/EntanglementProofInput.d.ts +0 -6
  129. package/lib/src/generated/rest/EntanglementProofInput.js +0 -2
  130. package/lib/src/generated/rest/EntanglementProofPreflightRequest.d.ts +0 -4
  131. package/lib/src/generated/rest/EntanglementProofPreflightRequest.js +0 -2
  132. package/lib/src/generated/rest/ExecuteCommandsRequest.d.ts +0 -4
  133. package/lib/src/generated/rest/ExecuteCommandsRequest.js +0 -2
  134. package/lib/src/generated/rest/ExportRequest.d.ts +0 -5
  135. package/lib/src/generated/rest/ExportRequest.js +0 -2
  136. package/lib/src/generated/rest/ExpressionManyRequest.d.ts +0 -3
  137. package/lib/src/generated/rest/ExpressionManyRequest.js +0 -2
  138. package/lib/src/generated/rest/ExpressionProof.d.ts +0 -4
  139. package/lib/src/generated/rest/ExpressionProof.js +0 -2
  140. package/lib/src/generated/rest/ExpressionProofInput.d.ts +0 -6
  141. package/lib/src/generated/rest/ExpressionProofInput.js +0 -2
  142. package/lib/src/generated/rest/FriendSendMessageRequest.d.ts +0 -3
  143. package/lib/src/generated/rest/FriendSendMessageRequest.js +0 -2
  144. package/lib/src/generated/rest/FriendsListRequest.d.ts +0 -3
  145. package/lib/src/generated/rest/FriendsListRequest.js +0 -2
  146. package/lib/src/generated/rest/GenerateAgentRequest.d.ts +0 -3
  147. package/lib/src/generated/rest/GenerateAgentRequest.js +0 -2
  148. package/lib/src/generated/rest/GenerateJwtRequest.d.ts +0 -4
  149. package/lib/src/generated/rest/GenerateJwtRequest.js +0 -2
  150. package/lib/src/generated/rest/GetSubjectDataRequest.d.ts +0 -4
  151. package/lib/src/generated/rest/GetSubjectDataRequest.js +0 -2
  152. package/lib/src/generated/rest/HostingInfoResponse.d.ts +0 -5
  153. package/lib/src/generated/rest/HostingInfoResponse.js +0 -2
  154. package/lib/src/generated/rest/HostingWalletResponse.d.ts +0 -4
  155. package/lib/src/generated/rest/HostingWalletResponse.js +0 -2
  156. package/lib/src/generated/rest/ImportAgentRequest.d.ts +0 -6
  157. package/lib/src/generated/rest/ImportAgentRequest.js +0 -2
  158. package/lib/src/generated/rest/ImportRequest.d.ts +0 -4
  159. package/lib/src/generated/rest/ImportRequest.js +0 -2
  160. package/lib/src/generated/rest/JoinNeighbourhoodRequest.d.ts +0 -3
  161. package/lib/src/generated/rest/JoinNeighbourhoodRequest.js +0 -2
  162. package/lib/src/generated/rest/KeepAliveQueryRequest.d.ts +0 -3
  163. package/lib/src/generated/rest/KeepAliveQueryRequest.js +0 -2
  164. package/lib/src/generated/rest/LanguageMetaInput.d.ts +0 -6
  165. package/lib/src/generated/rest/LanguageMetaInput.js +0 -2
  166. package/lib/src/generated/rest/Link.d.ts +0 -5
  167. package/lib/src/generated/rest/Link.js +0 -2
  168. package/lib/src/generated/rest/LinkExpression.d.ts +0 -10
  169. package/lib/src/generated/rest/LinkExpression.js +0 -1
  170. package/lib/src/generated/rest/LinkExpressionInput.d.ts +0 -10
  171. package/lib/src/generated/rest/LinkExpressionInput.js +0 -1
  172. package/lib/src/generated/rest/LinkInput.d.ts +0 -5
  173. package/lib/src/generated/rest/LinkInput.js +0 -2
  174. package/lib/src/generated/rest/LinkLanguageTemplatesRequest.d.ts +0 -3
  175. package/lib/src/generated/rest/LinkLanguageTemplatesRequest.js +0 -2
  176. package/lib/src/generated/rest/LinkMutationRequest.d.ts +0 -12
  177. package/lib/src/generated/rest/LinkMutationRequest.js +0 -1
  178. package/lib/src/generated/rest/LinkMutationResponse.d.ts +0 -9
  179. package/lib/src/generated/rest/LinkMutationResponse.js +0 -1
  180. package/lib/src/generated/rest/LinkMutations.d.ts +0 -6
  181. package/lib/src/generated/rest/LinkMutations.js +0 -1
  182. package/lib/src/generated/rest/LinkMutationsRequest.d.ts +0 -5
  183. package/lib/src/generated/rest/LinkMutationsRequest.js +0 -1
  184. package/lib/src/generated/rest/LinkStatus.d.ts +0 -1
  185. package/lib/src/generated/rest/LinkStatus.js +0 -2
  186. package/lib/src/generated/rest/LinkUpdateInput.d.ts +0 -5
  187. package/lib/src/generated/rest/LinkUpdateInput.js +0 -1
  188. package/lib/src/generated/rest/LockAgentRequest.d.ts +0 -3
  189. package/lib/src/generated/rest/LockAgentRequest.js +0 -2
  190. package/lib/src/generated/rest/LoginUserRequest.d.ts +0 -5
  191. package/lib/src/generated/rest/LoginUserRequest.js +0 -2
  192. package/lib/src/generated/rest/ModelType.d.ts +0 -1
  193. package/lib/src/generated/rest/ModelType.js +0 -2
  194. package/lib/src/generated/rest/NotificationGrantRequest.d.ts +0 -3
  195. package/lib/src/generated/rest/NotificationGrantRequest.js +0 -2
  196. package/lib/src/generated/rest/NotificationInput.d.ts +0 -10
  197. package/lib/src/generated/rest/NotificationInput.js +0 -2
  198. package/lib/src/generated/rest/OpenLinkRequest.d.ts +0 -3
  199. package/lib/src/generated/rest/OpenLinkRequest.js +0 -2
  200. package/lib/src/generated/rest/PermitCapabilityRequest.d.ts +0 -3
  201. package/lib/src/generated/rest/PermitCapabilityRequest.js +0 -2
  202. package/lib/src/generated/rest/PerspectiveInput.d.ts +0 -4
  203. package/lib/src/generated/rest/PerspectiveInput.js +0 -1
  204. package/lib/src/generated/rest/PromptRequest.d.ts +0 -4
  205. package/lib/src/generated/rest/PromptRequest.js +0 -2
  206. package/lib/src/generated/rest/PublicPerspectiveInput.d.ts +0 -4
  207. package/lib/src/generated/rest/PublicPerspectiveInput.js +0 -1
  208. package/lib/src/generated/rest/PublishLanguageRequest.d.ts +0 -5
  209. package/lib/src/generated/rest/PublishLanguageRequest.js +0 -1
  210. package/lib/src/generated/rest/PublishNeighbourhoodRequest.d.ts +0 -6
  211. package/lib/src/generated/rest/PublishNeighbourhoodRequest.js +0 -1
  212. package/lib/src/generated/rest/QueryRequest.d.ts +0 -7
  213. package/lib/src/generated/rest/QueryRequest.js +0 -2
  214. package/lib/src/generated/rest/RemoveLinkRequest.d.ts +0 -5
  215. package/lib/src/generated/rest/RemoveLinkRequest.js +0 -1
  216. package/lib/src/generated/rest/RemoveLinksBulkRequest.d.ts +0 -5
  217. package/lib/src/generated/rest/RemoveLinksBulkRequest.js +0 -1
  218. package/lib/src/generated/rest/RequestCapabilityRequest.d.ts +0 -4
  219. package/lib/src/generated/rest/RequestCapabilityRequest.js +0 -1
  220. package/lib/src/generated/rest/RequestPaymentRequest.d.ts +0 -3
  221. package/lib/src/generated/rest/RequestPaymentRequest.js +0 -2
  222. package/lib/src/generated/rest/RequestVerificationRequest.d.ts +0 -4
  223. package/lib/src/generated/rest/RequestVerificationRequest.js +0 -2
  224. package/lib/src/generated/rest/ResourceInput.d.ts +0 -4
  225. package/lib/src/generated/rest/ResourceInput.js +0 -2
  226. package/lib/src/generated/rest/SetDefaultModelRequest.d.ts +0 -4
  227. package/lib/src/generated/rest/SetDefaultModelRequest.js +0 -1
  228. package/lib/src/generated/rest/SetFreeHostingEnabledRequest.d.ts +0 -3
  229. package/lib/src/generated/rest/SetFreeHostingEnabledRequest.js +0 -2
  230. package/lib/src/generated/rest/SetHotWalletAddressRequest.d.ts +0 -3
  231. package/lib/src/generated/rest/SetHotWalletAddressRequest.js +0 -2
  232. package/lib/src/generated/rest/SetMultiUserRequest.d.ts +0 -3
  233. package/lib/src/generated/rest/SetMultiUserRequest.js +0 -2
  234. package/lib/src/generated/rest/SetOnlineStatusRequest.d.ts +0 -5
  235. package/lib/src/generated/rest/SetOnlineStatusRequest.js +0 -1
  236. package/lib/src/generated/rest/SetStatusRequest.d.ts +0 -3
  237. package/lib/src/generated/rest/SetStatusRequest.js +0 -2
  238. package/lib/src/generated/rest/SetUserFreeAccessRequest.d.ts +0 -4
  239. package/lib/src/generated/rest/SetUserFreeAccessRequest.js +0 -2
  240. package/lib/src/generated/rest/SignMessageRequest.d.ts +0 -3
  241. package/lib/src/generated/rest/SignMessageRequest.js +0 -2
  242. package/lib/src/generated/rest/SignalRequest.d.ts +0 -6
  243. package/lib/src/generated/rest/SignalRequest.js +0 -1
  244. package/lib/src/generated/rest/SubscribeQueryRequest.d.ts +0 -3
  245. package/lib/src/generated/rest/SubscribeQueryRequest.js +0 -2
  246. package/lib/src/generated/rest/SubscribeQueryResponse.d.ts +0 -4
  247. package/lib/src/generated/rest/SubscribeQueryResponse.js +0 -2
  248. package/lib/src/generated/rest/TrustedAgentsRequest.d.ts +0 -3
  249. package/lib/src/generated/rest/TrustedAgentsRequest.js +0 -2
  250. package/lib/src/generated/rest/UnlockAgentRequest.d.ts +0 -4
  251. package/lib/src/generated/rest/UnlockAgentRequest.js +0 -2
  252. package/lib/src/generated/rest/UpdateLinkRequest.d.ts +0 -7
  253. package/lib/src/generated/rest/UpdateLinkRequest.js +0 -1
  254. package/lib/src/generated/rest/UpdatePerspectiveRequest.d.ts +0 -3
  255. package/lib/src/generated/rest/UpdatePerspectiveRequest.js +0 -2
  256. package/lib/src/generated/rest/UpdateProfileRequest.d.ts +0 -5
  257. package/lib/src/generated/rest/UpdateProfileRequest.js +0 -1
  258. package/lib/src/generated/rest/UserStatistics.d.ts +0 -9
  259. package/lib/src/generated/rest/UserStatistics.js +0 -2
  260. package/lib/src/generated/rest/VerificationRequestResult.d.ts +0 -6
  261. package/lib/src/generated/rest/VerificationRequestResult.js +0 -2
  262. package/lib/src/generated/rest/VerifyEmailRequest.d.ts +0 -6
  263. package/lib/src/generated/rest/VerifyEmailRequest.js +0 -2
  264. package/lib/src/generated/rest/VerifySignatureRequest.d.ts +0 -5
  265. package/lib/src/generated/rest/VerifySignatureRequest.js +0 -2
  266. package/lib/src/generated/rest/WriteSettingsRequest.d.ts +0 -3
  267. package/lib/src/generated/rest/WriteSettingsRequest.js +0 -2
  268. package/lib/src/generated/rest/index.d.ts +0 -73
  269. package/lib/src/generated/rest/index.js +0 -8
  270. package/lib/src/generated/rest/routes.d.ts +0 -587
  271. package/lib/src/generated/rest/routes.js +0 -3
  272. package/lib/src/model/query-surreal.d.ts +0 -44
  273. package/lib/src/model/query-surreal.js +0 -249
  274. package/lib/src/model/surreal-utils.d.ts +0 -42
  275. package/lib/src/model/surreal-utils.js +0 -128
  276. package/lib/src/perspectives/PerspectiveProxy.test.d.ts +0 -1
  277. package/lib/src/perspectives/PerspectiveProxy.test.js +0 -34
  278. package/lib/src/restClient.d.ts +0 -52
  279. package/lib/src/restClient.js +0 -227
@@ -1,4 +1,5 @@
1
1
  import { LinkCallback, PerspectiveClient, SyncStateChangeCallback } from "./PerspectiveClient";
2
+ import { CallOptions } from "../apiClient";
2
3
  import { Link, LinkExpression, LinkExpressionInput, LinkExpressionMutations, LinkMutations } from "../links/Links";
3
4
  import { LinkQuery } from "./LinkQuery";
4
5
  import { PerspectiveHandle, PerspectiveState } from './PerspectiveHandle'
@@ -15,8 +16,9 @@ import { AllInstancesResult } from "../model/types";
15
16
  import type { TranscriptTurn } from "../generated/api";
16
17
 
17
18
  import { SHACLShape } from "../shacl/SHACLShape";
18
- import { SHACLFlow, LinkPattern } from "../shacl/SHACLFlow";
19
- import type { AddAutoProcessorConfig, AutoProcessorEvent, InterpretationOverlayInfo } from "./AutoProcessor";
19
+ import { SHACLFlow } from "../shacl/SHACLFlow";
20
+ import { Ad4mModel } from "../model/Ad4mModel";
21
+ import type { AddAutoProcessorConfig, AutoProcessorEvent, AutoProcessorNeighbourhoodStateEvent, InterpretationOverlayInfo, RawScope, RunInterpretationObserveOptions } from "./AutoProcessor";
20
22
 
21
23
  type QueryCallback = (result: AllInstancesResult) => void;
22
24
 
@@ -77,6 +79,7 @@ export class QuerySubscriptionProxy {
77
79
  #callbacks: Set<QueryCallback>;
78
80
  #keepaliveTimer: number;
79
81
  #unsubscribe?: () => void;
82
+ #reconnectUnsub?: () => void;
80
83
  #latestResult: AllInstancesResult|null;
81
84
  #disposed: boolean = false;
82
85
  #initialized: Promise<boolean>;
@@ -84,6 +87,15 @@ export class QuerySubscriptionProxy {
84
87
  #initReject?: (reason?: any) => void;
85
88
  #initTimeoutId?: NodeJS.Timeout;
86
89
  #query: string;
90
+ // Monotonic token guarding the three concurrent writers of
91
+ // `#unsubscribe`/`#subscriptionId` (full subscribe() from the keepalive
92
+ // and init-timeout retry paths, and the reconnect swap handler). Each
93
+ // writer bumps it on entry and re-checks after every await; a mismatch
94
+ // means a newer writer took over while we were suspended, so the stale
95
+ // continuation must back out instead of clobbering the newer state
96
+ // (worst case otherwise: an overwritten-but-never-called unsubscribe
97
+ // leaks its callback in ApiClient._wsCallbacks for the client lifetime).
98
+ #generation: number = 0;
87
99
 
88
100
  /** Creates a new query subscription
89
101
  * @param uuid - The UUID of the perspective
@@ -105,12 +117,33 @@ export class QuerySubscriptionProxy {
105
117
  }
106
118
 
107
119
  async subscribe() {
120
+ // Invalidate any suspended writer (older subscribe() or reconnect
121
+ // swap parked on an await) — see #generation.
122
+ const generation = ++this.#generation;
123
+
124
+ // Remove any prior reconnect listener FIRST — before we touch
125
+ // `#unsubscribe`. Rationale: `#unsubscribe()` calls into
126
+ // `ApiClient.subscribe()`'s deleter, which closes the WebSocket
127
+ // whenever this query owned the last `_wsCallbacks` entry (and no
128
+ // RPCs are pending). The subsequent `subscribeQuery()` below then
129
+ // re-opens a fresh socket, and that fresh `onopen` fires the
130
+ // reconnect callback set. If the OLD reconnect listener is still
131
+ // in that set, it re-enters this method, closes the socket again,
132
+ // reopens again … an endless resubscribe loop. Clearing the
133
+ // listener up-front breaks the cycle; a fresh listener is
134
+ // installed at the end of a successful subscribe(), and a
135
+ // full-retry recovery listener in the catch block on failure.
136
+ if (this.#reconnectUnsub) {
137
+ this.#reconnectUnsub();
138
+ this.#reconnectUnsub = undefined;
139
+ }
140
+
108
141
  // Clean up previous subscription attempt if retrying
109
142
  if (this.#unsubscribe) {
110
143
  this.#unsubscribe();
111
144
  this.#unsubscribe = undefined;
112
145
  }
113
-
146
+
114
147
  // Clear any existing timeout
115
148
  if (this.#initTimeoutId) {
116
149
  clearTimeout(this.#initTimeoutId);
@@ -127,6 +160,17 @@ export class QuerySubscriptionProxy {
127
160
  // Initialize the query subscription
128
161
  let initialResult;
129
162
  initialResult = await this.#client.subscribeQuery(this.#uuid, this.#query);
163
+
164
+ // A newer writer (another subscribe() or a reconnect swap) took
165
+ // over while we awaited — back out without touching shared state,
166
+ // and release the now-orphaned server-side subscription so it
167
+ // doesn't linger until its keepalive TTL expires.
168
+ if (this.#disposed || this.#generation !== generation) {
169
+ this.#client.disposeQuerySubscription(this.#uuid, initialResult.subscriptionId)
170
+ .catch(e => console.error('Error disposing superseded query subscription:', e));
171
+ return;
172
+ }
173
+
130
174
  this.#subscriptionId = initialResult.subscriptionId;
131
175
 
132
176
  // Process the initial result immediately for fast UX.
@@ -134,14 +178,7 @@ export class QuerySubscriptionProxy {
134
178
  // so treat that as successful initialization instead of waiting for a
135
179
  // follow-up WebSocket update that may never arrive until the query changes.
136
180
  if (initialResult.result !== undefined) {
137
- this.#latestResult = initialResult.result;
138
- this.#notifyCallbacks(initialResult.result);
139
-
140
- if (this.#initResolve) {
141
- this.#initResolve(true);
142
- this.#initResolve = undefined;
143
- this.#initReject = undefined;
144
- }
181
+ this.#deliverResult(initialResult.result);
145
182
  } else {
146
183
  console.warn('⚠️ No initial result returned from subscribeQuery!');
147
184
 
@@ -159,65 +196,139 @@ export class QuerySubscriptionProxy {
159
196
  // Subscribe to query updates
160
197
  this.#unsubscribe = this.#client.subscribeToQueryUpdates(
161
198
  this.#subscriptionId,
162
- (updateResult) => {
163
- // Clear timeout on first message
164
- if (this.#initTimeoutId) {
165
- clearTimeout(this.#initTimeoutId);
166
- this.#initTimeoutId = undefined;
167
- }
168
-
169
- // Resolve the initialization promise (only resolves once)
170
- if (this.#initResolve) {
171
- this.#initResolve(true);
172
- this.#initResolve = undefined; // Prevent double-resolve
173
- this.#initReject = undefined;
174
- }
175
-
176
- this.#latestResult = updateResult;
177
- this.#notifyCallbacks(updateResult);
178
- }
199
+ (updateResult) => this.#deliverResult(updateResult)
179
200
  );
180
201
  } catch (error) {
181
202
  console.error('Error setting up subscription:', error);
182
-
203
+
183
204
  // Reject the promise if this is the first attempt
184
205
  if (this.#initReject) {
185
206
  this.#initReject(error);
186
207
  this.#initResolve = undefined;
187
208
  this.#initReject = undefined;
188
209
  }
189
-
210
+
211
+ // Restore reconnect recovery before rethrowing. The listener was
212
+ // removed at the top of this method; without re-installing one
213
+ // here, a single failed resubscribe (e.g. subscribeQuery timing
214
+ // out during a network flap) would leave the proxy permanently
215
+ // dead: the keepalive loop stops itself on resubscribe failure,
216
+ // and nothing else retries. The recovery listener runs the FULL
217
+ // subscribe() (not the swap-in-place handler) because after a
218
+ // failed attempt there is no keepalive loop left to feed the new
219
+ // server subscription — subscribe() restarts it. This is
220
+ // loop-safe: in this failed state the proxy owns no
221
+ // `_wsCallbacks` entry (the old one was unsubscribed at the top
222
+ // of this method and no new one got registered), so the
223
+ // subscribe() it triggers has nothing to unsubscribe → the
224
+ // socket never closes/reopens under it → no re-entrant onopen.
225
+ if (!this.#disposed && this.#generation === generation && this.#client.onReconnect) {
226
+ this.#reconnectUnsub = this.#client.onReconnect(() => {
227
+ if (this.#disposed) return;
228
+ console.log('WebSocket reconnected — retrying failed subscription for query:', this.#query);
229
+ this.subscribe().catch(e => {
230
+ console.error('Error during subscription retry after reconnect:', e);
231
+ });
232
+ });
233
+ }
234
+
190
235
  throw error; // Re-throw so caller knows it failed
191
236
  }
192
237
 
193
- // Start keepalive loop using platform-agnostic setTimeout
194
- const keepaliveLoop = async () => {
195
- if (this.#disposed) return;
196
-
197
- try {
198
- await this.#client.keepAliveQuery(this.#uuid, this.#subscriptionId);
199
- } catch (e) {
200
- console.error('Error in keepalive:', e);
201
- // try to reinitialize the subscription
202
- console.log('Reinitializing subscription for query:', this.#query);
238
+ // Start keepalive loop
239
+ this.#startKeepalive(generation);
240
+
241
+ // Register for reconnect notification — on WebSocket reconnect,
242
+ // immediately re-establish a fresh server-side subscription instead
243
+ // of waiting up to 30s for the keepalive to fail.
244
+ //
245
+ // We deliberately do NOT call `this.subscribe()` here. Full subscribe
246
+ // runs `#unsubscribe` first, which delegates to `ApiClient.subscribe`'s
247
+ // deleter — that closes the WebSocket when this query owned the LAST
248
+ // `_wsCallbacks` entry. The subsequent `subscribeQuery` reopens the
249
+ // socket, whose fresh `onopen` fires every registered reconnect
250
+ // callback again → recursion (CodeRabbit's original finding). And
251
+ // during that close→reopen gap, RPCs in flight from OTHER proxies
252
+ // fail with `503 WebSocket not connected` (observed in
253
+ // integration-tests-mcp `should fire onWake when mention uses agent DID`
254
+ // after PR #899's initial fix — the WakerSubscriptionManager tests
255
+ // share a wakerClient across cases, so any dying reconnect handler
256
+ // interferes with sibling subscriptions).
257
+ //
258
+ // The correct shape is a swap-in-place: get a new server-side
259
+ // subscription ID via `subscribeQuery`, register a new client-side
260
+ // callback FIRST, and only then unsubscribe the old one. That way
261
+ // `_wsCallbacks.size` never dips to 0 during the transition, so the
262
+ // socket doesn't close, no reconnect loop, and no cross-proxy 503s.
263
+ // Any prior listener was already removed at the top of this method
264
+ // (see the note there for why cleanup must run before `#unsubscribe`,
265
+ // not here).
266
+ if (this.#client.onReconnect) {
267
+ this.#reconnectUnsub = this.#client.onReconnect(async () => {
268
+ if (this.#disposed) return;
269
+ // The handler is a writer of `#unsubscribe`/`#subscriptionId`
270
+ // too, so it takes its own generation — see #generation.
271
+ const swapGeneration = ++this.#generation;
272
+ console.log(
273
+ 'WebSocket reconnected — re-establishing server subscription for query:',
274
+ this.#query,
275
+ );
203
276
  try {
204
- await this.subscribe();
205
- console.log('Subscription reinitialized');
206
- } catch (resubscribeError) {
207
- console.error('Error during resubscription from keepalive:', resubscribeError);
208
- // Don't schedule another keepalive on resubscribe failure
209
- return;
277
+ const newInitial = await this.#client.subscribeQuery(this.#uuid, this.#query);
278
+ if (this.#disposed || this.#generation !== swapGeneration) {
279
+ // A newer writer took over while we awaited — back out
280
+ // and release the orphaned server-side subscription.
281
+ this.#client.disposeQuerySubscription(this.#uuid, newInitial.subscriptionId)
282
+ .catch(e => console.error('Error disposing superseded query subscription:', e));
283
+ return;
284
+ }
285
+ const newSubId = newInitial.subscriptionId;
286
+
287
+ // Register the NEW client-side callback BEFORE removing the
288
+ // old one — keeps `_wsCallbacks.size >= 1` across the swap.
289
+ const newUnsub = this.#client.subscribeToQueryUpdates(
290
+ newSubId,
291
+ (updateResult) => this.#deliverResult(updateResult),
292
+ );
293
+ const oldUnsub = this.#unsubscribe;
294
+ this.#unsubscribe = newUnsub;
295
+ this.#subscriptionId = newSubId;
296
+ if (oldUnsub) oldUnsub();
297
+
298
+ // Our generation bump invalidated the running keepalive
299
+ // loop — restart it under our generation so the new
300
+ // server subscription keeps receiving keepalives.
301
+ clearTimeout(this.#keepaliveTimer);
302
+ this.#startKeepalive(swapGeneration);
303
+
304
+ // Deliver the fresh initial result if the server included one
305
+ // (matches the eager-delivery path in the main subscribe() body).
306
+ // #deliverResult also clears a still-pending init timeout and
307
+ // resolves #initialized, keeping this path symmetric with the
308
+ // update callback in subscribe() — without it, a swap landing
309
+ // while initialization was pending would leave the 30s init
310
+ // timer armed and trigger a spurious full resubscribe.
311
+ if (newInitial.result !== undefined) {
312
+ this.#deliverResult(newInitial.result);
313
+ }
314
+ } catch (error) {
315
+ console.error(
316
+ 'Error re-establishing subscription after reconnect:',
317
+ error,
318
+ );
319
+ // Our generation bump invalidated the running keepalive
320
+ // loop; if nothing newer superseded us, restart it so
321
+ // liveness is preserved — its keepAliveQuery against the
322
+ // dead old subscription will fail and fall back to a
323
+ // full subscribe(). The reconnect listener also remains
324
+ // installed, so a later reconnect retries this handler.
325
+ if (!this.#disposed && this.#generation === swapGeneration) {
326
+ clearTimeout(this.#keepaliveTimer);
327
+ this.#startKeepalive(swapGeneration);
328
+ }
210
329
  }
211
- }
212
-
213
- // Schedule next keepalive if not disposed
214
- if (!this.#disposed) {
215
- this.#keepaliveTimer = setTimeout(keepaliveLoop, 30000) as unknown as number;
216
- }
217
- };
218
-
219
- // Start the first keepalive loop
220
- this.#keepaliveTimer = setTimeout(keepaliveLoop, 30000) as unknown as number;
330
+ });
331
+ }
221
332
  }
222
333
 
223
334
  /** Get the subscription ID for this query subscription
@@ -283,6 +394,69 @@ export class QuerySubscriptionProxy {
283
394
  return () => this.#callbacks.delete(callback);
284
395
  }
285
396
 
397
+ /** Deliver a result to consumers: complete a still-pending
398
+ * initialization (clear the 30s init timeout, resolve #initialized),
399
+ * record the result as latest, and notify all callbacks. Shared by the
400
+ * initial-result path, the update callback, and the reconnect swap
401
+ * handler so all three stay lifecycle-symmetric. */
402
+ #deliverResult(result: AllInstancesResult) {
403
+ if (this.#initTimeoutId) {
404
+ clearTimeout(this.#initTimeoutId);
405
+ this.#initTimeoutId = undefined;
406
+ }
407
+ // Resolve the initialization promise (only resolves once)
408
+ if (this.#initResolve) {
409
+ this.#initResolve(true);
410
+ this.#initResolve = undefined; // Prevent double-resolve
411
+ this.#initReject = undefined;
412
+ }
413
+ this.#latestResult = result;
414
+ this.#notifyCallbacks(result);
415
+ }
416
+
417
+ /** Start the keepalive loop for the given generation. The loop runs
418
+ * every 30s until it is superseded (generation mismatch — a newer
419
+ * subscribe() or reconnect swap took over) or the proxy is disposed.
420
+ * On a keepalive error it falls back to a full subscribe(). */
421
+ #startKeepalive(generation: number) {
422
+ const keepaliveLoop = async () => {
423
+ // Generation check kills orphaned loops: a loop whose
424
+ // keepAliveQuery was in flight while a newer writer ran is not
425
+ // cancelled by clearTimeout and would otherwise reschedule
426
+ // itself alongside the newer loop.
427
+ if (this.#disposed || this.#generation !== generation) return;
428
+
429
+ try {
430
+ await this.#client.keepAliveQuery(this.#uuid, this.#subscriptionId);
431
+ } catch (e) {
432
+ if (this.#disposed || this.#generation !== generation) return;
433
+ console.error('Error in keepalive:', e);
434
+ // try to reinitialize the subscription
435
+ console.log('Reinitializing subscription for query:', this.#query);
436
+ try {
437
+ await this.subscribe();
438
+ console.log('Subscription reinitialized');
439
+ } catch (resubscribeError) {
440
+ console.error('Error during resubscription from keepalive:', resubscribeError);
441
+ // Don't schedule another keepalive on resubscribe failure.
442
+ // Recovery is not lost: the failed subscribe() installed a
443
+ // reconnect listener that retries the full subscribe.
444
+ return;
445
+ }
446
+ // subscribe() succeeded and started its own keepalive loop
447
+ // under a new generation — this loop is done.
448
+ return;
449
+ }
450
+
451
+ // Schedule next keepalive if still the active generation
452
+ if (!this.#disposed && this.#generation === generation) {
453
+ this.#keepaliveTimer = setTimeout(keepaliveLoop, 30000) as unknown as number;
454
+ }
455
+ };
456
+
457
+ this.#keepaliveTimer = setTimeout(keepaliveLoop, 30000) as unknown as number;
458
+ }
459
+
286
460
  /** Internal method to notify all callbacks of a new result */
287
461
  #notifyCallbacks(result: AllInstancesResult) {
288
462
  for (const callback of this.#callbacks) {
@@ -307,10 +481,17 @@ export class QuerySubscriptionProxy {
307
481
  */
308
482
  dispose() {
309
483
  this.#disposed = true;
484
+ // Invalidate any suspended writer so a mid-flight subscribe() or
485
+ // reconnect swap backs out instead of resurrecting state.
486
+ this.#generation++;
310
487
  clearTimeout(this.#keepaliveTimer);
311
488
  if (this.#unsubscribe) {
312
489
  this.#unsubscribe();
313
490
  }
491
+ if (this.#reconnectUnsub) {
492
+ this.#reconnectUnsub();
493
+ this.#reconnectUnsub = undefined;
494
+ }
314
495
  this.#callbacks.clear();
315
496
  if (this.#initTimeoutId) {
316
497
  clearTimeout(this.#initTimeoutId);
@@ -372,6 +553,7 @@ interface Parameter {
372
553
  * });
373
554
  * ```
374
555
  */
556
+
375
557
  export class PerspectiveProxy {
376
558
  /** Unique identifier of this perspective */
377
559
  uuid: string;
@@ -544,8 +726,8 @@ export class PerspectiveProxy {
544
726
  * });
545
727
  * ```
546
728
  */
547
- async get(query: LinkQuery): Promise<LinkExpression[]> {
548
- return await this.#client.queryLinks(this.#handle.uuid, query)
729
+ async get(query: LinkQuery, options?: CallOptions): Promise<LinkExpression[]> {
730
+ return await this.#client.queryLinks(this.#handle.uuid, query, options)
549
731
  }
550
732
 
551
733
  /**
@@ -561,8 +743,74 @@ export class PerspectiveProxy {
561
743
  * @param basePrefix URI namespace for new instance identities, e.g. `soa://ext/`
562
744
  * @param classes local names of the subject classes to extract into; omit for all
563
745
  */
564
- async runInterpretation(transcript: TranscriptTurn[], basePrefix: string, classes?: string[]): Promise<string[]> {
565
- return await this.#client.runInterpretation(this.#handle.uuid, transcript, basePrefix, classes)
746
+ async runInterpretation(
747
+ transcript: TranscriptTurn[],
748
+ basePrefix: string,
749
+ classes?: string[],
750
+ options?: {
751
+ existingScope?: RawScope,
752
+ mintScope?: RawScope,
753
+ /** Report progress while the pass runs — see {@link RunInterpretationObserveOptions}. */
754
+ observe?: RunInterpretationObserveOptions,
755
+ },
756
+ ): Promise<string[]> {
757
+ // Grouped into an options bag rather than continuing the client's positional list.
758
+ // The scopes were already unreachable from here for that reason, and a fourth, fifth and
759
+ // sixth positional parameter would have made `undefined, undefined, { … }` the normal way
760
+ // to ask for the only one of them most callers want.
761
+ return await this.#client.runInterpretation(
762
+ this.#handle.uuid,
763
+ transcript,
764
+ basePrefix,
765
+ classes,
766
+ options?.existingScope,
767
+ options?.mintScope,
768
+ options?.observe,
769
+ )
770
+ }
771
+
772
+ /**
773
+ * Harness-dispatched interpretation pass over this perspective (design v3
774
+ * §6 — the tool-calling counterpart to {@link runInterpretation}). The LLM
775
+ * sees a live per-class tool surface (`{Class}_query`, `{Class}_get`,
776
+ * `{Class}_propose_create`, `{Class}_propose_link_child`, …) and drives
777
+ * the extraction via tool calls; buffered proposals drain through the
778
+ * same overlay gate the single-shot path uses.
779
+ *
780
+ * @param transcript ordered `{ speaker, text }` turns
781
+ * @param basePrefix URI namespace new instance identities are minted under
782
+ * @param maxToolCalls upper bound on tool calls the harness will make in
783
+ * one pass (must be > 0 — use {@link runInterpretation} for the
784
+ * classic single-shot path)
785
+ * @param classes local names of the subject classes to extract into; omit for all
786
+ * @param modelOverride optional model override; omit for the default LLM
787
+ */
788
+ async runInterpretationWithHarness(
789
+ transcript: TranscriptTurn[],
790
+ basePrefix: string,
791
+ maxToolCalls: number,
792
+ classes?: string[],
793
+ modelOverride?: string,
794
+ // Optional live-debug observability. When both `observationId` and
795
+ // `emitDebugEvents` are supplied, every dispatched tool call fires
796
+ // `ToolCall` + `ToolResult` events on the `auto-processor-event`
797
+ // topic keyed by `observationId`. Subscribe with
798
+ // {@link addAutoProcessorEventListener} to render the harness loop
799
+ // live in a UI. Absent = fast headless path (no telemetry cost).
800
+ observationId?: string,
801
+ emitDebugEvents?: boolean,
802
+ ): Promise<string[]> {
803
+ return await this.#client.runInterpretationWithHarness(
804
+ this.#handle.uuid,
805
+ transcript,
806
+ basePrefix,
807
+ maxToolCalls,
808
+ classes,
809
+ modelOverride,
810
+ undefined,
811
+ observationId,
812
+ emitDebugEvents,
813
+ )
566
814
  }
567
815
 
568
816
  /**
@@ -575,6 +823,25 @@ export class PerspectiveProxy {
575
823
  return await this.#client.addAutoProcessor(this.#handle.uuid, config)
576
824
  }
577
825
 
826
+ /**
827
+ * Stop an auto-processor by deleting its config.
828
+ *
829
+ * The registration is data — the watch loop reads the processor set back out of the
830
+ * perspective's graph on every tick — so deleting the config is what stops it, and there is
831
+ * nothing else to unregister. The config is `Shared`, so this stops the processor for the
832
+ * neighbourhood rather than only for this peer.
833
+ *
834
+ * Resolves `true` when there was a processor to remove and `false` when there was not; a
835
+ * processor another peer has already removed is not an error.
836
+ *
837
+ * The processor's `InterpretationRun` nodes stay: they are the record of what it did and the
838
+ * processed-turn cursor, so a processor later registered under the same id resumes where this
839
+ * one left off rather than re-reading every turn.
840
+ */
841
+ async removeAutoProcessor(processorId: string): Promise<boolean> {
842
+ return await this.#client.removeAutoProcessor(this.#handle.uuid, processorId)
843
+ }
844
+
578
845
  /**
579
846
  * Pending interpretation overlays on this perspective — LLM suggestions the
580
847
  * §4 divergence gate staged rather than applied, awaiting human accept/reject.
@@ -606,6 +873,19 @@ export class PerspectiveProxy {
606
873
  return await this.#client.addAutoProcessorEventListener(this.#handle.uuid, cb)
607
874
  }
608
875
 
876
+ /**
877
+ * Subscribe to this perspective's auto-processor neighbourhood-state
878
+ * events — fires when this executor claims / finishes / abandons a
879
+ * batch. Perspective-scoped, so a UI can render "someone is
880
+ * auto-processing this" without receiving the batch payload. See
881
+ * `AutoProcessorNeighbourhoodStateEvent`.
882
+ */
883
+ async addAutoProcessorNeighbourhoodStateListener(
884
+ cb: (event: AutoProcessorNeighbourhoodStateEvent) => void,
885
+ ): Promise<void> {
886
+ return await this.#client.addAutoProcessorNeighbourhoodStateListener(this.#handle.uuid, cb)
887
+ }
888
+
609
889
  /**
610
890
  * Executes a Prolog query against the perspective's knowledge base.
611
891
  * This is a powerful way to find complex patterns in the graph.
@@ -629,30 +909,36 @@ export class PerspectiveProxy {
629
909
  * `);
630
910
  * ```
631
911
  */
632
- async infer(query: string): Promise<any> {
633
- return await this.#client.queryProlog(this.#handle.uuid, query)
912
+ async infer(query: string, options?: CallOptions): Promise<any> {
913
+ return await this.#client.queryProlog(this.#handle.uuid, query, options)
634
914
  }
635
915
 
636
916
  /**
637
917
  * Executes a SPARQL query against the perspective's link cache.
638
918
  * This allows powerful SQL-like queries on the link data stored in SPARQL.
639
- *
919
+ *
640
920
  * **Security Note:** Only read-only queries (SELECT, RETURN, etc.) are permitted.
641
921
  * Mutating operations (DELETE, UPDATE, INSERT, CREATE, DROP, DEFINE, etc.) are
642
922
  * blocked for security reasons. Use the perspective's add/remove methods to modify links.
643
- *
644
- * @param query - SPARQL query string (read-only operations only)
645
- * @returns Query results as parsed JSON
646
- *
647
- * Executes a SPARQL query against the perspective's RDF (Oxigraph) store.
648
923
  *
649
- * @param query - SPARQL query string
924
+ * **Cancellation:** Pass `{ signal }` from an `AbortController` to abort
925
+ * an in-flight query. The executor receives `request.cancel` over the
926
+ * WebSocket and short-circuits the JSON reply. Caveat: Oxigraph itself
927
+ * cannot be interrupted mid-evaluation, so an already-running scan will
928
+ * keep its blocking thread busy until it completes; what's saved is the
929
+ * serialise + network + client-deserialise tax on the result. Aborted
930
+ * calls reject with `DOMException('Aborted', 'AbortError')` — match
931
+ * `fetch()` for handling. Cached results bypass the round-trip entirely
932
+ * and are returned synchronously, ignoring the signal.
933
+ *
934
+ * @param query - SPARQL query string (read-only operations only)
935
+ * @param options - Optional call options (e.g. AbortSignal for cancellation)
650
936
  * @returns Query results as parsed JSON
651
937
  */
652
- async querySparql<T = any>(query: string): Promise<T> {
938
+ async querySparql<T = any>(query: string, options?: CallOptions): Promise<T> {
653
939
  const cached = getCachedResult(this.#handle.uuid, query);
654
940
  if (cached !== undefined) return cached as T;
655
- const result = await this.#client.querySparql(this.#handle.uuid, query);
941
+ const result = await this.#client.querySparql(this.#handle.uuid, query, options);
656
942
  setCachedResult(this.#handle.uuid, query, result);
657
943
  return result as T;
658
944
  }
@@ -668,8 +954,43 @@ export class PerspectiveProxy {
668
954
  * @param queryJson - Structured query as JSON string
669
955
  * @returns Object with `instances` array and `totalCount`
670
956
  */
671
- async modelQuery(className: string, queryJson: string): Promise<{ instances: any[], totalCount: number }> {
672
- return await this.#client.modelQuery(this.#handle.uuid, className, queryJson);
957
+ async modelQuery(className: string, queryJson: string, options?: CallOptions): Promise<{ instances: any[], totalCount: number }> {
958
+ return await this.#client.modelQuery(this.#handle.uuid, className, queryJson, options);
959
+ }
960
+
961
+ /** Resolve each URI to the names of every subject class it is an instance of.
962
+ *
963
+ * The counterpart of {@link isSubjectInstance}, which asks the same question
964
+ * one class at a time. Without this, finding the class of an arbitrary URI
965
+ * meant looping over every registered class — a round trip each — and doing
966
+ * it again for every URI.
967
+ *
968
+ * Class membership in AD4M is structural — a URI belongs to a class when it
969
+ * carries that class's flags and required properties — so membership is **not
970
+ * exclusive**: an instance conforms to its parent classes, and to any
971
+ * unrelated class whose required set happens to be a subset of what it
972
+ * carries. Every match is returned.
973
+ *
974
+ * The list is ordered **most specific first**, meaning by the number of
975
+ * triples the class requires — a subclass requires everything its parent does
976
+ * and more — with ties broken alphabetically so that every peer answers
977
+ * identically. A caller that can only act on one class should take
978
+ * `classes[0]`, but that head is only a heuristic: it is arbitrary between two
979
+ * unrelated classes requiring the same number of triples, which is exactly
980
+ * the case the full list exists to expose.
981
+ *
982
+ * A URI is **absent from the result** when no *registered* class matched it.
983
+ * That covers two situations, and nothing here separates them: the URI may
984
+ * not be a subject instance at all, or it may be an instance of a class this
985
+ * perspective has not registered. Absence is used rather than an empty list
986
+ * because an empty list would claim the stronger thing — that the URI belongs
987
+ * to no class — which this cannot know.
988
+ *
989
+ * @param uris The expression URIs to classify.
990
+ */
991
+ async subjectClassesOf(uris: string[]): Promise<Record<string, string[]>> {
992
+ if (uris.length === 0) return {};
993
+ return await this.#client.subjectClassesOf(this.#handle.uuid, uris);
673
994
  }
674
995
 
675
996
  /**
@@ -1027,108 +1348,45 @@ export class PerspectiveProxy {
1027
1348
  });
1028
1349
  }
1029
1350
 
1030
- /** Returns all Social DNA flows that can be started from the given expression */
1351
+ /**
1352
+ * Returns all Social DNA flows that can be started from the given expression.
1353
+ *
1354
+ * Post-`flowable` retirement: a flow is a candidate iff its `inputTypes`
1355
+ * declaration is compatible with the expression. Matching rules:
1356
+ * - Empty `inputTypes` or one containing the `"any"` wildcard → always
1357
+ * matches (same behaviour as the legacy `flowable === "any"` case).
1358
+ * - Otherwise, at least one of the expression's registered subject-class
1359
+ * URIs (resolved via {@link subjectClassesOf}) must appear in
1360
+ * `inputTypes`. This is the concrete-type match the design doc's §5
1361
+ * spawn engine calls for; without it, a flow declaring
1362
+ * `inputTypes: ["Task"]` was previously *never* returned by
1363
+ * `availableFlows("some-task-uri")` — the entire point of typed
1364
+ * flows was silently unreachable (James PR #929 J#3).
1365
+ *
1366
+ * The expression is classified against the perspective's registered
1367
+ * classes only. An expression whose class is not registered on this
1368
+ * perspective matches no typed flow (absence, not falsehood — same
1369
+ * discipline as {@link subjectClassesOf}); typed flows requiring
1370
+ * unknown classes are still returned to their untyped-caller peers.
1371
+ */
1031
1372
  async availableFlows(exprAddr: string): Promise<string[]> {
1032
1373
  const allFlowNames = await this.sdnaFlows();
1374
+ if (allFlowNames.length === 0) return [];
1375
+ const classesOf = await this.subjectClassesOf([exprAddr]);
1376
+ const exprClasses = classesOf[exprAddr] ?? [];
1033
1377
  const available: string[] = [];
1034
1378
  for (const name of allFlowNames) {
1035
1379
  const flow = await this.getFlow(name);
1036
1380
  if (!flow) continue;
1037
- if (flow.flowable === "any") {
1381
+ if (flow.inputTypes.length === 0 || flow.inputTypes.includes("any")) {
1038
1382
  available.push(name);
1039
- } else {
1040
- // Check if the expression matches the flowable link pattern
1041
- const pattern = flow.flowable as LinkPattern;
1042
- const source = pattern.source || exprAddr;
1043
- const links = await this.get(new LinkQuery({
1044
- source,
1045
- predicate: pattern.predicate,
1046
- target: pattern.target
1047
- }));
1048
- if (links.length > 0) {
1049
- available.push(name);
1050
- }
1383
+ continue;
1051
1384
  }
1052
- }
1053
- return available;
1054
- }
1055
-
1056
- /** Starts the Social DNA flow @param flowName on the expression @param exprAddr */
1057
- async startFlow(flowName: string, exprAddr: string) {
1058
- const flow = await this.getFlow(flowName);
1059
- if (!flow) throw `Flow "${flowName}" not found`;
1060
- if (flow.startAction.length === 0) throw `Flow "${flowName}" has no start action`;
1061
- await this.executeAction(flow.startAction, exprAddr, undefined)
1062
- }
1063
-
1064
- /** Returns all expressions in the given state of given Social DNA flow */
1065
- async expressionsInFlowState(flowName: string, flowState: number): Promise<string[]> {
1066
- const flow = await this.getFlow(flowName);
1067
- if (!flow) return [];
1068
- // Find the state with the matching value
1069
- const state = flow.states.find(s => s.value === flowState);
1070
- if (!state) return [];
1071
- // Query for expressions matching this state's check pattern
1072
- const pattern = state.stateCheck;
1073
- const links = await this.get(new LinkQuery({
1074
- predicate: pattern.predicate,
1075
- target: pattern.target
1076
- }));
1077
- // Return the sources (expression addresses) - use source if pattern has no explicit source
1078
- return links.map(l => pattern.source ? l.data.target : l.data.source);
1079
- }
1080
-
1081
- /** Returns the given expression's flow state with regard to given Social DNA flow */
1082
- async flowState(flowName: string, exprAddr: string): Promise<number> {
1083
- const flow = await this.getFlow(flowName);
1084
- if (!flow) throw `Flow "${flowName}" not found`;
1085
- // Check each state to find which one the expression is in
1086
- for (const state of flow.states) {
1087
- const pattern = state.stateCheck;
1088
- const source = pattern.source || exprAddr;
1089
- const links = await this.get(new LinkQuery({
1090
- source,
1091
- predicate: pattern.predicate,
1092
- target: pattern.target
1093
- }));
1094
- if (links.length > 0) return state.value;
1095
- }
1096
- throw `Expression "${exprAddr}" is not in any state of flow "${flowName}"`;
1097
- }
1098
-
1099
- /** Returns available action names, with regard to Social DNA flow and expression's flow state */
1100
- async flowActions(flowName: string, exprAddr: string): Promise<string[]> {
1101
- const flow = await this.getFlow(flowName);
1102
- if (!flow) return [];
1103
- // Determine current state
1104
- let currentStateName: string | null = null;
1105
- for (const state of flow.states) {
1106
- const pattern = state.stateCheck;
1107
- const source = pattern.source || exprAddr;
1108
- const links = await this.get(new LinkQuery({
1109
- source,
1110
- predicate: pattern.predicate,
1111
- target: pattern.target
1112
- }));
1113
- if (links.length > 0) {
1114
- currentStateName = state.name;
1115
- break;
1385
+ if (exprClasses.some(cls => flow.inputTypes.includes(cls))) {
1386
+ available.push(name);
1116
1387
  }
1117
1388
  }
1118
- if (!currentStateName) return [];
1119
- // Return transitions available from current state
1120
- return flow.transitions
1121
- .filter(t => t.fromState === currentStateName)
1122
- .map(t => t.actionName);
1123
- }
1124
-
1125
- /** Runs given Social DNA flow action */
1126
- async runFlowAction(flowName: string, exprAddr: string, actionName: string) {
1127
- const flow = await this.getFlow(flowName);
1128
- if (!flow) throw `Flow "${flowName}" not found`;
1129
- const transition = flow.transitions.find(t => t.actionName === actionName);
1130
- if (!transition) throw `Action "${actionName}" not found in flow "${flowName}"`;
1131
- await this.executeAction(transition.actions, exprAddr, undefined)
1389
+ return available;
1132
1390
  }
1133
1391
 
1134
1392
  /** Returns the perspective's Social DNA code
@@ -1331,122 +1589,47 @@ export class PerspectiveProxy {
1331
1589
  }
1332
1590
 
1333
1591
  /**
1334
- * Retrieve a SHACL shape by name from this Perspective
1592
+ * Retrieve a SHACL shape by name from this Perspective (one RPC call).
1593
+ * The executor resolves the full shape (including property sub-shapes)
1594
+ * in-process and returns link triples for client-side reconstruction.
1335
1595
  */
1336
1596
  async getShacl(name: string): Promise<SHACLShape | null> {
1337
- // Find the shape URI from the name mapping
1338
- const nameMapping = Literal.fromUrl(`literal:string:shacl://${name}`);
1339
- const shapeUriLinks = await this.get(new LinkQuery({
1340
- source: nameMapping.toUrl(),
1341
- predicate: "ad4m://shacl_shape_uri"
1342
- }));
1343
-
1344
- if (shapeUriLinks.length === 0) {
1345
- return null;
1346
- }
1347
-
1348
- const shapeUri = shapeUriLinks[0].data.target;
1349
-
1350
- // First get property shape URIs so we can query everything in one go
1351
- const propertyLinks = await this.get(new LinkQuery({
1352
- source: shapeUri,
1353
- predicate: "sh://property"
1354
- }));
1355
-
1356
- // Fetch all links from the shape and its property shapes. These reads are
1357
- // independent of each other, so fire them concurrently rather than one RPC
1358
- // round trip at a time — over a remote (non-loopback) connection, a shape with
1359
- // a dozen properties otherwise pays a dozen sequential round trips just to load.
1360
- const sourceUris = [shapeUri, ...propertyLinks.map(l => l.data.target)];
1361
- const linksByUri = await Promise.all(sourceUris.map(uri => this.get(new LinkQuery({ source: uri }))));
1362
- // Dedupe by (source, predicate, target): a perspective that's accumulated duplicate
1363
- // SDNA links (e.g. from repeated registration attempts, or executor-side sync bugs)
1364
- // would otherwise feed the same triple into SHACLShape.fromLinks more than once —
1365
- // harmless for scalar fields like targetClass (first match wins) but can surface as
1366
- // visibly duplicated properties for repeated sh://property links. Cheap: this is an
1367
- // in-memory pass over data already fetched, no extra round trips.
1368
- const seenLinks = new Set<string>();
1369
- const allLinks: Array<{source: string, predicate: string, target: string}> = [];
1370
- for (const links of linksByUri) {
1371
- for (const l of links) {
1372
- const key = `${l.data.source} ${l.data.predicate} ${l.data.target}`;
1373
- if (seenLinks.has(key)) continue;
1374
- seenLinks.add(key);
1375
- allLinks.push({
1376
- source: l.data.source,
1377
- predicate: l.data.predicate,
1378
- target: l.data.target
1379
- });
1380
- }
1381
- }
1382
-
1383
- const shapeLinks = allLinks;
1384
-
1385
- return SHACLShape.fromLinks(shapeLinks, shapeUri);
1597
+ const result = await this.#client.getShacl(this.#handle.uuid, name);
1598
+ if (!result) return null;
1599
+ return SHACLShape.fromLinks(result.links as any, result.shapeUri);
1386
1600
  }
1387
1601
 
1388
1602
  /**
1389
- * List the names of every SHACL shape stored in this Perspective, without fetching
1390
- * each shape's full definition (properties, target class, etc.) — just the cheap
1391
- * `ad4m://has_shacl` enumeration, one round trip regardless of how many shapes exist.
1392
- * Use this to check which shapes are actually worth resolving via `getShacl()` before
1393
- * paying for each one's full (multi-round-trip) fetch.
1603
+ * List the names of every SHACL shape stored in this Perspective (one RPC call).
1394
1604
  */
1395
1605
  async getShaclNames(): Promise<string[]> {
1396
- const nameLinks = await this.get(new LinkQuery({
1397
- source: "ad4m://self",
1398
- predicate: "ad4m://has_shacl"
1399
- }));
1400
- // Dedupe: a perspective with duplicate `has_shacl` links (see the dedup note in
1401
- // getShacl()) would otherwise report the same name more than once, causing callers
1402
- // to redundantly resolve (or redundantly disambiguate) it multiple times.
1403
- const names = nameLinks.map((nameLink) => {
1404
- const name = Literal.fromUrl(nameLink.data.target).get() as string;
1405
- return name.replace('shacl://', '');
1406
- });
1407
- return [...new Set(names)];
1606
+ return this.#client.getShaclNames(this.#handle.uuid);
1408
1607
  }
1409
1608
 
1410
1609
  /**
1411
- * Resolve just a shape's `sh:targetClass` by name, without fetching its properties —
1412
- * two round trips (name → shapeUri, then shapeUri's own direct triples) instead of
1413
- * `getShacl()`'s full walk (which also fetches every property sub-shape). Use this to
1414
- * disambiguate a shape name that collides with another app's `@Model({ name })` string
1415
- * (the bare `shacl://{name}` mapping ad4m-core uses is namespace-blind — see
1416
- * `getShaclNames()` callers for why that matters) before paying for a full fetch.
1610
+ * Resolve a shape's `sh:targetClass` by name (one RPC call).
1611
+ *
1612
+ * `PerspectiveClient.getShaclTargetClass` now returns `undefined` on
1613
+ * "not found" already (see review r3897752023 — the null→undefined
1614
+ * coercion used to happen here and be duplicated one layer down),
1615
+ * so this method is a pure passthrough.
1417
1616
  */
1418
1617
  async getShaclTargetClass(name: string): Promise<string | undefined> {
1419
- const nameMapping = Literal.fromUrl(`literal:string:shacl://${name}`);
1420
- const shapeUriLinks = await this.get(new LinkQuery({
1421
- source: nameMapping.toUrl(),
1422
- predicate: "ad4m://shacl_shape_uri"
1423
- }));
1424
- if (shapeUriLinks.length === 0) {
1425
- return undefined;
1426
- }
1427
- const shapeUri = shapeUriLinks[0].data.target;
1428
-
1429
- const shapeOwnLinks = await this.get(new LinkQuery({ source: shapeUri }));
1430
- return shapeOwnLinks.find(l => l.data.predicate === "sh://targetClass")?.data.target;
1618
+ return this.#client.getShaclTargetClass(this.#handle.uuid, name);
1431
1619
  }
1432
1620
 
1433
1621
  /**
1434
- * Get all SHACL shapes stored in this Perspective
1622
+ * Get all SHACL shapes stored in this Perspective (one RPC call).
1623
+ * The executor resolves all shapes in-process and returns them in bulk.
1435
1624
  */
1436
1625
  async getAllShacl(): Promise<Array<{name: string, shape: SHACLShape}>> {
1437
- const shapeNames = await this.getShaclNames();
1438
-
1439
- // Each shape is fetched independently of the others — resolve them concurrently.
1440
- // Sequentially awaiting getShacl() per shape means a perspective with N SDNA
1441
- // models pays N times getShacl()'s own multi-round-trip cost one after another;
1442
- // over a remote connection with real per-call latency that compounds into the
1443
- // dominant cost of switching into a perspective at all.
1444
- const results = await Promise.all(shapeNames.map(async (shapeName) => {
1445
- const shape = await this.getShacl(shapeName);
1446
- return shape ? { name: shapeName, shape } : null;
1447
- }));
1448
-
1449
- return results.filter((s): s is { name: string, shape: SHACLShape } => s !== null);
1626
+ const entries = await this.#client.getAllShacl(this.#handle.uuid);
1627
+ return entries
1628
+ .map(({ name, shapeUri, links }) => {
1629
+ const shape = SHACLShape.fromLinks(links as any, shapeUri);
1630
+ return shape ? { name, shape } : null;
1631
+ })
1632
+ .filter((s): s is { name: string; shape: SHACLShape } => s !== null);
1450
1633
  }
1451
1634
 
1452
1635
  /**
@@ -1461,29 +1644,27 @@ export class PerspectiveProxy {
1461
1644
  * @example
1462
1645
  * ```typescript
1463
1646
  * import { SHACLFlow } from '@coasys/ad4m';
1464
- *
1465
- * const todoFlow = new SHACLFlow('TODO', 'todo://');
1466
- * todoFlow.flowable = 'any';
1467
- *
1468
- * // Define states
1469
- * todoFlow.addState({ name: 'ready', value: 0, stateCheck: { predicate: 'todo://state', target: 'todo://ready' }});
1470
- * todoFlow.addState({ name: 'done', value: 1, stateCheck: { predicate: 'todo://state', target: 'todo://done' }});
1471
- *
1472
- * // Define start action
1473
- * todoFlow.startAction = [{ action: 'addLink', source: 'this', predicate: 'todo://state', target: 'todo://ready' }];
1474
- *
1475
- * // Define transitions
1476
- * todoFlow.addTransition({
1477
- * actionName: 'Complete',
1478
- * fromState: 'ready',
1479
- * toState: 'done',
1480
- * actions: [
1481
- * { action: 'addLink', source: 'this', predicate: 'todo://state', target: 'todo://done' },
1482
- * { action: 'removeLink', source: 'this', predicate: 'todo://state', target: 'todo://ready' }
1483
- * ]
1484
- * });
1485
- *
1486
- * await perspective.addFlow('TODO', todoFlow);
1647
+ *
1648
+ * const deliveryFlow = new SHACLFlow('Delivery', 'delivery://');
1649
+ * deliveryFlow.inputTypes = ['Task'];
1650
+ * deliveryFlow.interpretationHint =
1651
+ * 'Advance a Task through delivery: Identified → Scoped → InProgress → Review → Done.';
1652
+ *
1653
+ * deliveryFlow.addState({ name: 'Identified', value: 0 });
1654
+ * deliveryFlow.addState({ name: 'Scoped', value: 1 });
1655
+ * deliveryFlow.addState({ name: 'InProgress', value: 2 });
1656
+ * deliveryFlow.addState({ name: 'Review', value: 3 });
1657
+ * deliveryFlow.addState({ name: 'Done', value: 4 });
1658
+ *
1659
+ * deliveryFlow.addTransition({ actionName: 'Scope', fromState: 'Identified', toState: 'Scoped', actions: [] });
1660
+ * deliveryFlow.addTransition({ actionName: 'Start', fromState: 'Scoped', toState: 'InProgress', actions: [] });
1661
+ * deliveryFlow.addTransition({ actionName: 'Submit', fromState: 'InProgress', toState: 'Review', actions: [] });
1662
+ * deliveryFlow.addTransition({ actionName: 'Accept', fromState: 'Review', toState: 'Done', actions: [] });
1663
+ *
1664
+ * // Optional: n distinct DIDs must co-sign a proposal before it fires.
1665
+ * deliveryFlow.consensusRule = { n: 2 };
1666
+ *
1667
+ * await perspective.addFlow('Delivery', deliveryFlow);
1487
1668
  * ```
1488
1669
  */
1489
1670
  async addFlow(name: string, flow: SHACLFlow): Promise<void> {
@@ -1522,36 +1703,39 @@ export class PerspectiveProxy {
1522
1703
  */
1523
1704
  async getFlow(name: string): Promise<SHACLFlow | null> {
1524
1705
  const flowNameLiteral = Literal.from(name).toUrl();
1525
-
1706
+
1526
1707
  // Find flow URI from name mapping
1527
1708
  const flowUriLinks = await this.get(new LinkQuery({
1528
1709
  source: flowNameLiteral,
1529
1710
  predicate: "ad4m://flow_uri"
1530
1711
  }));
1531
-
1712
+
1532
1713
  if (flowUriLinks.length === 0) {
1533
1714
  return null;
1534
1715
  }
1535
-
1716
+
1536
1717
  const flowUri = flowUriLinks[0].data.target;
1537
- // Compute alternate prefix for state/transition URIs
1538
- const alternatePrefix = flowUri.endsWith('Flow')
1539
- ? flowUri.slice(0, -4) + '.'
1540
- : flowUri + '.';
1541
-
1542
- // Fetch flow links using SPARQL to match flowUri source OR alternatePrefix sources
1543
- const sparqlQuery = `SELECT ?s ?p ?o WHERE {
1544
- ?s ?p ?o .
1545
- FILTER(?s = <${flowUri}> || STRSTARTS(STR(?s), "${alternatePrefix}"))
1546
- }`;
1547
- const sparqlResult = await this.querySparql(sparqlQuery);
1548
-
1549
- const flowLinks = (sparqlResult || []).map((r: any) => ({
1550
- source: r.s,
1551
- predicate: r.p,
1552
- target: r.o
1718
+
1719
+ // Fetch flow-level links (hasState, hasTransition, startAction, inputTypes/outputTypes/…)
1720
+ const flowLevelLinks = await this.get(new LinkQuery({ source: flowUri }));
1721
+
1722
+ // Collect state and transition URIs, then fetch their child links
1723
+ const childUris = flowLevelLinks
1724
+ .filter(l => l.data.predicate === "ad4m://hasState"
1725
+ || l.data.predicate === "ad4m://hasTransition")
1726
+ .map(l => l.data.target);
1727
+ const childResults = await Promise.all(
1728
+ childUris.map(uri => this.get(new LinkQuery({ source: uri })))
1729
+ );
1730
+
1731
+ // Flatten into the {source, predicate, target} shape fromLinks expects
1732
+ const allExprs = [...flowLevelLinks, ...childResults.flat()];
1733
+ const flowLinks = allExprs.map(l => ({
1734
+ source: l.data.source,
1735
+ predicate: l.data.predicate,
1736
+ target: l.data.target
1553
1737
  }));
1554
-
1738
+
1555
1739
  return SHACLFlow.fromLinks(flowLinks, flowUri);
1556
1740
  }
1557
1741
 
@@ -1604,7 +1788,9 @@ export class PerspectiveProxy {
1604
1788
  * with the properties of the subject class.
1605
1789
  * @param exprAddr The address of the expression to be turned into a subject instance
1606
1790
  * @param initialValues Optional initial values for properties. If provided, these will be
1607
- * merged with constructor actions for better performance.
1791
+ * merged with constructor actions for better performance. A collection property accepts
1792
+ * an array value and stores one entry per element; scalar properties store arrays/objects
1793
+ * as a single JSON value.
1608
1794
  * @param batchId Optional batch ID for grouping operations. If provided, returns the expression address
1609
1795
  * instead of the subject proxy since the subject won't exist until the batch is committed.
1610
1796
  * @returns A proxy object for the created subject, or just the expression address if in batch mode