@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
@@ -40,14 +40,35 @@ export type RawScope = { id: string; predicate: string };
40
40
  * - `batchReady` → `notCandidate` — this peer stood down for an earlier author
41
41
  * - `claimed` → `shapesMissing` — a configured class shape hasn't synced
42
42
  * - `claimed` → `emptyTranscript` — the batch drained empty
43
+ * - any → `failed` — the model errored or timed out;
44
+ * `detail` carries why. Distinct from the two above, which are the pass
45
+ * correctly finding nothing to do — reporting "nothing to extract" when
46
+ * the LLM endpoint was unreachable points someone at their transcript
47
+ * instead of at their model settings.
48
+ *
49
+ * ## Lifecycle (one-shot `runInterpretation`)
50
+ *
51
+ * A one-shot pass emits nothing unless the caller passes `observe` (see
52
+ * {@link PerspectiveProxy.runInterpretation}). With it:
53
+ *
54
+ * `runningInterpretation` → [`llmRequestSent` → `llmResponseReceived`] →
55
+ * `processed` | `failed`
56
+ *
57
+ * — plus `claimed` → `finished`/`abandoned` on the neighbourhood stream, so
58
+ * one-shot and watch passes render through the same consumer code. There is
59
+ * no `batchReady`, `gatheringTranscript` or claim: the caller supplied the
60
+ * transcript, and `processorId`/`batchKey` both carry the caller's own
61
+ * `observationId`.
43
62
  *
44
63
  * ## Payload fields per step
45
64
  *
46
- * All steps carry `perspectiveUuid`, `processorId`, `agentDid`, `itemIds[]`.
65
+ * All steps carry `perspectiveUuid`, `processorId`, `agentDid`, `itemIds[]`
66
+ * and `batchKey` (the join key to the neighbourhood-state stream).
47
67
  * Additional payload:
48
68
  *
49
69
  * - `backedOff`, `notCandidate` → `detail` = holder / elected-author DID
50
70
  * - `shapesMissing` → `detail` = comma-joined missing class URIs
71
+ * - `failed` → `detail` = the error
51
72
  * - `llmRequestSent` → `llmInput` = raw prompt
52
73
  * - `llmResponseReceived` → `llmOutput` = raw LLM response
53
74
  * - `processed` → `bases[]` = new/updated instance URIs
@@ -62,9 +83,12 @@ export type AutoProcessorStep =
62
83
  | "runningInterpretation"
63
84
  | "llmRequestSent"
64
85
  | "llmResponseReceived"
86
+ | "toolCall"
87
+ | "toolResult"
65
88
  | "processed"
66
89
  | "shapesMissing"
67
- | "emptyTranscript";
90
+ | "emptyTranscript"
91
+ | "failed";
68
92
 
69
93
  /** A single step-signal from one auto-processor pass on one perspective. */
70
94
  export interface AutoProcessorEvent {
@@ -76,6 +100,24 @@ export interface AutoProcessorEvent {
76
100
  step: AutoProcessorStep;
77
101
  /** The batch's source item ids (present from `batchReady` onward). */
78
102
  itemIds: string[];
103
+ /**
104
+ * Content hash of the batch — the same value
105
+ * {@link AutoProcessorNeighbourhoodStateEvent.batchKey} carries, and the
106
+ * key that joins the two streams.
107
+ *
108
+ * A UI that renders one row per pass subscribes to both: the
109
+ * perspective-scoped neighbourhood stream opens the row (and names the
110
+ * claimant), while this DID-scoped stream fills in the fine-grained
111
+ * steps and LLM I/O for the pass this agent is running. Matching them on
112
+ * `processorId` alone breaks as soon as a processor runs a second pass;
113
+ * matching on `itemIds` means re-implementing the Rust SHA-256 and its
114
+ * exact serialization. So both streams carry the same key.
115
+ *
116
+ * Present from `batchReady` onward. Optional on the type because a
117
+ * pre-#903 executor does not send it — treat its absence as "cannot
118
+ * correlate", not as an error.
119
+ */
120
+ batchKey?: string;
79
121
  /** Instance base URIs written by the pass (present on `processed`). */
80
122
  bases: string[];
81
123
  /** Free-form context for the step (a holder/elected DID, an error, …). */
@@ -88,6 +130,24 @@ export interface AutoProcessorEvent {
88
130
  * `llmResponseReceived` events, and only when the processor was
89
131
  * configured with `emitDebugEvents: true`. Never carried on `processed`. */
90
132
  llmOutput?: string;
133
+ /**
134
+ * Name of the tool the harness LLM invoked (or that just returned).
135
+ * Present on `toolCall` + `toolResult` events (harness path only).
136
+ */
137
+ toolName?: string;
138
+ /**
139
+ * JSON-encoded arguments the LLM sent to the tool. Present ONLY on
140
+ * `toolCall`; absent on `toolResult` where {@link toolResult} carries
141
+ * the return text instead.
142
+ */
143
+ toolArgsJson?: string;
144
+ /**
145
+ * The tool's return text. Present ONLY on `toolResult`; may be
146
+ * pre-truncated by the emitter with an `…[truncated for event]`
147
+ * marker when the tool returns a large payload (e.g. a `_query`
148
+ * result). Consumers wanting the full text can re-run the tool.
149
+ */
150
+ toolResult?: string;
91
151
  }
92
152
 
93
153
  /**
@@ -122,6 +182,34 @@ export interface AutoProcessorNeighbourhoodStateEvent {
122
182
  phase: NeighbourhoodPhase;
123
183
  }
124
184
 
185
+ /**
186
+ * Opt a one-shot `runInterpretation` call into the same event streams a
187
+ * standing watch produces.
188
+ *
189
+ * Without it the call is silent until it resolves — which, on a local model,
190
+ * is minutes of a UI having nothing to say. With it the pass reports
191
+ * `runningInterpretation` → `processed`/`failed` on the DID-scoped stream and
192
+ * `claimed` → `finished`/`abandoned` on the perspective-scoped one.
193
+ */
194
+ export interface RunInterpretationObserveOptions {
195
+ /**
196
+ * The caller's own id for this pass, echoed back as both `processorId` and
197
+ * `batchKey` on every event it emits.
198
+ *
199
+ * Supplied by the caller rather than minted by the executor because
200
+ * `runInterpretation` is a single blocking call: there is no earlier
201
+ * response that could hand back a server-side id, so the events would
202
+ * arrive with nothing to match them against. Any value unique among this
203
+ * client's in-flight passes will do.
204
+ */
205
+ observationId: string;
206
+ /**
207
+ * Also emit `llmRequestSent` / `llmResponseReceived` with the raw prompt
208
+ * and response. Default `false`.
209
+ */
210
+ emitDebugEvents?: boolean;
211
+ }
212
+
125
213
  /** Configuration for `perspective.addAutoProcessor` (everything but `uuid`). */
126
214
  export interface AddAutoProcessorConfig {
127
215
  /** Human-meaningful processor id (unique per perspective). */
@@ -194,30 +282,12 @@ export interface AddAutoProcessorConfig {
194
282
  */
195
283
  mintScope?: RawScope;
196
284
  /**
197
- * Persist the raw LLM prompt + response on the pass's `InterpretationRun`
198
- * (`debugPrompt` / `debugResponse`) so a UI can look them up post-hoc.
199
- * Independent of `emitDebugEvents` — Nico's PR #903 split so a caller
200
- * can persist without emitting mid-pass events (retrospective inspection
201
- * only) or emit without persisting (live observability, no graph-sync
202
- * payload). Default `false` — LLM I/O is 10s of KB per pass and every
203
- * enabled peer syncs it.
204
- */
205
- persistDebug?: boolean;
206
- /**
207
- * Emit `LlmRequestSent` and `LlmResponseReceived` `auto-processor-event`s
208
- * mid-pass, so a subscribed UI can render "waiting on LLM" between
209
- * prompt-send and response-receive. See `persistDebug` for the split
210
- * rationale. Default `false`.
285
+ * Enable full debug observability: persists the raw LLM prompt + response
286
+ * on the pass's `InterpretationRun` (`debugPrompt` / `debugResponse`) AND
287
+ * emits `LlmRequestSent` / `LlmResponseReceived` mid-pass events so a
288
+ * subscribed UI can render "waiting on LLM". Default `false`.
211
289
  */
212
290
  emitDebugEvents?: boolean;
213
- /**
214
- * Legacy backwards-compat alias — pre-split callers set `debugMode` as a
215
- * single coupled flag. When present and both `persistDebug` +
216
- * `emitDebugEvents` are absent, its value is expanded to both. The two
217
- * specific fields take precedence when present. Prefer the split fields;
218
- * this alias is retained so pre-split clients still work.
219
- */
220
- debugMode?: boolean;
221
291
  }
222
292
 
223
293
  /**
@@ -0,0 +1,369 @@
1
+ /**
2
+ * `FlowInstance` — object-oriented wrapper for a running flow.
3
+ *
4
+ * Design authority: `docs/flow-interpretation-hints-design.md` §4.3.
5
+ *
6
+ * Wraps two on-graph objects:
7
+ *
8
+ * - `FlowInstanceRecord` — the raw @Model row minted by
9
+ * {@link FlowInstance.start}; carries `flow`, `subject`, `currentState`,
10
+ * and Ad4mModel's synthesised `createdAt`.
11
+ * - `SHACLFlow` — the flow definition the record is bound to. Held so
12
+ * `availableTransitions` / `currentState` object lookups don't require
13
+ * a per-call round-trip.
14
+ *
15
+ * Construct via the class factories — {@link FlowInstance.start} for the
16
+ * mint path and {@link FlowInstance.findAll} for the read path — rather
17
+ * than the `wrap` escape hatch, which exists for tests that already own
18
+ * a matched (record, shape) pair.
19
+ *
20
+ * # What's here vs. what's coming in §7 / slice 10.6
21
+ *
22
+ * Read surface (implemented today, PR #929):
23
+ * - `uri`, `subject`, `flowName`, `currentStateName`, `startedAtMillis`
24
+ * accessors.
25
+ * - `currentState` — resolves the `FlowState` on the shape whose name
26
+ * matches `record.currentState`.
27
+ * - `availableTransitions` — filters `shape.transitions` by `fromState`.
28
+ * - `proposals()` — queries `FlowTransitionProposal` records that
29
+ * target this instance's URI.
30
+ *
31
+ * Mutations + subscriptions (`proposeTransition`, `accept`, `reject`,
32
+ * `fireAction`, `onStateChange`, `onProposalAdded`, `onProposalResolved`)
33
+ * land with the consensus-engine slice (§4.3 / slice 10.6). Rather than
34
+ * ship them as `throw new Error("not yet")` stubs — which is a type-level
35
+ * lie the caller only discovers at runtime — they are simply absent from
36
+ * this class until the engine is wired.
37
+ */
38
+
39
+ import { PerspectiveProxy } from "./PerspectiveProxy";
40
+ import { Ad4mModel } from "../model/Ad4mModel";
41
+ import { FlowInstanceRecord, FlowTransitionProposal } from "./FlowModels";
42
+ import { SHACLFlow, FlowState, FlowTransition } from "../shacl/SHACLFlow";
43
+
44
+ /**
45
+ * Extract the flow's human-readable name from its canonical URI.
46
+ *
47
+ * `SHACLFlow.flowUri` is `${namespace}${name}Flow` (e.g.
48
+ * `coasys://DeliveryFlow`). This function strips the `Flow` suffix and
49
+ * everything before the last URI-segment separator (`/` or `#`), leaving
50
+ * the bare name. Returns `undefined` for URIs that don't match the
51
+ * `…{name}Flow` shape — a stale FlowInstanceRecord whose flow URI came
52
+ * from an older writer, for instance.
53
+ */
54
+ function flowNameFromUri(flowUri: string): string | undefined {
55
+ if (!flowUri.endsWith("Flow")) return undefined;
56
+ const withoutSuffix = flowUri.slice(0, -"Flow".length);
57
+ const sepIdx = Math.max(
58
+ withoutSuffix.lastIndexOf("/"),
59
+ withoutSuffix.lastIndexOf("#"),
60
+ );
61
+ if (sepIdx < 0) return withoutSuffix || undefined;
62
+ const name = withoutSuffix.slice(sepIdx + 1);
63
+ return name || undefined;
64
+ }
65
+
66
+ export class FlowInstance {
67
+ /**
68
+ * Private constructor — construct via {@link FlowInstance.start} or
69
+ * {@link FlowInstance.findAll}. {@link FlowInstance.wrap} is the
70
+ * escape hatch for tests / direct construction cases.
71
+ */
72
+ private constructor(
73
+ private readonly perspective: PerspectiveProxy,
74
+ /** The flow definition this instance was minted against. */
75
+ public readonly shape: SHACLFlow,
76
+ /**
77
+ * The on-graph record — carries `flow`, `subject`, `currentState`
78
+ * and Ad4mModel's synthesised `createdAt`. Callers can reach into it
79
+ * for anything the wrapper doesn't expose directly, but should prefer
80
+ * the wrapper accessors so future refactors of the underlying shape
81
+ * don't ripple through their code.
82
+ */
83
+ public readonly record: FlowInstanceRecord,
84
+ ) {}
85
+
86
+ /**
87
+ * Escape hatch used by {@link FlowInstance.start} and
88
+ * {@link FlowInstance.findAll} — not meant for general use, but public
89
+ * so tests that already own a `FlowInstanceRecord + SHACLFlow` pair
90
+ * (e.g. from pre-populated fixtures) can build a wrapper without
91
+ * going through the mint path.
92
+ */
93
+ static wrap(
94
+ perspective: PerspectiveProxy,
95
+ shape: SHACLFlow,
96
+ record: FlowInstanceRecord,
97
+ ): FlowInstance {
98
+ return new FlowInstance(perspective, shape, record);
99
+ }
100
+
101
+ /**
102
+ * Mint a new `FlowInstance` on the given perspective (design doc §4.3).
103
+ *
104
+ * Idempotently registers the hardwired `FlowInstanceRecord` +
105
+ * `FlowTransitionProposal` @Model classes on first call — the on-graph
106
+ * shape matches the Rust-side hardwired SDNA (parity-locked in
107
+ * `flow-instance.test.ts` / `flow-transition-proposal.test.ts`).
108
+ *
109
+ * The returned wrapper carries the parsed `SHACLFlow` alongside the
110
+ * on-graph record, so `currentState` / `availableTransitions` /
111
+ * `proposals` accessors work without further round-trips. The consensus
112
+ * engine (slice 10.6) will read the record's `currentState` when it
113
+ * fires transitions.
114
+ *
115
+ * @param perspective - The perspective the flow instance lives on
116
+ * @param flowName - Name of a `SHACLFlow` already registered on the perspective
117
+ * @param baseExpression - URI of the subject expression the flow runs on
118
+ * @throws When the flow is unknown or has zero declared states (zero-state
119
+ * flows fire via the forthcoming atomic-action path, §6.3).
120
+ */
121
+ static async start(
122
+ perspective: PerspectiveProxy,
123
+ flowName: string,
124
+ baseExpression: string,
125
+ ): Promise<FlowInstance> {
126
+ const flow = await perspective.getFlow(flowName);
127
+ if (!flow) throw `Flow "${flowName}" not found`;
128
+ if (flow.states.length === 0) {
129
+ throw `Flow "${flowName}" has no states — FlowInstance.start is for stateful flows only; zero-state flows fire via the forthcoming atomic-action path (§6.3)`;
130
+ }
131
+ // Register the hardwired runtime classes if this is the first flow
132
+ // instance on the perspective. registerAll is a single batched RPC and
133
+ // no-ops when both classes are already present.
134
+ await Ad4mModel.registerAll(perspective, [FlowInstanceRecord, FlowTransitionProposal]);
135
+ // Property keys must be the FlowInstanceRecord @Model field names —
136
+ // `subject` (not `baseExpression`, which collides with Ad4mModel's
137
+ // synthetic hydration field and would be silently shadowed on read).
138
+ // No explicit start-time field: Ad4mModel synthesises `createdAt` on
139
+ // hydration from the earliest link timestamp on the instance's URI.
140
+ // Convention: `SHACLFlow.states` is stored sorted ascending by `value`
141
+ // (enforced by `fromLinks`), so `states[0]` is the initial state. A
142
+ // flow author who wants a specific state as the entry point must give
143
+ // it the lowest `value` in the set.
144
+ //
145
+ // Store the flow's URI, not the bare name — see FlowInstanceRecord's
146
+ // docstring for the collision-across-modules argument (James PR #929 R5).
147
+ const record = await FlowInstanceRecord.create(perspective, {
148
+ flowUri: flow.flowUri,
149
+ subject: baseExpression,
150
+ currentState: flow.states[0].name,
151
+ });
152
+ return FlowInstance.wrap(perspective, flow, record);
153
+ }
154
+
155
+ /**
156
+ * Return every live `FlowInstance` on the perspective (design doc §4.3).
157
+ *
158
+ * Read-only path: never registers classes. On a perspective that has
159
+ * never minted a flow instance, the `FlowInstanceRecord` SHACL shape
160
+ * isn't installed yet — this returns `[]` in that case rather than
161
+ * mutating the perspective. Registration is the responsibility of
162
+ * {@link FlowInstance.start}, which is the write path. (Registering on
163
+ * a read would sync a write to every peer in the neighbourhood —
164
+ * exactly what a query must not do — James PR #929 R7.)
165
+ *
166
+ * Filter surface (all optional, all combinable):
167
+ * - **`flowName`** — narrows by flow-name discriminator (e.g. "Delivery")
168
+ * - **`subject`** — narrows by base-expression URI, i.e. "give me every
169
+ * flow running on THIS expression"
170
+ *
171
+ * Both filters translate to a single SHACL `where`-filter round-trip
172
+ * (no client-side filtering); combining them AND-joins server-side.
173
+ * The string-arg shape (`FlowInstance.findAll(p, "Delivery")`) is
174
+ * shorthand for `{ flowName: "Delivery" }`.
175
+ *
176
+ * Records whose `flow` value has no matching `SHACLFlow` on the
177
+ * perspective (e.g. the flow was unregistered) are silently skipped —
178
+ * the wrapper can't answer `currentState` / `availableTransitions`
179
+ * without the shape, and callers routinely iterate the returned array
180
+ * without null-checks.
181
+ *
182
+ * @example
183
+ * ```typescript
184
+ * const all = await FlowInstance.findAll(perspective);
185
+ * const deliveries = await FlowInstance.findAll(perspective, "Delivery");
186
+ * const onThisTask = await FlowInstance.findAll(perspective, {
187
+ * subject: "ad4m://task/1",
188
+ * });
189
+ * const deliveriesOnTask = await FlowInstance.findAll(perspective, {
190
+ * flowName: "Delivery",
191
+ * subject: "ad4m://task/1",
192
+ * });
193
+ * ```
194
+ */
195
+ static async findAll(
196
+ perspective: PerspectiveProxy,
197
+ filter?: string | { flowName?: string; subject?: string },
198
+ ): Promise<FlowInstance[]> {
199
+ const { flowName, subject } =
200
+ typeof filter === "string"
201
+ ? { flowName: filter, subject: undefined }
202
+ : { flowName: filter?.flowName, subject: filter?.subject };
203
+
204
+ // Filter surface accepts a flow *name* for ergonomics — resolve it to
205
+ // the canonical URI before the SHACL query, since the record stores
206
+ // the URI (James PR #929 R5). Unknown name → no matches (short-circuit
207
+ // with an empty result rather than issuing a bare-name query that
208
+ // would silently return nothing anyway).
209
+ const where: Record<string, string> = {};
210
+ if (flowName !== undefined) {
211
+ const flow = await perspective.getFlow(flowName);
212
+ if (!flow) return [];
213
+ where.flowUri = flow.flowUri;
214
+ }
215
+ if (subject !== undefined) where.subject = subject;
216
+
217
+ // "Shape not found" on a perspective that has never minted a flow
218
+ // instance is a no-op read, not an error — the executor throws for a
219
+ // missing SHACL shape and there is no side-effect-free way to ask
220
+ // "does this class exist". Return `[]` on that specific case; rethrow
221
+ // anything else so real infra failures don't get swallowed.
222
+ //
223
+ // Regex covers every message the executor + client stack raises for
224
+ // an unregistered class:
225
+ // "No SHACL shape stored for class 'FlowInstance'." (executor RPC)
226
+ // "Shape not found" (older Rust path)
227
+ // "class not registered" / "not registered" (TS Ad4mModel guard)
228
+ let records: FlowInstanceRecord[];
229
+ try {
230
+ records =
231
+ Object.keys(where).length > 0
232
+ ? await FlowInstanceRecord.findAll(perspective, { where })
233
+ : await FlowInstanceRecord.findAll(perspective);
234
+ } catch (e) {
235
+ const msg = e instanceof Error ? e.message : String(e);
236
+ if (
237
+ /no shacl shape stored|shape not found|class not registered|not registered/i.test(
238
+ msg,
239
+ )
240
+ ) {
241
+ return [];
242
+ }
243
+ throw e;
244
+ }
245
+
246
+ // Pair each record with its parsed SHACLFlow. Cache lookups by
247
+ // flow-URI so `getFlow` fires at most once per distinct flow —
248
+ // matters when a perspective has hundreds of instances against
249
+ // one shape.
250
+ //
251
+ // The URI stored on the record is `${namespace}${name}Flow`
252
+ // (see SHACLFlow.flowUri) — recovering the name for `getFlow`
253
+ // means stripping the namespace + the `Flow` suffix. Records that
254
+ // don't parse this way are treated as stale and skipped.
255
+ const shapesByUri = new Map<string, SHACLFlow>();
256
+ const wrappers: FlowInstance[] = [];
257
+ for (const record of records) {
258
+ let shape = shapesByUri.get(record.flowUri);
259
+ if (!shape) {
260
+ const name = flowNameFromUri(record.flowUri);
261
+ if (!name) continue;
262
+ const loaded = await perspective.getFlow(name);
263
+ if (!loaded || loaded.flowUri !== record.flowUri) {
264
+ // Stale record — the flow it references was unregistered,
265
+ // or a different flow now owns that name.
266
+ continue;
267
+ }
268
+ shape = loaded;
269
+ shapesByUri.set(record.flowUri, shape);
270
+ }
271
+ wrappers.push(FlowInstance.wrap(perspective, shape, record));
272
+ }
273
+ return wrappers;
274
+ }
275
+
276
+ // ── Read accessors ────────────────────────────────────────────────────
277
+
278
+ /**
279
+ * URI of the on-graph `FlowInstance` node — `ad4m://flow/instance/{id}`.
280
+ *
281
+ * Sourced from `Ad4mModel`'s synthesised `baseExpression`, which for
282
+ * `FlowInstanceRecord` *is* the instance's own URI (the value
283
+ * `FlowTransitionProposal.flowInstance` references).
284
+ */
285
+ get uri(): string {
286
+ return (this.record as any).baseExpression as string;
287
+ }
288
+
289
+ /**
290
+ * URI of the base expression this flow runs on — matches the
291
+ * `SHACLFlow.inputTypes` that {@link PerspectiveProxy.availableFlows}
292
+ * would greenlight for this expression.
293
+ */
294
+ get subject(): string {
295
+ return this.record.subject;
296
+ }
297
+
298
+ /**
299
+ * Human-readable flow name — the display label. Sourced from the paired
300
+ * `SHACLFlow.name`, not from the record (which stores the URI as its
301
+ * canonical identity — see FlowInstanceRecord's docstring for why).
302
+ */
303
+ get flowName(): string {
304
+ return this.shape.name;
305
+ }
306
+
307
+ /** Flow URI — the on-graph discriminator, collision-free across modules. */
308
+ get flowUri(): string {
309
+ return this.record.flowUri;
310
+ }
311
+
312
+ /** Name of the state this instance is currently in. */
313
+ get currentStateName(): string {
314
+ return this.record.currentState;
315
+ }
316
+
317
+ /**
318
+ * ISO-8601 (epoch millis after Ad4mModel hydration) start time.
319
+ * Returns `undefined` when hydration didn't produce a `createdAt`
320
+ * — rare, but not fatal.
321
+ */
322
+ get startedAtMillis(): number | undefined {
323
+ const v = (this.record as any).createdAt;
324
+ return typeof v === "number" ? v : undefined;
325
+ }
326
+
327
+ /**
328
+ * The `FlowState` object on the shape matching `currentStateName`.
329
+ * Throws when the record's state name is not declared on the flow —
330
+ * that's a "stale FlowInstance whose flow was edited under it" bug,
331
+ * not a silent-fail case.
332
+ */
333
+ get currentState(): FlowState {
334
+ const s = this.shape.states.find((x) => x.name === this.currentStateName);
335
+ if (!s) {
336
+ throw new Error(
337
+ `FlowInstance ${this.uri}: currentState "${this.currentStateName}" is not declared on flow "${this.flowName}". ` +
338
+ `Known states: ${this.shape.states.map((x) => x.name).join(", ") || "(none)"}`,
339
+ );
340
+ }
341
+ return s;
342
+ }
343
+
344
+ /**
345
+ * Every `FlowTransition` on the shape whose `fromState` matches
346
+ * `currentStateName`. Order preserved from the shape.
347
+ *
348
+ * Empty when the current state is terminal (no outgoing transitions).
349
+ */
350
+ get availableTransitions(): FlowTransition[] {
351
+ return this.shape.transitions.filter((t) => t.fromState === this.currentStateName);
352
+ }
353
+
354
+ /**
355
+ * All `FlowTransitionProposal` records targeting this instance's URI.
356
+ *
357
+ * Uses the SDNA identity discriminator (`ad4m://flow/instance` predicate)
358
+ * for the where-filter — one SPARQL round-trip, no client-side
359
+ * filtering.
360
+ *
361
+ * Note: the consensus engine (slice 10.6) will start writing these; today
362
+ * they only exist when a client wrote one directly (or a test seeded one).
363
+ */
364
+ async proposals(): Promise<FlowTransitionProposal[]> {
365
+ return FlowTransitionProposal.findAll(this.perspective, {
366
+ where: { flowInstance: this.uri },
367
+ });
368
+ }
369
+ }