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

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 (55) hide show
  1. package/lib/index.cjs +817 -65
  2. package/lib/index.js +814 -66
  3. package/lib/src/ai/AIClient.d.ts +13 -0
  4. package/lib/src/ai/AIClient.js +15 -0
  5. package/lib/src/ai/AITypes.d.ts +5 -0
  6. package/lib/src/index.js +2 -0
  7. package/lib/src/model/Ad4mModel.d.ts +6 -1
  8. package/lib/src/model/Ad4mModel.js +41 -6
  9. package/lib/src/model/ModelQueryBuilder.d.ts +47 -3
  10. package/lib/src/model/ModelQueryBuilder.js +97 -6
  11. package/lib/src/model/query-common.d.ts +10 -1
  12. package/lib/src/model/query-common.js +16 -0
  13. package/lib/src/model/query-sparql.d.ts +11 -0
  14. package/lib/src/model/query-sparql.js +93 -1
  15. package/lib/src/model/query-utils.js +16 -0
  16. package/lib/src/model/shacl-gen.js +12 -0
  17. package/lib/src/model/types.d.ts +320 -3
  18. package/lib/src/model/types.js +9 -0
  19. package/lib/src/perspectives/AutoProcessor.d.ts +8 -0
  20. package/lib/src/perspectives/FlowInstance.d.ts +176 -12
  21. package/lib/src/perspectives/FlowInstance.js +77 -13
  22. package/lib/src/perspectives/FlowModels.d.ts +40 -9
  23. package/lib/src/perspectives/FlowModels.js +59 -13
  24. package/lib/src/perspectives/PerspectiveClient.d.ts +18 -0
  25. package/lib/src/perspectives/PerspectiveClient.js +30 -0
  26. package/lib/src/perspectives/PerspectiveProxy.d.ts +69 -2
  27. package/lib/src/perspectives/PerspectiveProxy.js +157 -7
  28. package/lib/src/perspectives/WakerSubscriptionManager.d.ts +55 -5
  29. package/lib/src/perspectives/WakerSubscriptionManager.js +183 -8
  30. package/lib/src/shacl/SHACLFlow.d.ts +43 -0
  31. package/package.json +1 -1
  32. package/src/ai/AIClient.ts +16 -0
  33. package/src/ai/AITypes.ts +5 -0
  34. package/src/index.ts +2 -0
  35. package/src/model/Ad4mModel.test.ts +442 -0
  36. package/src/model/Ad4mModel.ts +39 -7
  37. package/src/model/ModelQueryBuilder.ts +101 -10
  38. package/src/model/query-common.ts +20 -1
  39. package/src/model/query-sparql.test.ts +115 -0
  40. package/src/model/query-sparql.ts +97 -1
  41. package/src/model/query-utils.ts +18 -0
  42. package/src/model/relation-filtering.test.ts +7 -0
  43. package/src/model/shacl-gen.ts +12 -0
  44. package/src/model/shacl-roundtrip.test.ts +71 -0
  45. package/src/model/types-typed-query.test.ts +42 -0
  46. package/src/model/types.ts +316 -6
  47. package/src/perspectives/AutoProcessor.ts +8 -0
  48. package/src/perspectives/FlowInstance.ts +194 -13
  49. package/src/perspectives/FlowModels.ts +53 -13
  50. package/src/perspectives/PerspectiveClient.ts +62 -0
  51. package/src/perspectives/PerspectiveProxy.test.ts +272 -0
  52. package/src/perspectives/PerspectiveProxy.ts +163 -7
  53. package/src/perspectives/WakerSubscriptionManager.test.ts +199 -0
  54. package/src/perspectives/WakerSubscriptionManager.ts +197 -9
  55. package/src/shacl/SHACLFlow.ts +44 -0
package/lib/index.js CHANGED
@@ -2093,6 +2093,18 @@ interpretationHint) {
2093
2093
  const propMeta = properties[propName];
2094
2094
  if (!propMeta.through)
2095
2095
  continue; // Skip properties without predicates
2096
+ // `@BelongsToOne`/`@BelongsToMany` register in both maps: the relation
2097
+ // registry describes the edge, and `applyPropertyMetadata` marks the
2098
+ // accessor read-only so the non-owning side gets no setter. Both loops
2099
+ // then emitted a shape for it, so an inverse relation appeared twice in
2100
+ // the generated SHACL — once thinly, from here, and once with its target
2101
+ // class, polymorphism and ordering, from the relation loop below.
2102
+ //
2103
+ // The relation loop is the complete description, so this one stands
2104
+ // aside. Skipping by presence in the relation map rather than by kind
2105
+ // keeps it right for any future decorator that registers in both.
2106
+ if (allRelationsMeta[propName])
2107
+ continue;
2096
2108
  const propShape = {
2097
2109
  name: propName,
2098
2110
  path: propMeta.through,
@@ -3983,7 +3995,7 @@ var __classPrivateFieldGet$a = (undefined && undefined.__classPrivateFieldGet) |
3983
3995
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
3984
3996
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
3985
3997
  };
3986
- var _QuerySubscriptionProxy_instances, _QuerySubscriptionProxy_uuid, _QuerySubscriptionProxy_subscriptionId, _QuerySubscriptionProxy_client, _QuerySubscriptionProxy_callbacks, _QuerySubscriptionProxy_keepaliveTimer, _QuerySubscriptionProxy_unsubscribe, _QuerySubscriptionProxy_reconnectUnsub, _QuerySubscriptionProxy_latestResult, _QuerySubscriptionProxy_disposed, _QuerySubscriptionProxy_initialized, _QuerySubscriptionProxy_initResolve, _QuerySubscriptionProxy_initReject, _QuerySubscriptionProxy_initTimeoutId, _QuerySubscriptionProxy_query, _QuerySubscriptionProxy_generation, _QuerySubscriptionProxy_deliverResult, _QuerySubscriptionProxy_startKeepalive, _QuerySubscriptionProxy_notifyCallbacks, _PerspectiveProxy_handle, _PerspectiveProxy_client, _PerspectiveProxy_perspectiveLinkAddedCallbacks, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, _PerspectiveProxy_perspectiveSyncStateChangeCallbacks, _PerspectiveProxy_ensuredSubjectClasses;
3998
+ var _QuerySubscriptionProxy_instances, _QuerySubscriptionProxy_uuid, _QuerySubscriptionProxy_subscriptionId, _QuerySubscriptionProxy_client, _QuerySubscriptionProxy_callbacks, _QuerySubscriptionProxy_keepaliveTimer, _QuerySubscriptionProxy_unsubscribe, _QuerySubscriptionProxy_reconnectUnsub, _QuerySubscriptionProxy_latestResult, _QuerySubscriptionProxy_disposed, _QuerySubscriptionProxy_initialized, _QuerySubscriptionProxy_initResolve, _QuerySubscriptionProxy_initReject, _QuerySubscriptionProxy_initTimeoutId, _QuerySubscriptionProxy_query, _QuerySubscriptionProxy_generation, _QuerySubscriptionProxy_deliverResult, _QuerySubscriptionProxy_startKeepalive, _QuerySubscriptionProxy_notifyCallbacks, _PerspectiveProxy_handle, _PerspectiveProxy_client, _PerspectiveProxy_perspectiveLinkAddedCallbacks, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, _PerspectiveProxy_perspectiveSyncStateChangeCallbacks, _PerspectiveProxy_ensuredSubjectClasses, _PerspectiveProxy_overlaysInFlight;
3987
3999
  /** Extract namespace prefix from a URI (everything up to and including the last / or #) */
3988
4000
  function extractNamespaceFromUri(uri) {
3989
4001
  const hashIdx = uri.lastIndexOf('#');
@@ -4475,6 +4487,10 @@ class PerspectiveProxy {
4475
4487
  _PerspectiveProxy_perspectiveLinkUpdatedCallbacks.set(this, void 0);
4476
4488
  _PerspectiveProxy_perspectiveSyncStateChangeCallbacks.set(this, void 0);
4477
4489
  _PerspectiveProxy_ensuredSubjectClasses.set(this, new Set()
4490
+ /** The `interpretationOverlays()` RPC currently in flight, shared by concurrent callers. */
4491
+ );
4492
+ /** The `interpretationOverlays()` RPC currently in flight, shared by concurrent callers. */
4493
+ _PerspectiveProxy_overlaysInFlight.set(this, null
4478
4494
  /**
4479
4495
  * Creates a new PerspectiveProxy instance.
4480
4496
  * Note: Don't create this directly, use ad4m.perspective.add() instead.
@@ -4689,9 +4705,28 @@ class PerspectiveProxy {
4689
4705
  /**
4690
4706
  * Pending interpretation overlays on this perspective — LLM suggestions the
4691
4707
  * §4 divergence gate staged rather than applied, awaiting human accept/reject.
4708
+ *
4709
+ * Concurrent callers share one in-flight RPC. Nothing is kept after it
4710
+ * settles, so every call made after that fetches from the executor again.
4711
+ * {@link acceptInterpretation} and {@link rejectInterpretation} detach the
4712
+ * in-flight RPC, so a read issued after they resolve never joins a read
4713
+ * that started before the write.
4714
+ * Each caller gets its own copy of the array.
4692
4715
  */
4693
4716
  async interpretationOverlays() {
4694
- return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").interpretationOverlays(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid);
4717
+ if (__classPrivateFieldGet$a(this, _PerspectiveProxy_overlaysInFlight, "f")) {
4718
+ return [...(await __classPrivateFieldGet$a(this, _PerspectiveProxy_overlaysInFlight, "f"))];
4719
+ }
4720
+ const pending = __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").interpretationOverlays(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid);
4721
+ __classPrivateFieldSet$a(this, _PerspectiveProxy_overlaysInFlight, pending, "f");
4722
+ try {
4723
+ return [...(await pending)];
4724
+ }
4725
+ finally {
4726
+ if (__classPrivateFieldGet$a(this, _PerspectiveProxy_overlaysInFlight, "f") === pending) {
4727
+ __classPrivateFieldSet$a(this, _PerspectiveProxy_overlaysInFlight, null, "f");
4728
+ }
4729
+ }
4695
4730
  }
4696
4731
  /**
4697
4732
  * Accept an interpretation overlay's suggestion(s): the LLM's staged value
@@ -4699,7 +4734,13 @@ class PerspectiveProxy {
4699
4734
  * `property` to accept a single predicate; omit it for the whole base.
4700
4735
  */
4701
4736
  async acceptInterpretation(base, property) {
4702
- return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").acceptInterpretation(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, base, property);
4737
+ try {
4738
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").acceptInterpretation(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, base, property);
4739
+ }
4740
+ finally {
4741
+ // A read already in flight may predate this write; later callers must not join it.
4742
+ __classPrivateFieldSet$a(this, _PerspectiveProxy_overlaysInFlight, null, "f");
4743
+ }
4703
4744
  }
4704
4745
  /**
4705
4746
  * Reject an interpretation overlay's suggestion(s). Omit `property` to reject
@@ -4707,7 +4748,59 @@ class PerspectiveProxy {
4707
4748
  * rejected `update` drops the overlay and keeps the real value.
4708
4749
  */
4709
4750
  async rejectInterpretation(base, property) {
4710
- return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").rejectInterpretation(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, base, property);
4751
+ try {
4752
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").rejectInterpretation(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, base, property);
4753
+ }
4754
+ finally {
4755
+ // A read already in flight may predate this write; later callers must not join it.
4756
+ __classPrivateFieldSet$a(this, _PerspectiveProxy_overlaysInFlight, null, "f");
4757
+ }
4758
+ }
4759
+ /**
4760
+ * `outputs` names the instances a run produces, as `{ className, id }`
4761
+ * pairs, for a transition into a terminal state. The proposal signs a
4762
+ * hash over their content, and a receipt for the run can only speak for
4763
+ * exactly these instances, as they stood at completion. Naming outputs
4764
+ * for a non-terminal state is refused.
4765
+ */
4766
+ async proposeFlowTransition(instanceUri, toState, rationale, outputs) {
4767
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").proposeFlowTransition(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, instanceUri, toState, rationale, outputs);
4768
+ }
4769
+ async acceptFlowProposal(proposalUri) {
4770
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").acceptFlowProposal(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, proposalUri);
4771
+ }
4772
+ /** Withdraw our own links from a proposal; resolves to how many went. */
4773
+ async rejectFlowProposal(proposalUri) {
4774
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").rejectFlowProposal(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, proposalUri);
4775
+ }
4776
+ /**
4777
+ * Re-decide a flow receipt under this perspective's own flow catalogue.
4778
+ * The verdict is three-way — see {@link FlowReceiptVerdict}: branch on
4779
+ * `outcome`, never on a boolean you derive from it.
4780
+ */
4781
+ async verifyFlowReceipt(receipt) {
4782
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").verifyFlowReceipt(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, receipt);
4783
+ }
4784
+ /**
4785
+ * Which instances are, as they stand, valid outputs of `flow`?
4786
+ *
4787
+ * Backed by receipt verification executor-side (see
4788
+ * {@link FlowValidOutput}); an instance without a verifying receipt, or
4789
+ * edited since its run completed, is not listed. The same predicate is
4790
+ * available as a model-query filter:
4791
+ * `where: { producedByFlow: { flow, state? } }`.
4792
+ *
4793
+ * Rejects — never resolves to `[]` — when the flow is not on this
4794
+ * perspective, or when it carries more receipt candidates than the
4795
+ * executor's per-flow budget (256): "could not read every receipt" is not
4796
+ * "no valid outputs". The filter rejects the same way.
4797
+ */
4798
+ async flowValidOutputs(flow, state) {
4799
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").flowValidOutputs(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, flow, state);
4800
+ }
4801
+ /** Mint and store the receipt for a completed flow run. */
4802
+ async mintFlowReceipt(instanceUri) {
4803
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").mintFlowReceipt(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, instanceUri);
4711
4804
  }
4712
4805
  /** Subscribe to this perspective's auto-processor step signals. */
4713
4806
  async addAutoProcessorEventListener(cb) {
@@ -4953,11 +5046,48 @@ class PerspectiveProxy {
4953
5046
  /**
4954
5047
  * Removes a link from the perspective.
4955
5048
  *
4956
- * @param link - The link to remove
5049
+ * Accepts either a full `LinkExpressionInput` (as returned by `add`) or a bare
5050
+ * `Link` (source/predicate/target only). When a bare Link is passed the method
5051
+ * resolves it to the first stored `LinkExpression` whose source, predicate, and
5052
+ * target match, then removes that expression. A bare Link without a predicate
5053
+ * (or with the constructor's `""` stand-in) matches only stored links that
5054
+ * themselves have no predicate. If no match is found an error is thrown
5055
+ * naming the link so the caller knows what was expected.
5056
+ *
5057
+ * @param link - The link to remove (LinkExpressionInput or bare Link)
4957
5058
  * @param batchId - Optional batch ID to group this operation with others
4958
5059
  */
4959
5060
  async remove(link, batchId) {
4960
- const result = await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").removeLink(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, link, batchId);
5061
+ let resolvedLink;
5062
+ if (!('data' in link) || link.data === undefined) {
5063
+ // bare Link — resolve to stored expression
5064
+ const bare = link;
5065
+ // The Link constructor coerces an absent predicate to "" and the
5066
+ // store reports predicate-less links as predicate null — so ""
5067
+ // and undefined both mean "no predicate" here, and neither may
5068
+ // widen the query: dropping the filter would resolve (and
5069
+ // remove!) an arbitrary source→target link under a *different*
5070
+ // predicate. LinkQuery cannot express "predicate is absent", so
5071
+ // in that case we query on source/target only and require the
5072
+ // absence ourselves.
5073
+ const predicateGiven = bare.predicate !== undefined && bare.predicate !== '';
5074
+ const candidates = await this.get(new LinkQuery({
5075
+ source: bare.source || undefined,
5076
+ predicate: predicateGiven ? bare.predicate : undefined,
5077
+ target: bare.target || undefined,
5078
+ }));
5079
+ const matches = predicateGiven
5080
+ ? candidates
5081
+ : candidates.filter(m => !m.data.predicate);
5082
+ if (matches.length === 0) {
5083
+ throw new Error(`PerspectiveProxy.remove: no stored LinkExpression matches Link { source: "${bare.source}", predicate: "${bare.predicate}", target: "${bare.target}" }`);
5084
+ }
5085
+ resolvedLink = matches[0];
5086
+ }
5087
+ else {
5088
+ resolvedLink = link;
5089
+ }
5090
+ const result = await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").removeLink(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, resolvedLink, batchId);
4961
5091
  invalidatePerspectiveCache(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid);
4962
5092
  return result;
4963
5093
  }
@@ -5545,6 +5675,38 @@ class PerspectiveProxy {
5545
5675
  return [];
5546
5676
  }
5547
5677
  }
5678
+ /**
5679
+ * Return the full target-class URIs of every registered SubjectClass.
5680
+ *
5681
+ * Unlike {@link subjectClasses}, which strips the namespace and returns bare
5682
+ * names (`"Space"`, `"Channel"`), this method returns the complete URIs
5683
+ * (`"we://Space"`, `"flux://Channel"`). The full URI is the key that
5684
+ * `load_shape` resolves against, so it is the only collision-safe identifier
5685
+ * — two apps can both declare a class called `"Template"` under different
5686
+ * namespaces, and the bare name cannot distinguish them.
5687
+ *
5688
+ * Callers that need to check whether a *set* of models are already
5689
+ * registered should call this once and test membership against the returned
5690
+ * set, rather than issuing one `queryLinks` per model.
5691
+ *
5692
+ * One `queryLinks` round trip, no executor-side changes.
5693
+ */
5694
+ async subjectClassTargetClasses() {
5695
+ try {
5696
+ const classLinks = await this.get(new LinkQuery({
5697
+ predicate: "rdf://type",
5698
+ target: "ad4m://SubjectClass"
5699
+ }));
5700
+ const uris = classLinks
5701
+ .map(l => l.data.source)
5702
+ .filter(source => source.length > 0);
5703
+ return [...new Set(uris)];
5704
+ }
5705
+ catch (e) {
5706
+ console.warn('subjectClassTargetClasses: lookup failed:', e);
5707
+ return [];
5708
+ }
5709
+ }
5548
5710
  async stringOrTemplateObjectToSubjectClassName(subjectClass) {
5549
5711
  if (typeof subjectClass === "string")
5550
5712
  return subjectClass;
@@ -6267,7 +6429,7 @@ class PerspectiveProxy {
6267
6429
  return subscriptionProxy;
6268
6430
  }
6269
6431
  }
6270
- _PerspectiveProxy_handle = new WeakMap(), _PerspectiveProxy_client = new WeakMap(), _PerspectiveProxy_perspectiveLinkAddedCallbacks = new WeakMap(), _PerspectiveProxy_perspectiveLinkRemovedCallbacks = new WeakMap(), _PerspectiveProxy_perspectiveLinkUpdatedCallbacks = new WeakMap(), _PerspectiveProxy_perspectiveSyncStateChangeCallbacks = new WeakMap(), _PerspectiveProxy_ensuredSubjectClasses = new WeakMap();
6432
+ _PerspectiveProxy_handle = new WeakMap(), _PerspectiveProxy_client = new WeakMap(), _PerspectiveProxy_perspectiveLinkAddedCallbacks = new WeakMap(), _PerspectiveProxy_perspectiveLinkRemovedCallbacks = new WeakMap(), _PerspectiveProxy_perspectiveLinkUpdatedCallbacks = new WeakMap(), _PerspectiveProxy_perspectiveSyncStateChangeCallbacks = new WeakMap(), _PerspectiveProxy_ensuredSubjectClasses = new WeakMap(), _PerspectiveProxy_overlaysInFlight = new WeakMap();
6271
6433
 
6272
6434
  var __classPrivateFieldSet$9 = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
6273
6435
  if (kind === "m") throw new TypeError("Private method is not writable");
@@ -6559,6 +6721,36 @@ class PerspectiveClient {
6559
6721
  async rejectInterpretation(uuid, base, property) {
6560
6722
  return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.rejectInterpretation', { uuid, base, property });
6561
6723
  }
6724
+ async proposeFlowTransition(uuid, instanceUri, toState, rationale, outputs) {
6725
+ return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.proposeFlowTransition', { uuid, instanceUri, toState, rationale, outputs });
6726
+ }
6727
+ async acceptFlowProposal(uuid, proposalUri) {
6728
+ return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.acceptFlowProposal', { uuid, proposalUri });
6729
+ }
6730
+ /**
6731
+ * Withdraw this agent's own links from a proposal. Resolves to how many
6732
+ * were retracted — one for a withdrawn vote, more when retracting a
6733
+ * proposal this agent opened.
6734
+ */
6735
+ async rejectFlowProposal(uuid, proposalUri) {
6736
+ const result = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.rejectFlowProposal', { uuid, proposalUri });
6737
+ return result.retractedLinks;
6738
+ }
6739
+ /** Re-decide a flow receipt under this perspective's own flow catalogue. */
6740
+ async verifyFlowReceipt(uuid, receipt) {
6741
+ return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.verifyFlowReceipt', { uuid, receipt });
6742
+ }
6743
+ /** The instances that are, as they stand, valid outputs of `flow`
6744
+ * (optionally: of runs settled into terminal state `state`). */
6745
+ async flowValidOutputs(uuid, flow, state) {
6746
+ return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.flowValidOutputs', { uuid, flow, state });
6747
+ }
6748
+ /** Mint and store the receipt for a completed flow run. Fails while the
6749
+ * run has not settled into a terminal state, and when an output's
6750
+ * content no longer matches what the quorum committed to. */
6751
+ async mintFlowReceipt(uuid, instanceUri) {
6752
+ return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.mintFlowReceipt', { uuid, instanceUri });
6753
+ }
6562
6754
  /**
6563
6755
  * Subscribe to auto-processor step signals. `cb` fires for every
6564
6756
  * `auto-processor-event` on `uuid` (BatchReady → Claimed/BackedOff/… →
@@ -14923,6 +15115,21 @@ class AIClient {
14923
15115
  async getModels() {
14924
15116
  return __classPrivateFieldGet$2(this, _AIClient_apiClient, "f").call('ai.models');
14925
15117
  }
15118
+ /**
15119
+ * Ask a remote endpoint which models it serves, before adding one.
15120
+ *
15121
+ * Takes the credentials of a model that does not exist yet — a settings
15122
+ * form is being filled in and wants the list to pick from. Rejects when
15123
+ * the endpoint is unreachable or the key is refused, which makes this the
15124
+ * credential check too: without it a bad key surfaces later as a failed
15125
+ * completion carrying an error from a different layer.
15126
+ *
15127
+ * `apiType` defaults to the OpenAI shape, which is what every endpoint
15128
+ * that is not Anthropic speaks.
15129
+ */
15130
+ async discoverModels(baseUrl, apiKey, apiType) {
15131
+ return __classPrivateFieldGet$2(this, _AIClient_apiClient, "f").call('ai.discoverModels', { baseUrl, apiKey, apiType });
15132
+ }
14926
15133
  async addModel(model) {
14927
15134
  return __classPrivateFieldGet$2(this, _AIClient_apiClient, "f").call('ai.addModel', { model: this.serializeModelInput(model) });
14928
15135
  }
@@ -15033,6 +15240,27 @@ class AIClient {
15033
15240
  }
15034
15241
  _AIClient_apiClient = new WeakMap(), _AIClient_transcriptionUnsubscribers = new WeakMap(), _AIClient_pendingStreamIds = new WeakMap();
15035
15242
 
15243
+ /**
15244
+ * Shared type definitions for the Ad4mModel system.
15245
+ *
15246
+ * Extracted into a standalone module so that utility files
15247
+ * (`query-utils.ts`, `decorators.ts`, etc.) can import types without
15248
+ * creating circular runtime dependencies on `Ad4mModel.ts`.
15249
+ */
15250
+ /**
15251
+ * Whether this scope is a traversal rather than a single named parent.
15252
+ *
15253
+ * The other two forms carry `id`; this one carries `ids` and may name several,
15254
+ * so anything reaching for one parent — every write path — has to ask first.
15255
+ */
15256
+ function isTraverseScope(scope) {
15257
+ return 'ids' in scope;
15258
+ }
15259
+ /** Type guard for IncludeProjection objects. */
15260
+ function isIncludeProjection(val) {
15261
+ return typeof val === 'object' && val !== null && 'from' in val;
15262
+ }
15263
+
15036
15264
  /**
15037
15265
  * Shared query helpers used by both the Prolog and SPARQL query pipelines.
15038
15266
  */
@@ -15045,6 +15273,21 @@ _AIClient_apiClient = new WeakMap(), _AIClient_transcriptionUnsubscribers = new
15045
15273
  * - With `field`: direct key lookup
15046
15274
  * - Without `field`: scan for a relation whose `target()` matches `childCtor`
15047
15275
  */
15276
+ /**
15277
+ * Narrow a scope to the one-parent forms, for the paths that write a link.
15278
+ *
15279
+ * A traversal describes a read outward from several anchors. Creating a record
15280
+ * "under" one would have to pick which, and nothing in the scope says — so this
15281
+ * refuses rather than guessing at the first of the list. The executor's write
15282
+ * scopes refuse it for the same reason.
15283
+ */
15284
+ function requireSingleParent(parent) {
15285
+ if (isTraverseScope(parent)) {
15286
+ throw new Error('parent(): a traverse scope describes a read and names no single parent to write under. ' +
15287
+ 'Use { id, predicate } or { model, id } when creating a record under a parent.');
15288
+ }
15289
+ return parent;
15290
+ }
15048
15291
  function resolveParentPredicate(parent, childCtor) {
15049
15292
  // Raw form — explicit predicate
15050
15293
  if ('predicate' in parent)
@@ -15449,6 +15692,68 @@ function hasJsOnlyWhereFilters(metadata, allRelationsMetadata, where) {
15449
15692
  }
15450
15693
  return false;
15451
15694
  }
15695
+ /**
15696
+ * Prepare a `where` for this client-side SPARQL builder: unwrap `{ eq: X }`
15697
+ * to the bare `X`, and refuse a per-link `author`.
15698
+ *
15699
+ * A per-link `author` (nested, `{ agent: { eq: X, author: A } }`, or a
15700
+ * top-level `author` beside link-backed property or relation conditions) is
15701
+ * answered by the executor, which joins each matched link's reifier (#1114). This builder
15702
+ * has no such join, and treating the author as instance-level here would
15703
+ * answer a different, wider question. `findAll()`/`count()` answer it.
15704
+ */
15705
+ function normalizeWhereForSparql(metadata, where) {
15706
+ if (!where)
15707
+ return where;
15708
+ assertNoPerLinkAuthor(metadata, where);
15709
+ const out = {};
15710
+ for (const [key, condition] of Object.entries(where)) {
15711
+ out[key] = unwrapEq(key, condition);
15712
+ }
15713
+ return out;
15714
+ }
15715
+ function isOpsObject(condition) {
15716
+ return typeof condition === "object" && condition !== null && !Array.isArray(condition);
15717
+ }
15718
+ function unwrapEq(key, condition) {
15719
+ if (key === "OR" || key === "AND" || key === "NOT" || !isOpsObject(condition) || condition.eq === undefined) {
15720
+ return condition;
15721
+ }
15722
+ if (Object.keys(condition).some((k) => k !== "eq")) {
15723
+ throw new Error(`where.${key}: \`eq\` cannot be combined with another operator`);
15724
+ }
15725
+ return condition.eq;
15726
+ }
15727
+ function assertNoPerLinkAuthor(metadata, where) {
15728
+ const refuse = (what) => {
15729
+ throw new Error(`buildSPARQLQuery: ${what} is a per-link \`author\`, which the executor answers by ` +
15730
+ "checking who wrote each matched link. This client-side SPARQL builder cannot express " +
15731
+ "it. Use the model query path (findAll/count).");
15732
+ };
15733
+ // A property or a relation with a predicate, as the executor's `is_link_leaf`.
15734
+ const linkBacked = (key) => {
15735
+ const field = metadata.properties[key] ?? metadata.relations?.[key];
15736
+ return !!field && !!field.predicate && !field.getter;
15737
+ };
15738
+ for (const [key, condition] of Object.entries(where)) {
15739
+ if (key === "OR" || key === "AND") {
15740
+ for (const branch of condition ?? [])
15741
+ assertNoPerLinkAuthor(metadata, branch);
15742
+ }
15743
+ else if (key === "NOT") {
15744
+ if (condition)
15745
+ assertNoPerLinkAuthor(metadata, condition);
15746
+ }
15747
+ else if (key === "author") {
15748
+ const sibling = Object.keys(where).find((k) => k !== "author" && linkBacked(k));
15749
+ if (sibling)
15750
+ refuse(`\`author\` beside \`${sibling}\``);
15751
+ }
15752
+ else if (isOpsObject(condition) && condition.author !== undefined) {
15753
+ refuse(`\`${key}.author\``);
15754
+ }
15755
+ }
15756
+ }
15452
15757
  /**
15453
15758
  * Check whether a string value is a well-formed absolute IRI that can be
15454
15759
  * stored verbatim as a link target (raw `NamedNode`) instead of being
@@ -15622,11 +15927,40 @@ function mapPropertyToSPARQLVar(propertyName, metadata) {
15622
15927
  function buildSPARQLQuery(metadata, allRelationsMetadata, query, modelClass) {
15623
15928
  const joinPatterns = [];
15624
15929
  const filterExpressions = [];
15930
+ query = { ...query, where: normalizeWhereForSparql(metadata, query.where) };
15625
15931
  // Parent filter — direct triple pattern
15626
15932
  if (query.parent) {
15627
15933
  const parentPredicate = resolveParentPredicate(query.parent, modelClass);
15628
- joinPatterns.push(`
15934
+ if (isTraverseScope(query.parent)) {
15935
+ const { ids, transitive, direction, limitPerAnchor, levels } = query.parent;
15936
+ // `limitPerAnchor` and `levels` are applied by the executor between
15937
+ // selecting ids and hydrating them, which is a shape this path does not
15938
+ // have — it builds one query and reads the rows. Refused rather than
15939
+ // ignored: quietly returning every reply where five per parent were
15940
+ // asked for — or one unbounded level where a walk was asked for — is a
15941
+ // wrong answer that looks like a right one.
15942
+ if (limitPerAnchor !== undefined) {
15943
+ throw new Error('buildSPARQLQuery: limitPerAnchor is applied by the executor between query phases and ' +
15944
+ 'has no equivalent here. Use the model query path for per-anchor limits.');
15945
+ }
15946
+ if (levels !== undefined) {
15947
+ throw new Error('buildSPARQLQuery: levels is walked by the executor between query phases and ' +
15948
+ 'has no equivalent here. Use the model query path for level walks.');
15949
+ }
15950
+ const anchors = (Array.isArray(ids) ? ids : [ids]).map(iri).join(' ');
15951
+ const path = transitive ? '+' : '';
15952
+ joinPatterns.push(`
15953
+ VALUES ?_anchor { ${anchors} }`);
15954
+ joinPatterns.push(direction === 'in'
15955
+ ? `
15956
+ ?source ${iri(parentPredicate)}${path} ?_anchor .`
15957
+ : `
15958
+ ?_anchor ${iri(parentPredicate)}${path} ?source .`);
15959
+ }
15960
+ else {
15961
+ joinPatterns.push(`
15629
15962
  ${iri(query.parent.id)} ${iri(parentPredicate)} ?source .`);
15963
+ }
15630
15964
  }
15631
15965
  // Required property JOIN patterns — direct triple patterns
15632
15966
  let hasConformance = false;
@@ -16123,6 +16457,23 @@ class ModelQueryBuilder {
16123
16457
  this.queryParams.properties = properties;
16124
16458
  return this;
16125
16459
  }
16460
+ /**
16461
+ * Asks for the individual links behind each instance — author, timestamp
16462
+ * and proof per link — under `instance.__links`. See `Query.links`.
16463
+ *
16464
+ * @param keys - Property / relation names, or absolute predicate IRIs
16465
+ * @returns The query builder for chaining
16466
+ *
16467
+ * @example
16468
+ * ```typescript
16469
+ * const [post] = await Post.query(perspective).links(["comments"]).get();
16470
+ * post.__links!.comments.map((l) => l.timestamp); // when each comment was attached
16471
+ * ```
16472
+ */
16473
+ links(keys) {
16474
+ this.queryParams.links = keys;
16475
+ return this;
16476
+ }
16126
16477
  /**
16127
16478
  * Controls whether SPARQL property getters are evaluated during hydration.
16128
16479
  *
@@ -16145,6 +16496,42 @@ class ModelQueryBuilder {
16145
16496
  this.queryParams.deepQuery = enabled;
16146
16497
  return this;
16147
16498
  }
16499
+ /**
16500
+ * Reads instances as they exist in links of one status only.
16501
+ *
16502
+ * `'shared'` leaves out every Local link, both from the values returned and
16503
+ * from what decides which instances are returned. Use it when the data is
16504
+ * shown to another user. `'local'` is the converse: it returns only
16505
+ * instances flagged in a Local link, so a Local note on a card flagged only
16506
+ * in a Shared link is read without `linkStatus`, not under `'local'`.
16507
+ * See {@link Query.linkStatus}.
16508
+ *
16509
+ * @param status - `'shared'` or `'local'`
16510
+ * @returns The query builder for chaining
16511
+ *
16512
+ * @example
16513
+ * ```typescript
16514
+ * const cards = await Card.query(perspective).linkStatus('shared').get();
16515
+ * ```
16516
+ */
16517
+ linkStatus(status) {
16518
+ this.queryParams.linkStatus = status;
16519
+ return this;
16520
+ }
16521
+ /**
16522
+ * Also hydrate from links whose signature did not verify.
16523
+ *
16524
+ * Off by default: the executor withholds unverified links. Turn it on only
16525
+ * to *display* an unverified claim, never for data you act on. See
16526
+ * {@link Query.includeUnverified}.
16527
+ *
16528
+ * @param enabled - Whether to include unverified links (default: true)
16529
+ * @returns The query builder for chaining
16530
+ */
16531
+ includeUnverified(enabled = true) {
16532
+ this.queryParams.includeUnverified = enabled;
16533
+ return this;
16534
+ }
16148
16535
  /**
16149
16536
  * Specifies which relations to eager-load (hydrate into model instances).
16150
16537
  *
@@ -16285,13 +16672,10 @@ class ModelQueryBuilder {
16285
16672
  const unsubscribe = this.perspective.client.subscribeToQueryUpdates(subscriptionId, (rawResult) => {
16286
16673
  try {
16287
16674
  const results = parseResults(rawResult);
16288
- console.debug(`[ModelQueryBuilder.subscribe] Update received for ${subscriptionId}: ${results.length} instances`);
16289
16675
  const fp = buildFingerprint(results);
16290
16676
  if (fp === lastResultFingerprint) {
16291
- console.debug(`[ModelQueryBuilder.subscribe] Fingerprint unchanged, skipping callback`);
16292
16677
  return;
16293
16678
  }
16294
- console.debug(`[ModelQueryBuilder.subscribe] Fingerprint changed, calling callback with ${results.length} results`);
16295
16679
  lastResultFingerprint = fp;
16296
16680
  callback(results);
16297
16681
  }
@@ -16560,15 +16944,56 @@ class ModelQueryBuilder {
16560
16944
  offset: pageSize * (pageNumber - 1),
16561
16945
  count: true,
16562
16946
  };
16947
+ // One read in flight. A dispatch while a read is running sets `pending`
16948
+ // so a fetch always completes after the last dispatch. The generation
16949
+ // counter from #1020 dropped superseded fetches, but ordered them by
16950
+ // start time rather than by how fresh the data they read was — two
16951
+ // back-to-back dispatches could keep the fetch that saw 1 model and
16952
+ // drop the one that saw 2, after which the server has nothing further
16953
+ // to say (issue #1051 / CI: "Paginate callback did not see second model save").
16954
+ // After dispose() no read starts and no result is delivered, including
16955
+ // a read that was already in flight when dispose() ran.
16956
+ let disposed = false;
16957
+ let fetching = false;
16958
+ let pending = false;
16959
+ let coalesced = 0;
16563
16960
  const processResults = async () => {
16564
- const { results, totalCount } = await ctor.executeModelQuery(this.perspective, paginatedQuery, this.modelClassName);
16565
- callback({ results, totalCount, pageSize, pageNumber });
16961
+ if (disposed)
16962
+ return;
16963
+ if (fetching) {
16964
+ pending = true;
16965
+ coalesced++;
16966
+ return;
16967
+ }
16968
+ fetching = true;
16969
+ try {
16970
+ const { results, totalCount } = await ctor.executeModelQuery(this.perspective, paginatedQuery, this.modelClassName);
16971
+ if (!disposed)
16972
+ callback({ results, totalCount, pageSize, pageNumber });
16973
+ }
16974
+ finally {
16975
+ fetching = false;
16976
+ if (pending) {
16977
+ const dispatches = coalesced;
16978
+ pending = false;
16979
+ coalesced = 0;
16980
+ // Whether a trailing fetch actually starts is decided by the entry
16981
+ // guard at the top of processResults, which returns when disposed.
16982
+ // Log only what that guard will let through, or the dispose path
16983
+ // announces a fetch it then drops.
16984
+ if (!disposed) {
16985
+ console.debug(`[ModelQueryBuilder.paginateSubscribe] ${dispatches} dispatch(es) during read for ${subscriptionId}, coalesced into one trailing fetch`);
16986
+ }
16987
+ // Detached from the caller's promise: needs its own handler, or a
16988
+ // rejection here is unhandled.
16989
+ processResults().catch(e => console.error('Paginate subscription error:', e));
16990
+ }
16991
+ }
16566
16992
  };
16567
16993
  const unsubscribe = this.perspective.client.subscribeToQueryUpdates(subscriptionId, (rawResult) => {
16568
16994
  console.debug(`[ModelQueryBuilder.paginateSubscribe] Update received for ${subscriptionId}, re-fetching paginated data...`);
16569
16995
  processResults().catch(e => console.error('Paginate subscription error:', e));
16570
16996
  });
16571
- let disposed = false;
16572
16997
  let keepaliveTimer;
16573
16998
  let resubscribeAttempts = 0;
16574
16999
  const MAX_RESUBSCRIBE_ATTEMPTS = 5;
@@ -17536,7 +17961,33 @@ class Ad4mModel {
17536
17961
  const queryInput = {};
17537
17962
  if (query.parent) {
17538
17963
  const parentPredicate = resolveParentPredicate(query.parent, this);
17539
- queryInput.parent = { id: query.parent.id, predicate: parentPredicate };
17964
+ // A traversal keeps its own shape on the wire: the executor reads `ids`,
17965
+ // and flattening it to one `id` here is how a request for a whole level
17966
+ // would quietly become a request for one parent's children.
17967
+ //
17968
+ // Its fields are named rather than spread, because `model` — the class
17969
+ // itself — is how the scope may name its predicate, and that is a
17970
+ // constructor, not something to put in a query variable. The predicate is
17971
+ // resolved above; what travels is the result.
17972
+ if (isTraverseScope(query.parent)) {
17973
+ const t = query.parent;
17974
+ const traverse = {
17975
+ ids: t.ids,
17976
+ predicate: parentPredicate,
17977
+ };
17978
+ if (t.transitive !== undefined)
17979
+ traverse.transitive = t.transitive;
17980
+ if (t.direction !== undefined)
17981
+ traverse.direction = t.direction;
17982
+ if (t.limitPerAnchor !== undefined)
17983
+ traverse.limitPerAnchor = t.limitPerAnchor;
17984
+ if (t.levels !== undefined)
17985
+ traverse.levels = t.levels;
17986
+ queryInput.parent = traverse;
17987
+ }
17988
+ else {
17989
+ queryInput.parent = { id: query.parent.id, predicate: parentPredicate };
17990
+ }
17540
17991
  }
17541
17992
  if (query.properties)
17542
17993
  queryInput.properties = query.properties;
@@ -17598,7 +18049,13 @@ class Ad4mModel {
17598
18049
  queryInput.limit = query.limit;
17599
18050
  if (query.count !== undefined)
17600
18051
  queryInput.count = query.count;
18052
+ if (query.links)
18053
+ queryInput.links = query.links;
17601
18054
  queryInput.deepQuery = query.deepQuery ?? true;
18055
+ if (query.linkStatus != null)
18056
+ queryInput.linkStatus = query.linkStatus;
18057
+ if (query.includeUnverified !== undefined)
18058
+ queryInput.includeUnverified = query.includeUnverified;
17602
18059
  // Conformance getters, where filters, and target shapes for includes
17603
18060
  // are all resolved by the executor from the perspective's SHACL triples
17604
18061
  // — no client-side pre-computation is needed any more.
@@ -18308,9 +18765,10 @@ class Ad4mModel {
18308
18765
  if (options?.parent && !options?.batchId) {
18309
18766
  const batchId = await perspective.createBatch();
18310
18767
  await instance.save(batchId);
18311
- const predicate = resolveParentPredicate(options.parent, this);
18768
+ const parent = requireSingleParent(options.parent);
18769
+ const predicate = resolveParentPredicate(parent, this);
18312
18770
  const link = new Link({
18313
- source: options.parent.id,
18771
+ source: parent.id,
18314
18772
  predicate,
18315
18773
  target: instance.id,
18316
18774
  });
@@ -18324,9 +18782,10 @@ class Ad4mModel {
18324
18782
  await instance.save(options?.batchId);
18325
18783
  // Create parent → child link if a parent scope was provided
18326
18784
  if (options?.parent) {
18327
- const predicate = resolveParentPredicate(options.parent, this);
18785
+ const parent = requireSingleParent(options.parent);
18786
+ const predicate = resolveParentPredicate(parent, this);
18328
18787
  const link = new Link({
18329
- source: options.parent.id,
18788
+ source: parent.id,
18330
18789
  predicate,
18331
18790
  target: instance.id,
18332
18791
  });
@@ -19123,14 +19582,14 @@ InterpretationOverlay = __decorate$1([
19123
19582
  * Querying:
19124
19583
  * const pending = await FlowTransitionProposal.findAll(perspective);
19125
19584
  *
19126
- * Slice 5/7 of the flow-implementation arc (design doc §4.2). The Rust
19127
- * engine does not yet mint these — that lands with the consensus firing
19128
- * work in a later PR arc. This class defines the on-graph shape so:
19129
- * - clients can build UI over proposals immediately (Deliberation demo);
19130
- * - the SDNA-parity test locks TS/Rust drift the moment the JSON exists
19131
- * (`rust-executor/src/perspectives/hardwired_sdna/flow_transition_proposal.json`);
19132
- * - the engine can start writing into this shape when consensus lands
19133
- * without touching the client-side surface.
19585
+ * Slice 5/7 of the flow-implementation arc (design doc §4.2). The Rust engine
19586
+ * mints these as of #987 — see `flow_classes.rs` (`mint_proposal`, URIs at
19587
+ * `ad4m://flow/proposal/{id}`) — and reads them back in
19588
+ * `flow_instance/atom.rs`. A UI mints or joins them through
19589
+ * `FlowInstance.proposeTransition`. This class is the client-side mirror:
19590
+ * - clients build UI over proposals without knowing the raw link predicates;
19591
+ * - the SDNA-parity test locks TS/Rust drift against
19592
+ * `rust-executor/src/perspectives/hardwired_sdna/flow_transition_proposal.json`.
19134
19593
  */
19135
19594
  var __decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
19136
19595
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
@@ -19144,9 +19603,12 @@ var __metadata = (undefined && undefined.__metadata) || function (k, v) {
19144
19603
  // ── FlowTransitionProposal ──────────────────────────────────────────────────
19145
19604
  // Mirrors the Rust hardwired `flow_transition_proposal.json` SDNA (once wired
19146
19605
  // on the engine side; see file header). One node per proposed transition; the
19147
- // URI is `ad4m://flow/proposal/<uuid>` when the engine mints it, but the class
19148
- // carries no URI-format constraint — apps constructing proposals directly may
19149
- // choose any URI they can defend as unique.
19606
+ // URI the engine mints is `ad4m://flow/proposal/<hash>` — the content address
19607
+ // of the proposer-signed fields under the `nonce` (#1108). The class carries
19608
+ // no URI-format constraint, but a proposal whose URI is not that content
19609
+ // address (including any app-chosen URI) is not engine-visible: co-signatures
19610
+ // name the URI, so the engine only counts proposals whose URI commits to
19611
+ // their fields.
19150
19612
  let FlowTransitionProposal = class FlowTransitionProposal extends Ad4mModel {
19151
19613
  constructor() {
19152
19614
  super(...arguments);
@@ -19179,6 +19641,31 @@ let FlowTransitionProposal = class FlowTransitionProposal extends Ad4mModel {
19179
19641
  * no rich-object type; the engine parses it back into a map.
19180
19642
  */
19181
19643
  this.evidenceHashes = "";
19644
+ /**
19645
+ * The instances the proposer names as the run's outputs. Written only on
19646
+ * a proposal into a terminal state; one link per output, ordering not
19647
+ * significant. Each entry is the canonical JSON text of a
19648
+ * `{ className, id }` pair (`FlowOutputRef`); `JSON.parse` it to read one.
19649
+ */
19650
+ this.outputs = [];
19651
+ /**
19652
+ * SHA-256 (hex) over the named outputs' content (each instance as
19653
+ * `model_query` returns it through its class), signed by the proposer
19654
+ * next to the evidence seal. Co-signers load the outputs and recompute it
19655
+ * before voting, and a flow receipt's output preimages must hash to it.
19656
+ * Empty on a proposal into a non-terminal state.
19657
+ */
19658
+ this.outputsHash = "";
19659
+ /**
19660
+ * The proposer's uniqueness salt for this proposal's content-addressed
19661
+ * URI (`ad4m://flow/proposal/<hash>`; the hash covers the instance, the
19662
+ * edge, the seal, the outputs commitment, the proposer DID and this
19663
+ * nonce). The engine writes a UUID. A proposal without one — or whose URI
19664
+ * does not match its own signed fields — is not engine-visible:
19665
+ * co-signatures name the URI, so the URI must commit to what they sign
19666
+ * (#1108).
19667
+ */
19668
+ this.nonce = "";
19182
19669
  // "When was this proposal written?" is answered by `Ad4mModel`'s built-in
19183
19670
  // `createdAt`, synthesized on hydration from the earliest link timestamp
19184
19671
  // of the proposal's own links (all written together during create_subject).
@@ -19208,6 +19695,18 @@ __decorate([
19208
19695
  Property({ through: "ad4m://flow/evidence_hashes", required: true }),
19209
19696
  __metadata("design:type", String)
19210
19697
  ], FlowTransitionProposal.prototype, "evidenceHashes", void 0);
19698
+ __decorate([
19699
+ HasMany({ through: "ad4m://flow/output", datatype: "xsd:string" }),
19700
+ __metadata("design:type", Array)
19701
+ ], FlowTransitionProposal.prototype, "outputs", void 0);
19702
+ __decorate([
19703
+ Property({ through: "ad4m://flow/outputs_hash" }),
19704
+ __metadata("design:type", String)
19705
+ ], FlowTransitionProposal.prototype, "outputsHash", void 0);
19706
+ __decorate([
19707
+ Property({ through: "ad4m://flow/nonce" }),
19708
+ __metadata("design:type", String)
19709
+ ], FlowTransitionProposal.prototype, "nonce", void 0);
19211
19710
  __decorate([
19212
19711
  Optional({ through: "ad4m://flow/run_uri" }),
19213
19712
  __metadata("design:type", String)
@@ -19267,7 +19766,13 @@ let FlowInstanceRecord = class FlowInstanceRecord extends Ad4mModel {
19267
19766
  * on read.
19268
19767
  */
19269
19768
  this.subject = "";
19270
- /** Name of the state the flow is currently in. */
19769
+ /**
19770
+ * The state name this replica's executor last derived for the flow — a
19771
+ * per-replica cache written as a `local` link, never the authority (the
19772
+ * fold over the signed proposals is). Optional on the shape: a row that
19773
+ * synced in from a peer carries no value until the local consensus pass
19774
+ * has run, so an empty string means "not yet derived here".
19775
+ */
19271
19776
  this.currentState = "";
19272
19777
  // "When was this flow started?" is answered by `Ad4mModel`'s built-in
19273
19778
  // `createdAt`, synthesized on hydration from the earliest link timestamp
@@ -19283,7 +19788,7 @@ __decorate([
19283
19788
  __metadata("design:type", String)
19284
19789
  ], FlowInstanceRecord.prototype, "subject", void 0);
19285
19790
  __decorate([
19286
- Property({ through: "ad4m://flow/current_state", required: true }),
19791
+ Property({ through: "ad4m://flow/current_state", local: true }),
19287
19792
  __metadata("design:type", String)
19288
19793
  ], FlowInstanceRecord.prototype, "currentState", void 0);
19289
19794
  FlowInstanceRecord = __decorate([
@@ -19309,7 +19814,7 @@ FlowInstanceRecord = __decorate([
19309
19814
  * than the `wrap` escape hatch, which exists for tests that already own
19310
19815
  * a matched (record, shape) pair.
19311
19816
  *
19312
- * # What's here vs. what's coming in §7 / slice 10.6
19817
+ * # What's here, and what is still absent
19313
19818
  *
19314
19819
  * Read surface (implemented today, PR #929):
19315
19820
  * - `uri`, `subject`, `flowName`, `currentStateName`, `startedAtMillis`
@@ -19320,12 +19825,31 @@ FlowInstanceRecord = __decorate([
19320
19825
  * - `proposals()` — queries `FlowTransitionProposal` records that
19321
19826
  * target this instance's URI.
19322
19827
  *
19323
- * Mutations + subscriptions (`proposeTransition`, `accept`, `reject`,
19324
- * `fireAction`, `onStateChange`, `onProposalAdded`, `onProposalResolved`)
19325
- * land with the consensus-engine slice (§4.3 / slice 10.6). Rather than
19326
- * ship them as `throw new Error("not yet")` stubs — which is a type-level
19327
- * lie the caller only discovers at runtime — they are simply absent from
19328
- * this class until the engine is wired.
19828
+ * - `acceptProposal()` / `rejectProposal()` — the consensus write API:
19829
+ * accept counts your DID toward the flow's consensusRule and fires the
19830
+ * transition at quorum; reject withdraws only the links you signed and
19831
+ * resolves to how many went. Reject is not a cancel — another agent's
19832
+ * proposal is theirs, and because state is recomputed from the links
19833
+ * present now, withdrawing a vote that had settled an edge moves the
19834
+ * flow back to where it stood before it.
19835
+ *
19836
+ * - `proposeTransition()` — the manual write path: propose an edge as this
19837
+ * agent, or co-sign the equivalent proposal another agent already opened.
19838
+ * Its `FlowProposeResult` is what tells queued from no-op from stalled.
19839
+ *
19840
+ * Still absent (rather than shipped as `throw new Error("not yet")`
19841
+ * stubs): `fireAction`, and the subscriptions (`onStateChange`,
19842
+ * `onProposalAdded`, `onProposalResolved`) — they land with the
19843
+ * subscription-topic slice.
19844
+ *
19845
+ * ## The guard-free rule
19846
+ *
19847
+ * A state with no `requires` guard is **never** proposed by the engine, on
19848
+ * any replica, ever — `flow_evaluator`'s auto-proposal composer skips it by
19849
+ * design. Nothing in the graph implies a human started work; they said so.
19850
+ * So states like "in progress" and "in review" only ever advance through
19851
+ * `proposeTransition`. This is a permanent contract, not a gap: wire the
19852
+ * button, or the instance sits there.
19329
19853
  */
19330
19854
  /**
19331
19855
  * Extract the flow's human-readable name from its canonical URI.
@@ -19388,9 +19912,15 @@ class FlowInstance {
19388
19912
  *
19389
19913
  * The returned wrapper carries the parsed `SHACLFlow` alongside the
19390
19914
  * on-graph record, so `currentState` / `availableTransitions` /
19391
- * `proposals` accessors work without further round-trips. The consensus
19392
- * engine (slice 10.6) will read the record's `currentState` when it
19393
- * fires transitions.
19915
+ * `proposals` accessors work without further round-trips.
19916
+ *
19917
+ * The record's `currentState` is a per-replica cache the consensus engine
19918
+ * writes as a local link. It is read back only for display — the cache-first
19919
+ * path in `gather_active_flow_contexts` fills the state rendered into LLM
19920
+ * context — and **never as authority**: anything that decides something
19921
+ * (the fold, the mint pass) derives state from the signed links present now
19922
+ * and does not consult the cache. Treat it as a display hint, not as the
19923
+ * flow's state.
19394
19924
  *
19395
19925
  * @param perspective - The perspective the flow instance lives on
19396
19926
  * @param flowName - Name of a `SHACLFlow` already registered on the perspective
@@ -19550,7 +20080,7 @@ class FlowInstance {
19550
20080
  * `FlowTransitionProposal.flowInstance` references).
19551
20081
  */
19552
20082
  get uri() {
19553
- return this.record.baseExpression;
20083
+ return this.record.id;
19554
20084
  }
19555
20085
  /**
19556
20086
  * URI of the base expression this flow runs on — matches the
@@ -19615,14 +20145,53 @@ class FlowInstance {
19615
20145
  * for the where-filter — one SPARQL round-trip, no client-side
19616
20146
  * filtering.
19617
20147
  *
19618
- * Note: the consensus engine (slice 10.6) will start writing these; today
19619
- * they only exist when a client wrote one directly (or a test seeded one).
20148
+ * These are written by the executor's consensus pass when it mints a
20149
+ * transition, and by clients proposing directly. Superseded proposals are
20150
+ * not swept here — a stale one is simply never counted by the fold, and
20151
+ * accepting it fails with a stale-state error.
19620
20152
  */
19621
20153
  async proposals() {
19622
20154
  return FlowTransitionProposal.findAll(this.perspective, {
19623
20155
  where: { flowInstance: this.uri },
19624
20156
  });
19625
20157
  }
20158
+ /**
20159
+ * Propose a flow transition for this instance, as the calling agent.
20160
+ *
20161
+ * The executor evaluates the guard on its own replica, seals the evidence,
20162
+ * and either writes a new proposal or — when an equivalent one is already
20163
+ * open, i.e. another agent pressed the same button first — co-signs that
20164
+ * one. When the resulting vote reaches the target state's
20165
+ * `consensusRule.n`, the transition fires in the same call.
20166
+ *
20167
+ * How to read the result — fired vs. queued vs. no-op vs. stalled — is
20168
+ * documented on {@link FlowProposeResult} itself.
20169
+ *
20170
+ * `outputs` names the instances the run produces, as `{ className, id }`
20171
+ * pairs, for a transition into a terminal state. The proposal signs a hash
20172
+ * over their content, every co-signer recomputes it on its own replica,
20173
+ * and a receipt for the run speaks for exactly these instances as they
20174
+ * stood at completion.
20175
+ *
20176
+ * Throws when `toState` is not reachable from the derived state, when the
20177
+ * target state carries a `requires` guard that is not currently satisfied
20178
+ * on this replica, when the instance is already contested, when `outputs`
20179
+ * is given for a non-terminal state or names something that is not an
20180
+ * instance of its class, or
20181
+ * when an open proposal on the same edge names different outputs.
20182
+ */
20183
+ async proposeTransition(toState, rationale, outputs) {
20184
+ return this.perspective.proposeFlowTransition(this.uri, toState, rationale, outputs);
20185
+ }
20186
+ async acceptProposal(proposal) {
20187
+ const uri = typeof proposal === "string" ? proposal : proposal.id;
20188
+ return this.perspective.acceptFlowProposal(uri);
20189
+ }
20190
+ /** Withdraw our own links from a proposal; resolves to how many went. */
20191
+ async rejectProposal(proposal) {
20192
+ const uri = typeof proposal === "string" ? proposal : proposal.id;
20193
+ return this.perspective.rejectFlowProposal(uri);
20194
+ }
19626
20195
  }
19627
20196
 
19628
20197
  /**
@@ -19744,15 +20313,73 @@ function parseLitBoolean(val) {
19744
20313
  /**
19745
20314
  * WakerSubscriptionManager — manages live query subscriptions for the waker.
19746
20315
  *
19747
- * Lives in core so it can be imported by both the plugin and integration tests
19748
- * without ESM/CJS import issues.
20316
+ * This is the single implementation: it is exported from `@coasys/ad4m` and
20317
+ * used by the integration tests, and the OpenClaw AD4M plugin re-exports this
20318
+ * module (`plugins/ad4m/wakerSubscriptionManager.ts`) rather than carrying its
20319
+ * own copy. Any behaviour change belongs here.
20320
+ */
20321
+ /**
20322
+ * Add a short cause hint to known subscription failures.
20323
+ * The executor needs its main key to register a live query; on a restarted
20324
+ * executor whose wallet was never unlocked this surfaces as a bare 403.
20325
+ */
20326
+ function hintFor(msg) {
20327
+ // "Executor is locked" is the current executor's message; "main key not
20328
+ // found" is what older executors (and unrelated key lookups) say for the
20329
+ // same locked state. Either way the caller cannot fix it themselves: keys
20330
+ // live in memory only, so every restart locks the node again and only its
20331
+ // operator can unlock it.
20332
+ if (/executor is locked/i.test(msg) || /main key not found/i.test(msg)) {
20333
+ return " — the executor is locked (its keys live in memory only, so every restart locks it again). Only the node's operator can unlock it: contact them and ask for unlockAgent, then subscribe again — a pending subscription re-attempts on its own once the node is unlocked";
20334
+ }
20335
+ if (/timed out after \d+ms/i.test(msg)) {
20336
+ return " — the executor accepted the waker's connection but never answered; check that the waker is pointed at the right executor host and API port (executorUrl in the plugin config) and that the node is unlocked";
20337
+ }
20338
+ return "";
20339
+ }
20340
+ /**
20341
+ * Reject `promise` after `ms` instead of waiting forever.
19749
20342
  *
19750
- * NOTE: keep in sync with plugins/ad4m/wakerSubscriptionManager.ts
20343
+ * The pending set only catches rejections. A handshake that hangs — the
20344
+ * executor accepted the socket but never answers — settles nothing, so the
20345
+ * subscription was recorded nowhere and the caller's tool invocation died at
20346
+ * the harness timeout instead (#1016). The underlying promise is left as is:
20347
+ * the caller disposes the proxy, so a late answer backs out on its own.
19751
20348
  */
20349
+ async function withTimeout(promise, ms, message) {
20350
+ let timer;
20351
+ try {
20352
+ return await Promise.race([
20353
+ promise,
20354
+ new Promise((_resolve, reject) => {
20355
+ timer = setTimeout(() => reject(new Error(message)), ms);
20356
+ }),
20357
+ ]);
20358
+ }
20359
+ finally {
20360
+ if (timer)
20361
+ clearTimeout(timer);
20362
+ }
20363
+ }
19752
20364
  class WakerSubscriptionManager {
19753
20365
  constructor(options) {
19754
20366
  this.proxies = new Map();
19755
20367
  this.activeSubscriptions = new Map();
20368
+ /** Subscriptions the executor rejected, waiting to be re-attempted. */
20369
+ this.pendingSubscriptions = new Map();
20370
+ this.retryTimer = null;
20371
+ /**
20372
+ * Cancellation tokens for in-flight `subscribe()` calls.
20373
+ *
20374
+ * `subscribe()` awaits `proxy.subscribe()` and `proxy.initialized`; a
20375
+ * `dispose()` / `disposeAll()` landing during either await used to leave a
20376
+ * live subscription behind, because nothing stopped the resumed call from
20377
+ * registering the proxy in `proxies` / `activeSubscriptions` afterwards.
20378
+ * `epoch` is bumped by `disposeAll()` (which cannot enumerate in-flight
20379
+ * ids), `generations` per id by `dispose()` and by each new `subscribe()`.
20380
+ */
20381
+ this.epoch = 0;
20382
+ this.generations = new Map();
19756
20383
  this.debounceTimers = new Map();
19757
20384
  /** Per-subscription set of already-processed message addresses (for mention subs)
19758
20385
  * or serialized result hash (for channel-messages subs). */
@@ -19764,6 +20391,18 @@ class WakerSubscriptionManager {
19764
20391
  this.onPersist = options.onPersist;
19765
20392
  this.QuerySubscriptionProxyCtor = options.QuerySubscriptionProxy ?? null;
19766
20393
  this.previousSeenMessages = options.previousSeenMessages ?? {};
20394
+ this.retryPendingMs = options.retryPendingMs ?? 30000;
20395
+ this.subscribeTimeoutMs = options.subscribeTimeoutMs ?? 15000;
20396
+ }
20397
+ /** A token identifying this attempt at subscribing `id`. */
20398
+ beginAttempt(id) {
20399
+ const gen = (this.generations.get(id) ?? 0) + 1;
20400
+ this.generations.set(id, gen);
20401
+ return { epoch: this.epoch, gen };
20402
+ }
20403
+ /** Whether this attempt has been superseded by a dispose or a newer one. */
20404
+ isStale(id, token) {
20405
+ return token.epoch !== this.epoch || this.generations.get(id) !== token.gen;
19767
20406
  }
19768
20407
  /**
19769
20408
  * Create a live SPARQL subscription.
@@ -19772,6 +20411,7 @@ class WakerSubscriptionManager {
19772
20411
  async subscribe(sub) {
19773
20412
  // Dispose existing subscription with same id if any
19774
20413
  this.dispose(sub.id, false);
20414
+ const token = this.beginAttempt(sub.id);
19775
20415
  if (!this.QuerySubscriptionProxyCtor) {
19776
20416
  throw new Error("WakerSubscriptionManager: QuerySubscriptionProxy must be provided via constructor options");
19777
20417
  }
@@ -19786,9 +20426,24 @@ class WakerSubscriptionManager {
19786
20426
  if (proxy.initialized && typeof proxy.initialized.catch === "function") {
19787
20427
  proxy.initialized.catch(() => { });
19788
20428
  }
20429
+ // One deadline for the whole handshake: `proxy.subscribe()` and the
20430
+ // `initialized` promise it resolves share the budget, so a hang in either
20431
+ // surfaces as the same loud-but-recoverable failure a rejection does.
20432
+ const budgetMs = this.subscribeTimeoutMs;
20433
+ const startedAt = Date.now();
20434
+ const bounded = (step, what) => budgetMs > 0
20435
+ ? withTimeout(step, Math.max(0, budgetMs - (Date.now() - startedAt)), `${what} timed out after ${budgetMs}ms`)
20436
+ : step;
19789
20437
  try {
19790
- await proxy.subscribe();
19791
- await proxy.initialized;
20438
+ await bounded(proxy.subscribe(), "subscribe handshake");
20439
+ if (this.isStale(sub.id, token)) {
20440
+ try {
20441
+ proxy.dispose();
20442
+ }
20443
+ catch { }
20444
+ return;
20445
+ }
20446
+ await bounded(proxy.initialized, "subscription initialization");
19792
20447
  }
19793
20448
  catch (err) {
19794
20449
  const msg = err?.message ?? String(err);
@@ -19797,12 +20452,36 @@ class WakerSubscriptionManager {
19797
20452
  proxy.dispose();
19798
20453
  }
19799
20454
  catch { }
19800
- // Remove from active state so it doesn't get persisted/retried
20455
+ // A dispose that landed mid-attempt wins: don't re-queue something the
20456
+ // caller has since asked us to forget.
20457
+ if (this.isStale(sub.id, token))
20458
+ return;
20459
+ // Remove from active state — it is not listening, so it must not be
20460
+ // reported as active or persisted as if it were.
19801
20461
  this.activeSubscriptions.delete(sub.id);
19802
20462
  this.seenMessages.delete(sub.id);
19803
20463
  this.persist();
19804
- return; // Don't throw — caller should not crash
20464
+ // Keep it pending and re-attempt: the usual cause (locked wallet, executor
20465
+ // mid-restart, a handshake the executor never answered) clears on its
20466
+ // own, and the caller asked to be enrolled.
20467
+ this.pendingSubscriptions.set(sub.id, sub);
20468
+ this.scheduleRetry();
20469
+ // Throw so callers can report the real outcome. Background callers
20470
+ // (auto-subscribe, restore-on-start) catch and log; the subscribe tools
20471
+ // turn this into an error result instead of a false "Subscribed" reply.
20472
+ throw new Error(`Waker subscription ${sub.id} failed: ${msg}${hintFor(msg)}` +
20473
+ (this.retryPendingMs > 0
20474
+ ? `. Not listening yet — re-attempting every ${Math.round(this.retryPendingMs / 1000)}s; check ad4m_list_waker_subscriptions.`
20475
+ : ""));
20476
+ }
20477
+ if (this.isStale(sub.id, token)) {
20478
+ try {
20479
+ proxy.dispose();
20480
+ }
20481
+ catch { }
20482
+ return;
19805
20483
  }
20484
+ this.pendingSubscriptions.delete(sub.id);
19806
20485
  this.logger.info(`[waker] ${sub.id}: subscription initialized successfully`);
19807
20486
  // Seed from persisted seen messages so we don't re-wake after restart
19808
20487
  const seen = new Set(this.previousSeenMessages[sub.id] ?? []);
@@ -19883,16 +20562,72 @@ class WakerSubscriptionManager {
19883
20562
  }, this.debounceMs));
19884
20563
  }
19885
20564
  });
20565
+ if (this.isStale(sub.id, token)) {
20566
+ try {
20567
+ proxy.dispose();
20568
+ }
20569
+ catch { }
20570
+ return;
20571
+ }
19886
20572
  this.proxies.set(sub.id, proxy);
19887
20573
  this.activeSubscriptions.set(sub.id, sub);
19888
20574
  this.persist();
19889
20575
  this.logger.info(`[waker] Subscription ${sub.id} active (type=${sub.type}, perspective=${sub.perspective})`);
19890
20576
  }
20577
+ /** Arm the re-attempt timer if pending subscriptions are waiting. */
20578
+ scheduleRetry() {
20579
+ if (this.retryPendingMs <= 0)
20580
+ return;
20581
+ if (this.retryTimer || this.pendingSubscriptions.size === 0)
20582
+ return;
20583
+ this.retryTimer = setTimeout(() => {
20584
+ this.retryTimer = null;
20585
+ void this.retryPending();
20586
+ }, this.retryPendingMs);
20587
+ if (typeof this.retryTimer.unref === "function")
20588
+ this.retryTimer.unref();
20589
+ }
20590
+ /**
20591
+ * Re-attempt every subscription the executor rejected.
20592
+ * Each attempt that fails puts itself back into the pending set and re-arms
20593
+ * the timer, so an agent that asked to be subscribed ends up enrolled once
20594
+ * the executor can accept the query.
20595
+ */
20596
+ async retryPending() {
20597
+ const waiting = Array.from(this.pendingSubscriptions.values());
20598
+ if (waiting.length === 0)
20599
+ return;
20600
+ this.logger.info(`[waker] re-attempting ${waiting.length} pending subscription(s)`);
20601
+ const epoch = this.epoch;
20602
+ for (const sub of waiting) {
20603
+ // A disposeAll() between two awaits must stop the whole sweep, and a
20604
+ // dispose() of this id must skip just it.
20605
+ if (epoch !== this.epoch)
20606
+ return;
20607
+ if (!this.pendingSubscriptions.has(sub.id))
20608
+ continue;
20609
+ this.pendingSubscriptions.delete(sub.id);
20610
+ try {
20611
+ await this.subscribe(sub);
20612
+ this.logger.info(`[waker] ${sub.id}: enrolled on re-attempt`);
20613
+ }
20614
+ catch (err) {
20615
+ // subscribe() already logged, re-queued and re-armed the timer.
20616
+ this.logger.debug(`[waker] ${sub.id}: still pending — ${err?.message ?? err}`);
20617
+ }
20618
+ }
20619
+ }
20620
+ /** Subscriptions that were rejected and are waiting to be re-attempted. */
20621
+ getPending() {
20622
+ return Array.from(this.pendingSubscriptions.values());
20623
+ }
19891
20624
  /**
19892
20625
  * Dispose a single subscription.
19893
20626
  * @param persist — if false, skip calling onPersist (used during batch cleanup).
19894
20627
  */
19895
20628
  dispose(id, persist = true) {
20629
+ // Invalidate any subscribe() for this id that is still awaiting.
20630
+ this.generations.set(id, (this.generations.get(id) ?? 0) + 1);
19896
20631
  const proxy = this.proxies.get(id);
19897
20632
  if (proxy) {
19898
20633
  try {
@@ -19909,15 +20644,24 @@ class WakerSubscriptionManager {
19909
20644
  this.debounceTimers.delete(id);
19910
20645
  }
19911
20646
  this.activeSubscriptions.delete(id);
20647
+ this.pendingSubscriptions.delete(id);
19912
20648
  this.seenMessages.delete(id);
19913
20649
  if (persist)
19914
20650
  this.persist();
19915
20651
  }
19916
- /** Dispose all active subscriptions. */
20652
+ /** Dispose all active subscriptions and drop anything still pending. */
19917
20653
  disposeAll() {
20654
+ // Bump the epoch first: in-flight subscribe() calls have no proxy in the
20655
+ // map yet, so per-id invalidation alone cannot reach them.
20656
+ this.epoch++;
19918
20657
  for (const [id] of this.proxies) {
19919
20658
  this.dispose(id, false);
19920
20659
  }
20660
+ this.pendingSubscriptions.clear();
20661
+ if (this.retryTimer) {
20662
+ clearTimeout(this.retryTimer);
20663
+ this.retryTimer = null;
20664
+ }
19921
20665
  }
19922
20666
  /** Get all active subscriptions. */
19923
20667
  getActive() {
@@ -20015,18 +20759,6 @@ class SmartLiteral {
20015
20759
  }
20016
20760
  _SmartLiteral_perspective = new WeakMap(), _SmartLiteral_base = new WeakMap();
20017
20761
 
20018
- /**
20019
- * Shared type definitions for the Ad4mModel system.
20020
- *
20021
- * Extracted into a standalone module so that utility files
20022
- * (`query-utils.ts`, `decorators.ts`, etc.) can import types without
20023
- * creating circular runtime dependencies on `Ad4mModel.ts`.
20024
- */
20025
- /** Type guard for IncludeProjection objects. */
20026
- function isIncludeProjection(val) {
20027
- return typeof val === 'object' && val !== null && 'from' in val;
20028
- }
20029
-
20030
20762
  /**
20031
20763
  * Shared query compilation utilities.
20032
20764
  *
@@ -20083,6 +20815,22 @@ function formatQueryValue(value) {
20083
20815
  * @returns A single SPARQL condition string
20084
20816
  */
20085
20817
  function buildWhereCondition(predicate, condition, opts) {
20818
+ // `{ eq: X }` is the bare `X`. A nested `author` is a per-link condition
20819
+ // the executor answers in model queries; a getter's SPARQL has no reifier
20820
+ // join to answer it with, so it is refused rather than dropped (#1114).
20821
+ if (typeof condition === 'object' && condition !== null && !Array.isArray(condition)) {
20822
+ const ops = condition;
20823
+ if (ops.author !== undefined) {
20824
+ throw new Error(`buildWhereCondition: a nested \`author\` on <${predicate}> is a per-link condition ` +
20825
+ 'that only the model query path can answer');
20826
+ }
20827
+ if (ops.eq !== undefined) {
20828
+ if (Object.keys(ops).some((k) => k !== 'eq')) {
20829
+ throw new Error(`buildWhereCondition: \`eq\` on <${predicate}> cannot be combined with another operator`);
20830
+ }
20831
+ condition = ops.eq;
20832
+ }
20833
+ }
20086
20834
  const escapedPredicate = escapeQueryString(predicate);
20087
20835
  // For deterministic-literal properties, values are stored as typed
20088
20836
  // literals like `"X"^^xsd:string` (or the legacy `<literal:string:VALUE>`
@@ -20364,4 +21112,4 @@ const fileToDataUri = ifExpr(exists(path('file_storage://data_base64')))
20364
21112
  .then(concat(literal('data:'), coalesce(path('file_storage://file_type'), literal('image/png')), literal(';base64,'), path('file_storage://data_base64')))
20365
21113
  .else(focus());
20366
21114
 
20367
- export { AIClient, Model as AIModel, AIModelLoadingStatus, AIPromptExamples, AIPromptExamplesInput, AITask, AITaskInput, Ad4mClient, Ad4mModel, Agent, AgentClient, AgentExpression, AgentSignature, AgentStatus, Apps, AuthInfo, AuthInfoInput, AutoProcessorConfig, BelongsToMany, BelongsToOne, Capability, CapabilityInput, ComputeLogEntry, EntanglementProof, EntanglementProofInput, ExceptionInfo, ExceptionType, Expression, ExpressionGeneric, ExpressionGenericInput, ExpressionProof, ExpressionProofInput, ExpressionRef, ExpressionRendered, Flag, FlowInstance, FlowInstanceRecord, FlowTransitionProposal, HasMany, HasOne, HostingUserInfo, IDBCache, Icon, ImportResult, ImportStats, InteractionCall, InteractionMeta, InteractionParameter, InterpretationOverlay, InterpretationRun, LanguageExpression, LanguageHandle, LanguageLanguageInput, LanguageMeta, LanguageMetaInput, LanguageMetaInternal, LanguageRef, Link, LinkExpression, LinkExpressionInput, LinkExpressionMutations, LinkExpressionUpdated, LinkInput, LinkMutations, LinkQuery, Literal, LocalModel, LocalModelInput, Model$1 as Model, ModelApi, ModelApiInput, ModelInput, ModelQueryBuilder, Neighbourhood, NeighbourhoodExpression, NeighbourhoodProxy, Notification, NotificationInput, NullCache, OnlineAgent, Optional, PaymentRequestResult, Perspective, PerspectiveDiff, PerspectiveDiffExpression, PerspectiveExpression, PerspectiveHandle, PerspectiveInput, PerspectiveProxy, PerspectiveState, PerspectiveUnsignedInput, Property, QuerySubscriptionProxy, ReadOnly, Resource, ResourceInput, RpcError as RestError, RpcError, RuntimeInfo, SHACLFlow, SHACLShape, SMART_LITERAL_CONTENT_PREDICATE, SentMessage, SmartLiteral, TokenizerSource, TokenizerSourceInput, TriggeredNotification, UserCreationResult, UserStatistics, VerificationRequestResult, VoiceActivityParamsInput, WakerSubscriptionManager, buildConformanceFilter, buildModelFromJSONSchema, buildPaginationSubquery, buildSDNA, buildSHACL, buildSPARQLQuery, buildWhereCondition, capSentence, clearQueryCache, coalesce, compileWhereClause, concat, createPersistentCache, determineNamespace, determinePredicate, effectiveLiteralStorage, escapeQueryString, exists, exprRef2String, fileToDataUri, fn, focus, formatList, formatQueryValue, formatSPARQLValue, getCachedResult, getDefaultValueForType, getMemoizedSHACL, getPropertiesMetadata, getPropertyOption, getRelationsMetadata, hasJsOnlyWhereFilters, ifExpr, invalidatePerspectiveCache, isArrayType, isExpression, isIncludeProjection, isLink, isNodeExpression, isNumericType, isObjectType, isSchemaType, linkEqual, literal, looksLikeUri, normalizeNamespaceString, normalizeSchemaType, normalizeValue, parseExprUrl, parseLit, parseLitBoolean, parseLitNumber, parseSparqlCount, path, queryCacheSize, resolveParentPredicate, setCachedResult, setPropertyRegistryEntry, setRelationRegistryEntry, typeDefsString, valueToLiteralIri };
21115
+ export { AIClient, Model as AIModel, AIModelLoadingStatus, AIPromptExamples, AIPromptExamplesInput, AITask, AITaskInput, Ad4mClient, Ad4mModel, Agent, AgentClient, AgentExpression, AgentSignature, AgentStatus, Apps, AuthInfo, AuthInfoInput, AutoProcessorConfig, BelongsToMany, BelongsToOne, Capability, CapabilityInput, ComputeLogEntry, EntanglementProof, EntanglementProofInput, ExceptionInfo, ExceptionType, Expression, ExpressionGeneric, ExpressionGenericInput, ExpressionProof, ExpressionProofInput, ExpressionRef, ExpressionRendered, Flag, FlowInstance, FlowInstanceRecord, FlowTransitionProposal, HasMany, HasOne, HostingUserInfo, IDBCache, Icon, ImportResult, ImportStats, InteractionCall, InteractionMeta, InteractionParameter, InterpretationOverlay, InterpretationRun, LanguageExpression, LanguageHandle, LanguageLanguageInput, LanguageMeta, LanguageMetaInput, LanguageMetaInternal, LanguageRef, Link, LinkExpression, LinkExpressionInput, LinkExpressionMutations, LinkExpressionUpdated, LinkInput, LinkMutations, LinkQuery, Literal, LocalModel, LocalModelInput, Model$1 as Model, ModelApi, ModelApiInput, ModelInput, ModelQueryBuilder, Neighbourhood, NeighbourhoodExpression, NeighbourhoodProxy, Notification, NotificationInput, NullCache, OnlineAgent, Optional, PaymentRequestResult, Perspective, PerspectiveDiff, PerspectiveDiffExpression, PerspectiveExpression, PerspectiveHandle, PerspectiveInput, PerspectiveProxy, PerspectiveState, PerspectiveUnsignedInput, Property, QuerySubscriptionProxy, ReadOnly, Resource, ResourceInput, RpcError as RestError, RpcError, RuntimeInfo, SHACLFlow, SHACLShape, SMART_LITERAL_CONTENT_PREDICATE, SentMessage, SmartLiteral, TokenizerSource, TokenizerSourceInput, TriggeredNotification, UserCreationResult, UserStatistics, VerificationRequestResult, VoiceActivityParamsInput, WakerSubscriptionManager, buildConformanceFilter, buildModelFromJSONSchema, buildPaginationSubquery, buildSDNA, buildSHACL, buildSPARQLQuery, buildWhereCondition, capSentence, clearQueryCache, coalesce, compileWhereClause, concat, createPersistentCache, determineNamespace, determinePredicate, effectiveLiteralStorage, escapeQueryString, exists, exprRef2String, fileToDataUri, fn, focus, formatList, formatQueryValue, formatSPARQLValue, getCachedResult, getDefaultValueForType, getMemoizedSHACL, getPropertiesMetadata, getPropertyOption, getRelationsMetadata, hasJsOnlyWhereFilters, hintFor, ifExpr, invalidatePerspectiveCache, isArrayType, isExpression, isIncludeProjection, isLink, isNodeExpression, isNumericType, isObjectType, isSchemaType, isTraverseScope, linkEqual, literal, looksLikeUri, normalizeNamespaceString, normalizeSchemaType, normalizeValue, normalizeWhereForSparql, parseExprUrl, parseLit, parseLitBoolean, parseLitNumber, parseSparqlCount, path, queryCacheSize, requireSingleParent, resolveParentPredicate, setCachedResult, setPropertyRegistryEntry, setRelationRegistryEntry, typeDefsString, valueToLiteralIri };