@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
@@ -18,6 +18,128 @@ export interface LinkPattern {
18
18
  target: string;
19
19
  }
20
20
 
21
+ /**
22
+ * Per-property condition for a `ModelQuery`. String / number / boolean
23
+ * shorthands compile to an equality match; the object forms are the full
24
+ * shape a `ModelQuery` engine consumer will evaluate against a class
25
+ * instance's decoded property value.
26
+ *
27
+ * Only the shorthand + `equals` / `in` / `exists` / `matches` operators are
28
+ * declared in v1 (see design doc §4.1). More operators can land as
29
+ * additional variants without a schema break.
30
+ */
31
+ export type PropertyCondition =
32
+ | string
33
+ | number
34
+ | boolean
35
+ | { equals: unknown }
36
+ | { in: unknown[] }
37
+ | { exists: true }
38
+ | { matches: string };
39
+
40
+ /**
41
+ * A model-level query — the shape a flow's `requires` guard evaluates
42
+ * against the perspective's current class-instance graph. Deliberately
43
+ * higher-level than raw links so guards talk about subject classes, not
44
+ * the underlying triples.
45
+ *
46
+ * See design doc §3 principle 2 ("Guards talk about models, not raw graph")
47
+ * and §4.1 for the full field spec. Template variables allowed inside
48
+ * `where` string values: `$flow.base`, `$flow.uri` (alias:
49
+ * `$flow.instance`), `$did` — the engine substitutes at evaluation time.
50
+ */
51
+ export interface ModelQuery {
52
+ /** Subject-class URI to search for. */
53
+ className: string;
54
+ /**
55
+ * Per-property conditions (all must match — AND semantics inside one
56
+ * ModelQuery, same as AND semantics across an array of ModelQueries).
57
+ */
58
+ where?: { [prop: string]: PropertyCondition | string };
59
+ /**
60
+ * Cardinality constraint on matching instances. Default `{ min: 1 }` —
61
+ * at least one match required to satisfy the guard.
62
+ */
63
+ count?: { min?: number; max?: number };
64
+ /**
65
+ * Scope the query to instances linked from a flow anchor. The anchor
66
+ * (base subject or flow instance URI) is the **source** of the link and
67
+ * the matched item is the **target**: `linkedTo: "base"` finds items
68
+ * where the base subject links TO them via the default predicate
69
+ * `ad4m://has_child`.
70
+ *
71
+ * `"base"` / `"flow"` use `ad4m://has_child`; the object form
72
+ * `{ via, to }` names a custom predicate (e.g.
73
+ * `{ via: "ns://about", to: "flow" }`).
74
+ *
75
+ * For the reverse direction (matched instance → anchor), use
76
+ * `where: { about: "$flow.base" }` instead — `linkedTo` cannot
77
+ * express that direction.
78
+ */
79
+ linkedTo?: "flow" | "base" | { via: string; to: "flow" | "base" };
80
+ /**
81
+ * When this query is used as a `ConsensusRule.fromRole`, names the
82
+ * property on the matched instance that carries a DID. Design doc §7.2
83
+ * Shape 1 (instance-carries-DID): engine runs the query, then extracts
84
+ * `didProperty` from each result to build the eligible-DID set.
85
+ *
86
+ * Shape 2 (instance-is-per-DID, using `$did` templating in `where`)
87
+ * omits `didProperty` — the engine iterates candidate DIDs and treats
88
+ * a non-empty result set as "this DID matches."
89
+ *
90
+ * Ignored when the query is used as a state guard (`requires`) or
91
+ * background `context`.
92
+ */
93
+ didProperty?: string;
94
+ /**
95
+ * OR-compose a role expression across multiple ModelQueries. Semantics:
96
+ * a DID counts if it appears in the result of ANY branch (design §7.3
97
+ * multi-role hybrid example — "either reviewer OR admin"). Branches
98
+ * can carry their own `didProperty` / `where`, but NOT `linkedTo`
99
+ * (which must be on the outer query — `linkedTo` on a branch is
100
+ * rejected at translation time).
101
+ *
102
+ * Every branch must use the same `className` as the outer query and
103
+ * cannot declare its own `count` — the outer query's class and
104
+ * cardinality apply to the combined result set.
105
+ *
106
+ * A ModelQuery with a non-empty `or` array acts as a composition node;
107
+ * its own `className` / `where` etc. still count as an additional
108
+ * branch (union with the array). Empty or unset = no composition.
109
+ *
110
+ * Intentionally scoped to `or` for v1 — `and` / `not` fall out of the
111
+ * same mechanism and can land later without a schema break (design
112
+ * §7.4). Ignored when the query is used as a state guard or context.
113
+ */
114
+ or?: ModelQuery[];
115
+ }
116
+
117
+ /**
118
+ * Consensus rule for a flow-state transition (or a top-level zero-state
119
+ * flow's completion). Distinct DID counting with optional role
120
+ * restriction.
121
+ *
122
+ * Design doc §7:
123
+ * - `{ n: 1 }` — any agent's proposal advances (default).
124
+ * - `{ n: 2 }` — two distinct agents must agree.
125
+ * - `{ n, fromRole }` — only agents matching the role query count.
126
+ *
127
+ * `fromRole` reuses `ModelQuery` (design §7.2) so role definitions live
128
+ * entirely in the ontology — communities can invent roles like
129
+ * "Reviewer" / "Guardian" without any code change.
130
+ */
131
+ export interface ConsensusRule {
132
+ /** Required count of distinct qualifying DIDs. */
133
+ n: number;
134
+ /**
135
+ * Optional role restriction. When set, only DIDs returned by the role
136
+ * query are counted. Two evaluation shapes (design §7.2):
137
+ * Shape 1 — `didProperty` present: run once, extract DIDs from matches.
138
+ * Shape 2 — `$did` templated in `where`: run per candidate.
139
+ */
140
+ fromRole?: ModelQuery;
141
+ }
142
+
21
143
  /**
22
144
  * Flow State definition
23
145
  * Represents a single state in the flow state machine
@@ -27,8 +149,97 @@ export interface FlowState {
27
149
  name: string;
28
150
  /** Numeric state value for ordering (e.g., 0, 0.5, 1) */
29
151
  value: number;
30
- /** Link pattern that indicates this state */
31
- stateCheck: LinkPattern;
152
+ /**
153
+ * Natural-language description of what puts a flow instance IN this state.
154
+ * Used by AI-driven state suggestion (`suggestFlowState`) — the same
155
+ * pattern subject classes use for `interpretationHint`. When set, the LLM
156
+ * reads it alongside conversation content to suggest transitions.
157
+ *
158
+ * Example (Deliberation Flow, "Tension" state):
159
+ * "Participants have voiced opposing views or objections — there is a
160
+ * clear disagreement or unresolved conflict on the table."
161
+ */
162
+ interpretationHint?: string;
163
+ /**
164
+ * Model-level guard: the state is satisfied when every ModelQuery in
165
+ * the array returns at least one match on committed graph state
166
+ * (overlays do NOT count as evidence — design §3 principle 5).
167
+ *
168
+ * Array semantics: AND — every entry must match. Empty / unset =
169
+ * no model-level guard.
170
+ *
171
+ * Design doc §4.1: "an array of queries, ALL must match; each query's
172
+ * matches become evidence."
173
+ */
174
+ requires?: ModelQuery[];
175
+ /**
176
+ * Optional English hint for a targeted LLM confirmation before the
177
+ * engine declares the state entered. Distinct from
178
+ * `interpretationHint`, which frames the state semantically for the
179
+ * up-front extraction pass — `semanticCheck` is the "am I still
180
+ * confident?" pass the engine runs after `requires` matches, for
181
+ * states where structural presence isn't enough (e.g. tension
182
+ * resolution).
183
+ *
184
+ * Design doc §5 covers the LLM confirmation pass shape. Unset = no
185
+ * confirmation, `requires` matches directly imply state entered.
186
+ */
187
+ semanticCheck?: string;
188
+ /**
189
+ * Per-state consensus rule override. When present, transitions INTO
190
+ * this state require the specified number of distinct qualifying DIDs
191
+ * (see `ConsensusRule`). Overrides the flow-level `consensusRule` if
192
+ * both are set; when neither is set, the runtime engine's default of
193
+ * `{ n: 1 }` applies (any single agent's action fires the transition).
194
+ *
195
+ * Design doc §4.1 (v3) — per-state override enables mixed-consensus
196
+ * flows where e.g. "Perspective" states need only one voice but the
197
+ * "Resolution" state requires a quorum.
198
+ */
199
+ consensusRule?: ConsensusRule;
200
+ }
201
+
202
+ /**
203
+ * Runtime shape check for a decoded `ModelQuery`. Deserialization paths use
204
+ * this to guard against malformed guard arrays leaking into flow metadata
205
+ * (an untyped `Array.isArray` would happily accept `[null]` or `[{}]`).
206
+ * Only the mandatory `className: string` field is enforced — richer
207
+ * validation stays with the runtime engine that will actually execute the
208
+ * query.
209
+ */
210
+ function isModelQueryShape(v: unknown): v is ModelQuery {
211
+ if (
212
+ typeof v !== "object" ||
213
+ v === null ||
214
+ typeof (v as { className?: unknown }).className !== "string" ||
215
+ (v as { className: string }).className.length === 0
216
+ ) {
217
+ return false;
218
+ }
219
+ const or = (v as { or?: unknown }).or;
220
+ if (or !== undefined) {
221
+ if (!Array.isArray(or) || !or.every(isModelQueryShape)) return false;
222
+ }
223
+ return true;
224
+ }
225
+
226
+ /**
227
+ * Runtime shape check for a decoded `ConsensusRule`. Enforces the one
228
+ * mandatory field (`n: number` with a sane range) and, when `fromRole`
229
+ * is present, that it's a valid ModelQuery. A malformed literal (e.g.
230
+ * `{ n: "many" }` or `{ n: 1, fromRole: null }`) leaves the field unset
231
+ * rather than becoming corrupt flow metadata that downstream engines
232
+ * would trip over.
233
+ */
234
+ function isConsensusRuleShape(v: unknown): v is ConsensusRule {
235
+ if (typeof v !== "object" || v === null) return false;
236
+ const n = (v as { n?: unknown }).n;
237
+ if (typeof n !== "number" || !Number.isFinite(n) || n < 1 || !Number.isInteger(n)) {
238
+ return false;
239
+ }
240
+ const fromRole = (v as { fromRole?: unknown }).fromRole;
241
+ if (fromRole !== undefined && !isModelQueryShape(fromRole)) return false;
242
+ return true;
32
243
  }
33
244
 
34
245
  /**
@@ -46,84 +257,139 @@ export interface FlowTransition {
46
257
  actions: AD4MAction[];
47
258
  }
48
259
 
49
- /**
50
- * Flowable condition - determines which expressions can enter this flow
51
- * "any" means all expressions can start this flow
52
- * Otherwise, a link pattern to check
53
- */
54
- export type FlowableCondition = "any" | LinkPattern;
55
-
56
260
  /**
57
261
  * SHACL Flow - represents a state machine for AD4M expressions
58
- *
262
+ *
59
263
  * Flows define:
60
- * - Which expressions can enter the flow (flowable condition)
61
- * - What states exist and how to detect them (via link patterns)
62
- * - How to transition between states (via actions)
63
- *
264
+ * - Which expressions can enter the flow (via `inputTypes`)
265
+ * - What states exist and their per-state guards (via `requires`)
266
+ * - How to transition between states (via transitions + consensus rules)
267
+ *
268
+ * State lives on the on-graph `FlowInstanceRecord.currentState` and is
269
+ * read/written through the `FlowInstance` wrapper class
270
+ * ({@link FlowInstance.start} / {@link FlowInstance.findAll}) — see design
271
+ * doc §4.3/§5.
272
+ *
64
273
  * @example
65
274
  * ```typescript
66
275
  * const todoFlow = new SHACLFlow('todo://TODO', 'todo://');
67
- *
276
+ *
68
277
  * // Any expression can become a TODO
69
- * todoFlow.flowable = 'any';
70
- *
71
- * // Define states
72
- * todoFlow.addState({
73
- * name: 'ready',
74
- * value: 0,
75
- * stateCheck: { predicate: 'todo://state', target: 'todo://ready' }
76
- * });
77
- * todoFlow.addState({
78
- * name: 'doing',
79
- * value: 0.5,
80
- * stateCheck: { predicate: 'todo://state', target: 'todo://doing' }
81
- * });
82
- * todoFlow.addState({
83
- * name: 'done',
84
- * value: 1,
85
- * stateCheck: { predicate: 'todo://state', target: 'todo://done' }
86
- * });
87
- *
88
- * // Define start action
89
- * todoFlow.startAction = [{
90
- * action: 'addLink',
91
- * source: 'this',
92
- * predicate: 'todo://state',
93
- * target: 'todo://ready'
94
- * }];
95
- *
96
- * // Define transitions
278
+ * todoFlow.inputTypes = ['any'];
279
+ *
280
+ * todoFlow.addState({ name: 'ready', value: 0 });
281
+ * todoFlow.addState({ name: 'doing', value: 0.5 });
282
+ * todoFlow.addState({ name: 'done', value: 1 });
283
+ *
97
284
  * todoFlow.addTransition({
98
285
  * actionName: 'Start',
99
286
  * fromState: 'ready',
100
287
  * toState: 'doing',
101
- * actions: [
102
- * { action: 'addLink', source: 'this', predicate: 'todo://state', target: 'todo://doing' },
103
- * { action: 'removeLink', source: 'this', predicate: 'todo://state', target: 'todo://ready' }
104
- * ]
288
+ * actions: [],
105
289
  * });
106
- *
107
- * // Store in perspective
290
+ *
291
+ * // Register on the perspective and mint an instance on a subject.
108
292
  * await perspective.addFlow('TODO', todoFlow);
293
+ * const instance = await FlowInstance.start(perspective, 'TODO', 'expr://123');
109
294
  * ```
110
295
  */
111
296
  export class SHACLFlow {
112
297
  /** Flow name (e.g., "TODO") */
113
298
  public name: string;
114
-
299
+
115
300
  /** Namespace for generated URIs */
116
301
  public namespace: string;
117
-
118
- /** Condition for which expressions can start this flow */
119
- public flowable: FlowableCondition = "any";
120
-
121
- /** Actions to execute when starting the flow */
122
- public startAction: AD4MAction[] = [];
123
-
124
- /** States in this flow */
302
+
303
+ /**
304
+ * Top-level natural-language description of what the flow is about — used
305
+ * by AI-driven state suggestion (`suggestFlowState`) to frame the state
306
+ * hints. Optional; states' own `interpretationHint`s are what actually
307
+ * discriminate. Example (Deliberation Flow):
308
+ * "Tracks a group deliberation from an initial proposal to a shared
309
+ * understanding — through voicing perspectives, surfacing tension, and
310
+ * finding overlap."
311
+ */
312
+ public interpretationHint?: string;
313
+
314
+ /**
315
+ * Subject-class URIs the flow accepts as its base expression.
316
+ *
317
+ * Design doc §4.1: a flow's *typed input*. When an
318
+ * expression whose class matches any URI in this array enters scope,
319
+ * the flow-spawn engine considers it a candidate base. Superseded
320
+ * the older link-level `flowable: LinkPattern` primitive — model-level
321
+ * matching by subject class instead of link matching. Empty array =
322
+ * flow declares no typed input. The `"any"` sentinel is accepted as
323
+ * a wildcard for tests and legacy flows.
324
+ */
325
+ public inputTypes: string[] = [];
326
+
327
+ /**
328
+ * Subject-class URIs the flow must produce (linked to the base) for a
329
+ * run to count as complete.
330
+ *
331
+ * Design doc §4.1: a flow's *typed output*. Two jobs:
332
+ * (a) documentation for stateful flows — records what a completed run
333
+ * leaves in the graph; (b) **terminal condition** for zero-state flows —
334
+ * a flow with no `FlowState`s completes when at least one instance of
335
+ * each `outputTypes` entry exists in scope and is linked to the base,
336
+ * and `consensusRule` fires. This is what makes "Like" a first-class
337
+ * flow with no state machine.
338
+ */
339
+ public outputTypes: string[] = [];
340
+
341
+ /**
342
+ * Optional English hint for AI-driven flow-spawn: when should the
343
+ * interpretation engine mint a new instance of this flow (as opposed
344
+ * to advancing an existing one)?
345
+ *
346
+ * Design doc §4.1: analogous to `interpretationHint` on subject
347
+ * classes — steers the LLM's up-front extraction pass. Distinct from
348
+ * `interpretationHint` on the flow, which describes what the flow *is*.
349
+ * Example (Delivery Flow): "Spawn when someone commits to a concrete,
350
+ * actionable task."
351
+ */
352
+ public creationHint?: string;
353
+
354
+ /**
355
+ * Optional background queries pulled into the LLM prompt as CONTEXT
356
+ * (not evidence).
357
+ *
358
+ * Design doc §4.1: engine evaluates each `ModelQuery` and threads
359
+ * matches into the prompt so the LLM can reason with them, but
360
+ * matches do NOT count toward `requires` guards on states. Same
361
+ * `ModelQuery[]` shape and template-variable rules as `FlowState.requires`.
362
+ * Empty / unset = no context queries.
363
+ */
364
+ public context?: ModelQuery[];
365
+
366
+ /**
367
+ * Flow-level consensus rule. Two roles:
368
+ * - **Default for state transitions** — when a `FlowState` doesn't
369
+ * declare its own `consensusRule`, transitions into it fall back
370
+ * to this rule.
371
+ * - **Zero-state flow completion** — for actions-as-flows (a flow
372
+ * with no `FlowState`s), this is the rule the engine checks the
373
+ * moment `outputTypes` are satisfied. E.g. a Like flow declares
374
+ * `{ n: 1 }` and completes on the first author.
375
+ *
376
+ * Design doc §4.1: terminal condition for stateless flows.
377
+ * Unset = engine default of `{ n: 1 }` applies at both layers.
378
+ */
379
+ public consensusRule?: ConsensusRule;
380
+
381
+ /**
382
+ * States in this flow.
383
+ *
384
+ * **Ordering convention (James PR #929 R9):** the array is stored sorted
385
+ * ascending by `value`. `states[0]` is the initial state — the one
386
+ * {@link FlowInstance.start} mints a fresh instance into. A flow author
387
+ * who wants a specific state as the entry point must give it the lowest
388
+ * `value` in the set. `fromLinks` enforces this sort, so link-order on
389
+ * the graph never dictates the initial state.
390
+ */
125
391
  private _states: FlowState[] = [];
126
-
392
+
127
393
  /** Transitions between states */
128
394
  private _transitions: FlowTransition[] = [];
129
395
 
@@ -208,27 +474,67 @@ export class SHACLFlow {
208
474
  target: Literal.from(this.name).toUrl()
209
475
  });
210
476
 
211
- // Flowable condition
212
- if (this.flowable === "any") {
477
+ // Top-level interpretation hint (optional, drives AI state suggestion).
478
+ // Empty strings are treated as "unset" so a round-trip through the graph
479
+ // doesn't materialise an empty-hint predicate that consumers would then
480
+ // read back as a meaningful value.
481
+ if (this.interpretationHint) {
482
+ links.push({
483
+ source: flowUri,
484
+ predicate: "ad4m://interpretationHint",
485
+ target: Literal.from(this.interpretationHint).toUrl()
486
+ });
487
+ }
488
+
489
+ // Typed I/O (flow-level, design §4.1). Both arrays are only
490
+ // serialized when non-empty — an empty list is indistinguishable
491
+ // from "unset" for a round-trip, and emitting one would give
492
+ // downstream consumers a meaningless predicate to interpret.
493
+ if (this.inputTypes.length > 0) {
494
+ links.push({
495
+ source: flowUri,
496
+ predicate: "ad4m://inputTypes",
497
+ target: `literal:string:${encodeURIComponent(JSON.stringify(this.inputTypes))}`
498
+ });
499
+ }
500
+ if (this.outputTypes.length > 0) {
501
+ links.push({
502
+ source: flowUri,
503
+ predicate: "ad4m://outputTypes",
504
+ target: `literal:string:${encodeURIComponent(JSON.stringify(this.outputTypes))}`
505
+ });
506
+ }
507
+
508
+ // Flow-level `creationHint` — same empty-string-is-unset guard as
509
+ // `interpretationHint`, same reason (round-trip fidelity).
510
+ if (this.creationHint) {
213
511
  links.push({
214
512
  source: flowUri,
215
- predicate: "ad4m://flowable",
216
- target: "ad4m://any"
513
+ predicate: "ad4m://creationHint",
514
+ target: Literal.from(this.creationHint).toUrl()
217
515
  });
218
- } else {
516
+ }
517
+
518
+ // Flow-level `context` — background queries the LLM sees but not
519
+ // guard evidence. Single JSON literal, consumers parse back.
520
+ if (this.context && this.context.length > 0) {
219
521
  links.push({
220
522
  source: flowUri,
221
- predicate: "ad4m://flowable",
222
- target: `literal:string:${encodeURIComponent(JSON.stringify(this.flowable))}`
523
+ predicate: "ad4m://context",
524
+ target: `literal:string:${encodeURIComponent(JSON.stringify(this.context))}`
223
525
  });
224
526
  }
225
527
 
226
- // Start action
227
- if (this.startAction.length > 0) {
528
+ // Flow-level `consensusRule` — default for state transitions when a
529
+ // FlowState omits its own rule; also the terminal-firing rule for
530
+ // zero-state flows. Serialized as one JSON literal (the shape is
531
+ // fixed and cheap to parse; consistent with `context` / `requires`
532
+ // so consumers only need one parser).
533
+ if (this.consensusRule) {
228
534
  links.push({
229
535
  source: flowUri,
230
- predicate: "ad4m://startAction",
231
- target: `literal:string:${encodeURIComponent(JSON.stringify(this.startAction))}`
536
+ predicate: "ad4m://consensusRule",
537
+ target: `literal:string:${encodeURIComponent(JSON.stringify(this.consensusRule))}`
232
538
  });
233
539
  }
234
540
 
@@ -264,12 +570,48 @@ export class SHACLFlow {
264
570
  target: Literal.from(state.value).toUrl()
265
571
  });
266
572
 
267
- // State check pattern
268
- links.push({
269
- source: stateUri,
270
- predicate: "ad4m://stateCheck",
271
- target: `literal:string:${encodeURIComponent(JSON.stringify(state.stateCheck))}`
272
- });
573
+ // Per-state interpretation hint (optional, drives AI state suggestion).
574
+ // Empty strings treated as unset — same rationale as the flow-level hint.
575
+ if (state.interpretationHint) {
576
+ links.push({
577
+ source: stateUri,
578
+ predicate: "ad4m://interpretationHint",
579
+ target: Literal.from(state.interpretationHint).toUrl()
580
+ });
581
+ }
582
+
583
+ // Per-state `requires` guard — array of ModelQueries, AND-combined.
584
+ // Serialized as one JSON string on `ad4m://requires`. Consumers
585
+ // (state-transition engine, `flow.availableActions`) parse back.
586
+ if (state.requires && state.requires.length > 0) {
587
+ links.push({
588
+ source: stateUri,
589
+ predicate: "ad4m://requires",
590
+ target: `literal:string:${encodeURIComponent(JSON.stringify(state.requires))}`
591
+ });
592
+ }
593
+
594
+ // Per-state `semanticCheck` hint — optional English confirmation
595
+ // that runs after `requires` matches, for states where structural
596
+ // presence isn't sufficient evidence. Empty string = unset.
597
+ if (state.semanticCheck) {
598
+ links.push({
599
+ source: stateUri,
600
+ predicate: "ad4m://semanticCheck",
601
+ target: Literal.from(state.semanticCheck).toUrl()
602
+ });
603
+ }
604
+
605
+ // Per-state `consensusRule` override — one JSON literal on the
606
+ // state, same predicate name as the flow-level rule but scoped by
607
+ // source URI so the reader can tell them apart.
608
+ if (state.consensusRule) {
609
+ links.push({
610
+ source: stateUri,
611
+ predicate: "ad4m://consensusRule",
612
+ target: `literal:string:${encodeURIComponent(JSON.stringify(state.consensusRule))}`
613
+ });
614
+ }
273
615
  }
274
616
 
275
617
  // Transitions
@@ -350,36 +692,123 @@ export class SHACLFlow {
350
692
 
351
693
  const flow = new SHACLFlow(name, namespace);
352
694
 
353
- // Find flowable condition
354
- const flowableLink = links.find(l =>
355
- l.source === flowUri && l.predicate === "ad4m://flowable"
695
+ // Find top-level interpretation hint. Only accept a decoded value that
696
+ // is a non-empty string — malformed literals (Literal.get() can return
697
+ // an object, number, etc.) leave the field unset rather than becoming
698
+ // corrupt flow metadata.
699
+ const flowHintLink = links.find(l =>
700
+ l.source === flowUri && l.predicate === "ad4m://interpretationHint"
356
701
  );
357
- if (flowableLink) {
358
- if (flowableLink.target === "ad4m://any") {
359
- flow.flowable = "any";
360
- } else {
361
- try {
362
- const jsonStr = flowableLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
363
- flow.flowable = JSON.parse(decodeURIComponent(jsonStr));
364
- } catch {
365
- flow.flowable = "any";
702
+ if (flowHintLink) {
703
+ try {
704
+ const decoded = Literal.fromUrl(flowHintLink.target).get();
705
+ if (typeof decoded === "string" && decoded.length > 0) {
706
+ flow.interpretationHint = decoded;
707
+ }
708
+ } catch {
709
+ // Ignore parse errors — leave unset.
710
+ }
711
+ }
712
+
713
+ // Find typed I/O (flow-level, design §4.1). Both arrays validated
714
+ // element-wise — only accept string[] payloads. A malformed literal
715
+ // (`[null]`, `[42]`, non-array) leaves the field as its default
716
+ // empty array rather than corrupting flow metadata.
717
+ const inputTypesLink = links.find(l =>
718
+ l.source === flowUri && l.predicate === "ad4m://inputTypes"
719
+ );
720
+ if (inputTypesLink) {
721
+ try {
722
+ const jsonStr = inputTypesLink.target.replace(
723
+ /^literal:\/\/string:|^literal:string:/,
724
+ ""
725
+ );
726
+ const parsed = JSON.parse(decodeURIComponent(jsonStr));
727
+ if (Array.isArray(parsed) && parsed.every(v => typeof v === "string" && v.length > 0)) {
728
+ flow.inputTypes = parsed as string[];
729
+ }
730
+ } catch {
731
+ // Ignore parse errors — leave as default empty array.
732
+ }
733
+ }
734
+
735
+ const outputTypesLink = links.find(l =>
736
+ l.source === flowUri && l.predicate === "ad4m://outputTypes"
737
+ );
738
+ if (outputTypesLink) {
739
+ try {
740
+ const jsonStr = outputTypesLink.target.replace(
741
+ /^literal:\/\/string:|^literal:string:/,
742
+ ""
743
+ );
744
+ const parsed = JSON.parse(decodeURIComponent(jsonStr));
745
+ if (Array.isArray(parsed) && parsed.every(v => typeof v === "string" && v.length > 0)) {
746
+ flow.outputTypes = parsed as string[];
747
+ }
748
+ } catch {
749
+ // Ignore parse errors — leave as default empty array.
750
+ }
751
+ }
752
+
753
+ // Find flow-level `creationHint`. Non-empty-string guard — same
754
+ // rationale as `interpretationHint`.
755
+ const creationHintLink = links.find(l =>
756
+ l.source === flowUri && l.predicate === "ad4m://creationHint"
757
+ );
758
+ if (creationHintLink) {
759
+ try {
760
+ const decoded = Literal.fromUrl(creationHintLink.target).get();
761
+ if (typeof decoded === "string" && decoded.length > 0) {
762
+ flow.creationHint = decoded;
763
+ }
764
+ } catch {
765
+ // Ignore parse errors — leave unset.
766
+ }
767
+ }
768
+
769
+ // Find flow-level `context` — same ModelQuery-shape guard as
770
+ // FlowState.requires (rejects `[null]`, `[{}]`, non-string
771
+ // `className`).
772
+ const contextLink = links.find(l =>
773
+ l.source === flowUri && l.predicate === "ad4m://context"
774
+ );
775
+ if (contextLink) {
776
+ try {
777
+ const jsonStr = contextLink.target.replace(
778
+ /^literal:\/\/string:|^literal:string:/,
779
+ ""
780
+ );
781
+ const parsed = JSON.parse(decodeURIComponent(jsonStr));
782
+ if (Array.isArray(parsed) && parsed.every(isModelQueryShape)) {
783
+ flow.context = parsed as ModelQuery[];
366
784
  }
785
+ } catch {
786
+ // Ignore parse errors — leave unset.
367
787
  }
368
788
  }
369
789
 
370
- // Find start action
371
- const startActionLink = links.find(l =>
372
- l.source === flowUri && l.predicate === "ad4m://startAction"
790
+ // Find flow-level `consensusRule`. Reject malformed literals
791
+ // (missing `n`, non-integer `n`, invalid `fromRole`) so the runtime
792
+ // engine never has to defensively re-validate a stored rule.
793
+ const consensusRuleLink = links.find(l =>
794
+ l.source === flowUri && l.predicate === "ad4m://consensusRule"
373
795
  );
374
- if (startActionLink) {
796
+ if (consensusRuleLink) {
375
797
  try {
376
- const jsonStr = startActionLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
377
- flow.startAction = JSON.parse(decodeURIComponent(jsonStr));
798
+ const jsonStr = consensusRuleLink.target.replace(
799
+ /^literal:\/\/string:|^literal:string:/,
800
+ ""
801
+ );
802
+ const parsed = JSON.parse(decodeURIComponent(jsonStr));
803
+ if (isConsensusRuleShape(parsed)) {
804
+ flow.consensusRule = parsed;
805
+ }
378
806
  } catch {
379
- // Ignore parse errors
807
+ // Ignore parse errors — leave unset.
380
808
  }
381
809
  }
382
810
 
811
+
383
812
  // Find states
384
813
  const stateLinks = links.filter(l =>
385
814
  l.source === flowUri && l.predicate === "ad4m://hasState"
@@ -406,23 +835,101 @@ export class SHACLFlow {
406
835
  );
407
836
  const stateValue = valueLink ? Literal.fromUrl(valueLink.target).get() as number : 0;
408
837
 
409
- // Get state check
410
- const checkLink = links.find(l =>
411
- l.source === stateUri && l.predicate === "ad4m://stateCheck"
838
+ // Get per-state interpretation hint (optional). Same non-empty-string
839
+ // guard as the flow-level hint.
840
+ const hintLink = links.find(l =>
841
+ l.source === stateUri && l.predicate === "ad4m://interpretationHint"
412
842
  );
413
- let stateCheck: LinkPattern = { predicate: "", target: "" };
414
- if (checkLink) {
843
+ let interpretationHint: string | undefined;
844
+ if (hintLink) {
415
845
  try {
416
- const jsonStr = checkLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
417
- stateCheck = JSON.parse(decodeURIComponent(jsonStr));
846
+ const decoded = Literal.fromUrl(hintLink.target).get();
847
+ if (typeof decoded === "string" && decoded.length > 0) {
848
+ interpretationHint = decoded;
849
+ }
418
850
  } catch {
419
- // Ignore parse errors
851
+ // Ignore parse errors — leave unset.
420
852
  }
421
853
  }
422
-
423
- flow.addState({ name: stateName, value: stateValue, stateCheck });
854
+
855
+ // Get per-state `requires` guard (optional) — one link carrying a
856
+ // JSON-encoded ModelQuery[]. Reject arrays whose entries are not
857
+ // ModelQuery-shaped (missing/non-string `className`, `null`, primitives).
858
+ const requiresLink = links.find(l =>
859
+ l.source === stateUri && l.predicate === "ad4m://requires"
860
+ );
861
+ let requires: ModelQuery[] | undefined;
862
+ if (requiresLink) {
863
+ try {
864
+ const jsonStr = requiresLink.target.replace(
865
+ /^literal:\/\/string:|^literal:string:/,
866
+ ""
867
+ );
868
+ const parsed = JSON.parse(decodeURIComponent(jsonStr));
869
+ if (Array.isArray(parsed) && parsed.every(isModelQueryShape)) {
870
+ requires = parsed as ModelQuery[];
871
+ }
872
+ } catch {
873
+ // Ignore parse errors — leave requires unset rather than crash
874
+ }
875
+ }
876
+
877
+ // Get per-state `semanticCheck` hint (optional). Non-empty-string guard.
878
+ const semanticCheckLink = links.find(l =>
879
+ l.source === stateUri && l.predicate === "ad4m://semanticCheck"
880
+ );
881
+ let semanticCheck: string | undefined;
882
+ if (semanticCheckLink) {
883
+ try {
884
+ const decoded = Literal.fromUrl(semanticCheckLink.target).get();
885
+ if (typeof decoded === "string" && decoded.length > 0) {
886
+ semanticCheck = decoded;
887
+ }
888
+ } catch {
889
+ // Ignore parse errors — leave unset.
890
+ }
891
+ }
892
+
893
+ // Get per-state `consensusRule` override (optional). Same shape
894
+ // guard as the flow-level rule; a malformed literal (missing `n`,
895
+ // non-integer, invalid `fromRole`) leaves the field unset.
896
+ const stateConsensusLink = links.find(l =>
897
+ l.source === stateUri && l.predicate === "ad4m://consensusRule"
898
+ );
899
+ let consensusRule: ConsensusRule | undefined;
900
+ if (stateConsensusLink) {
901
+ try {
902
+ const jsonStr = stateConsensusLink.target.replace(
903
+ /^literal:\/\/string:|^literal:string:/,
904
+ ""
905
+ );
906
+ const parsed = JSON.parse(decodeURIComponent(jsonStr));
907
+ if (isConsensusRuleShape(parsed)) {
908
+ consensusRule = parsed;
909
+ }
910
+ } catch {
911
+ // Ignore parse errors — leave unset.
912
+ }
913
+ }
914
+
915
+ flow.addState({
916
+ name: stateName,
917
+ value: stateValue,
918
+ ...(interpretationHint !== undefined ? { interpretationHint } : {}),
919
+ ...(requires !== undefined ? { requires } : {}),
920
+ ...(semanticCheck !== undefined ? { semanticCheck } : {}),
921
+ ...(consensusRule !== undefined ? { consensusRule } : {}),
922
+ });
424
923
  }
425
924
 
925
+ // Perspective link storage does not preserve insertion order — `hasState`
926
+ // links come back in arbitrary order from the graph, so `flow.states[0]`
927
+ // was randomly one of the round-tripped states. Sort by `value` ascending
928
+ // so the "initial state = states[0]" convention (used by
929
+ // `FlowInstance.start`) survives a fromGraph round trip.
930
+ // The `states` getter returns a defensive copy, so mutate `_states` directly.
931
+ flow._states.sort((a, b) => a.value - b.value);
932
+
426
933
  // Find transitions
427
934
  const transitionLinks = links.filter(l =>
428
935
  l.source === flowUri && l.predicate === "ad4m://hasTransition"
@@ -475,13 +982,31 @@ export class SHACLFlow {
475
982
  * Convert to JSON representation
476
983
  */
477
984
  toJSON(): object {
985
+ // Per-state metadata is optional; strip empty strings / empty arrays so
986
+ // json.states[i] agrees with what toLinks() would materialise (a state
987
+ // constructed with `interpretationHint: ""` produces no predicate, so
988
+ // JSON must not carry the empty field either).
989
+ const sanitizedStates = this._states.map(s => ({
990
+ name: s.name,
991
+ value: s.value,
992
+ ...(s.interpretationHint ? { interpretationHint: s.interpretationHint } : {}),
993
+ ...(s.requires && s.requires.length > 0 ? { requires: s.requires } : {}),
994
+ ...(s.semanticCheck ? { semanticCheck: s.semanticCheck } : {}),
995
+ ...(s.consensusRule ? { consensusRule: s.consensusRule } : {})
996
+ }));
478
997
  return {
479
998
  name: this.name,
480
999
  namespace: this.namespace,
481
- flowable: this.flowable,
482
- startAction: this.startAction,
483
- states: this._states,
484
- transitions: this._transitions
1000
+ states: sanitizedStates,
1001
+ transitions: this._transitions,
1002
+ // Empty strings / empty arrays treated as unset — same semantics
1003
+ // as the toLinks path, so JSON <-> links round-trips agree.
1004
+ ...(this.interpretationHint ? { interpretationHint: this.interpretationHint } : {}),
1005
+ ...(this.inputTypes.length > 0 ? { inputTypes: this.inputTypes } : {}),
1006
+ ...(this.outputTypes.length > 0 ? { outputTypes: this.outputTypes } : {}),
1007
+ ...(this.creationHint ? { creationHint: this.creationHint } : {}),
1008
+ ...(this.context && this.context.length > 0 ? { context: this.context } : {}),
1009
+ ...(this.consensusRule ? { consensusRule: this.consensusRule } : {})
485
1010
  };
486
1011
  }
487
1012
 
@@ -490,10 +1015,53 @@ export class SHACLFlow {
490
1015
  */
491
1016
  static fromJSON(json: any): SHACLFlow {
492
1017
  const flow = new SHACLFlow(json.name, json.namespace);
493
- flow.flowable = json.flowable || "any";
494
- flow.startAction = json.startAction || [];
1018
+ // Non-empty-string guard — mirrors the toLinks-side reader.
1019
+ if (typeof json.interpretationHint === "string" && json.interpretationHint.length > 0) {
1020
+ flow.interpretationHint = json.interpretationHint;
1021
+ }
1022
+ // Typed I/O (design §4.1). Same string[]/ModelQuery[] shape guards
1023
+ // as the fromLinks path — malformed payloads leave defaults untouched.
1024
+ if (
1025
+ Array.isArray(json.inputTypes) &&
1026
+ json.inputTypes.every((v: unknown) => typeof v === "string" && v.length > 0)
1027
+ ) {
1028
+ flow.inputTypes = json.inputTypes as string[];
1029
+ }
1030
+ if (
1031
+ Array.isArray(json.outputTypes) &&
1032
+ json.outputTypes.every((v: unknown) => typeof v === "string" && v.length > 0)
1033
+ ) {
1034
+ flow.outputTypes = json.outputTypes as string[];
1035
+ }
1036
+ if (typeof json.creationHint === "string" && json.creationHint.length > 0) {
1037
+ flow.creationHint = json.creationHint;
1038
+ }
1039
+ if (Array.isArray(json.context) && json.context.every(isModelQueryShape)) {
1040
+ flow.context = json.context as ModelQuery[];
1041
+ }
1042
+ if (isConsensusRuleShape(json.consensusRule)) {
1043
+ flow.consensusRule = json.consensusRule as ConsensusRule;
1044
+ }
495
1045
  for (const state of json.states || []) {
496
- flow.addState(state);
1046
+ // Same validation as the toLinks path: reject malformed optional fields
1047
+ // rather than let them poison downstream consumers.
1048
+ const sanitized: FlowState = {
1049
+ name: state.name,
1050
+ value: state.value,
1051
+ };
1052
+ if (typeof state.interpretationHint === "string" && state.interpretationHint.length > 0) {
1053
+ sanitized.interpretationHint = state.interpretationHint;
1054
+ }
1055
+ if (Array.isArray(state.requires) && state.requires.every(isModelQueryShape)) {
1056
+ sanitized.requires = state.requires as ModelQuery[];
1057
+ }
1058
+ if (typeof state.semanticCheck === "string" && state.semanticCheck.length > 0) {
1059
+ sanitized.semanticCheck = state.semanticCheck;
1060
+ }
1061
+ if (isConsensusRuleShape(state.consensusRule)) {
1062
+ sanitized.consensusRule = state.consensusRule as ConsensusRule;
1063
+ }
1064
+ flow.addState(sanitized);
497
1065
  }
498
1066
  for (const transition of json.transitions || []) {
499
1067
  flow.addTransition(transition);