@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
@@ -1,4 +1,5 @@
1
1
  import { LinkCallback, PerspectiveClient, SyncStateChangeCallback } from "./PerspectiveClient";
2
+ import type { FlowFireOutcome, FlowMintedReceipt, FlowOutputRef, FlowProposeResult, FlowReceiptVerdict, FlowValidOutput } from "./FlowInstance";
2
3
  import { CallOptions } from "../apiClient";
3
4
  import { Link, LinkExpression, LinkExpressionInput, LinkExpressionMutations, LinkMutations } from "../links/Links";
4
5
  import { LinkQuery } from "./LinkQuery";
@@ -343,6 +344,13 @@ export declare class PerspectiveProxy {
343
344
  /**
344
345
  * Pending interpretation overlays on this perspective — LLM suggestions the
345
346
  * §4 divergence gate staged rather than applied, awaiting human accept/reject.
347
+ *
348
+ * Concurrent callers share one in-flight RPC. Nothing is kept after it
349
+ * settles, so every call made after that fetches from the executor again.
350
+ * {@link acceptInterpretation} and {@link rejectInterpretation} detach the
351
+ * in-flight RPC, so a read issued after they resolve never joins a read
352
+ * that started before the write.
353
+ * Each caller gets its own copy of the array.
346
354
  */
347
355
  interpretationOverlays(): Promise<InterpretationOverlayInfo[]>;
348
356
  /**
@@ -357,6 +365,40 @@ export declare class PerspectiveProxy {
357
365
  * rejected `update` drops the overlay and keeps the real value.
358
366
  */
359
367
  rejectInterpretation(base: string, property?: string): Promise<boolean>;
368
+ /**
369
+ * `outputs` names the instances a run produces, as `{ className, id }`
370
+ * pairs, for a transition into a terminal state. The proposal signs a
371
+ * hash over their content, and a receipt for the run can only speak for
372
+ * exactly these instances, as they stood at completion. Naming outputs
373
+ * for a non-terminal state is refused.
374
+ */
375
+ proposeFlowTransition(instanceUri: string, toState: string, rationale?: string, outputs?: FlowOutputRef[]): Promise<FlowProposeResult>;
376
+ acceptFlowProposal(proposalUri: string): Promise<FlowFireOutcome[]>;
377
+ /** Withdraw our own links from a proposal; resolves to how many went. */
378
+ rejectFlowProposal(proposalUri: string): Promise<number>;
379
+ /**
380
+ * Re-decide a flow receipt under this perspective's own flow catalogue.
381
+ * The verdict is three-way — see {@link FlowReceiptVerdict}: branch on
382
+ * `outcome`, never on a boolean you derive from it.
383
+ */
384
+ verifyFlowReceipt(receipt: object): Promise<FlowReceiptVerdict>;
385
+ /**
386
+ * Which instances are, as they stand, valid outputs of `flow`?
387
+ *
388
+ * Backed by receipt verification executor-side (see
389
+ * {@link FlowValidOutput}); an instance without a verifying receipt, or
390
+ * edited since its run completed, is not listed. The same predicate is
391
+ * available as a model-query filter:
392
+ * `where: { producedByFlow: { flow, state? } }`.
393
+ *
394
+ * Rejects — never resolves to `[]` — when the flow is not on this
395
+ * perspective, or when it carries more receipt candidates than the
396
+ * executor's per-flow budget (256): "could not read every receipt" is not
397
+ * "no valid outputs". The filter rejects the same way.
398
+ */
399
+ flowValidOutputs(flow: string, state?: string): Promise<FlowValidOutput[]>;
400
+ /** Mint and store the receipt for a completed flow run. */
401
+ mintFlowReceipt(instanceUri: string): Promise<FlowMintedReceipt>;
360
402
  /** Subscribe to this perspective's auto-processor step signals. */
361
403
  addAutoProcessorEventListener(cb: (event: AutoProcessorEvent) => void): Promise<void>;
362
404
  /**
@@ -562,10 +604,18 @@ export declare class PerspectiveProxy {
562
604
  /**
563
605
  * Removes a link from the perspective.
564
606
  *
565
- * @param link - The link to remove
607
+ * Accepts either a full `LinkExpressionInput` (as returned by `add`) or a bare
608
+ * `Link` (source/predicate/target only). When a bare Link is passed the method
609
+ * resolves it to the first stored `LinkExpression` whose source, predicate, and
610
+ * target match, then removes that expression. A bare Link without a predicate
611
+ * (or with the constructor's `""` stand-in) matches only stored links that
612
+ * themselves have no predicate. If no match is found an error is thrown
613
+ * naming the link so the caller knows what was expected.
614
+ *
615
+ * @param link - The link to remove (LinkExpressionInput or bare Link)
566
616
  * @param batchId - Optional batch ID to group this operation with others
567
617
  */
568
- remove(link: LinkExpressionInput, batchId?: string): Promise<boolean>;
618
+ remove(link: LinkExpressionInput | Link, batchId?: string): Promise<boolean>;
569
619
  /** Creates a new batch for grouping operations */
570
620
  createBatch(): Promise<string>;
571
621
  /** Commits a batch of operations */
@@ -852,6 +902,23 @@ export declare class PerspectiveProxy {
852
902
  * Uses SHACL-based lookup (Prolog-free implementation).
853
903
  */
854
904
  subjectClasses(): Promise<string[]>;
905
+ /**
906
+ * Return the full target-class URIs of every registered SubjectClass.
907
+ *
908
+ * Unlike {@link subjectClasses}, which strips the namespace and returns bare
909
+ * names (`"Space"`, `"Channel"`), this method returns the complete URIs
910
+ * (`"we://Space"`, `"flux://Channel"`). The full URI is the key that
911
+ * `load_shape` resolves against, so it is the only collision-safe identifier
912
+ * — two apps can both declare a class called `"Template"` under different
913
+ * namespaces, and the bare name cannot distinguish them.
914
+ *
915
+ * Callers that need to check whether a *set* of models are already
916
+ * registered should call this once and test membership against the returned
917
+ * set, rather than issuing one `queryLinks` per model.
918
+ *
919
+ * One `queryLinks` round trip, no executor-side changes.
920
+ */
921
+ subjectClassTargetClasses(): Promise<string[]>;
855
922
  stringOrTemplateObjectToSubjectClassName<T>(subjectClass: T): Promise<string>;
856
923
  /**
857
924
  * Creates a new subject instance of the given subject class
@@ -9,7 +9,7 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
9
9
  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");
10
10
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
11
  };
12
- 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;
12
+ 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;
13
13
  import { Link } from "../links/Links";
14
14
  import { LinkQuery } from "./LinkQuery";
15
15
  import { Literal } from "../Literal";
@@ -508,6 +508,10 @@ export class PerspectiveProxy {
508
508
  _PerspectiveProxy_perspectiveLinkUpdatedCallbacks.set(this, void 0);
509
509
  _PerspectiveProxy_perspectiveSyncStateChangeCallbacks.set(this, void 0);
510
510
  _PerspectiveProxy_ensuredSubjectClasses.set(this, new Set()
511
+ /** The `interpretationOverlays()` RPC currently in flight, shared by concurrent callers. */
512
+ );
513
+ /** The `interpretationOverlays()` RPC currently in flight, shared by concurrent callers. */
514
+ _PerspectiveProxy_overlaysInFlight.set(this, null
511
515
  /**
512
516
  * Creates a new PerspectiveProxy instance.
513
517
  * Note: Don't create this directly, use ad4m.perspective.add() instead.
@@ -722,9 +726,28 @@ export class PerspectiveProxy {
722
726
  /**
723
727
  * Pending interpretation overlays on this perspective — LLM suggestions the
724
728
  * §4 divergence gate staged rather than applied, awaiting human accept/reject.
729
+ *
730
+ * Concurrent callers share one in-flight RPC. Nothing is kept after it
731
+ * settles, so every call made after that fetches from the executor again.
732
+ * {@link acceptInterpretation} and {@link rejectInterpretation} detach the
733
+ * in-flight RPC, so a read issued after they resolve never joins a read
734
+ * that started before the write.
735
+ * Each caller gets its own copy of the array.
725
736
  */
726
737
  async interpretationOverlays() {
727
- return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").interpretationOverlays(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid);
738
+ if (__classPrivateFieldGet(this, _PerspectiveProxy_overlaysInFlight, "f")) {
739
+ return [...(await __classPrivateFieldGet(this, _PerspectiveProxy_overlaysInFlight, "f"))];
740
+ }
741
+ const pending = __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").interpretationOverlays(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid);
742
+ __classPrivateFieldSet(this, _PerspectiveProxy_overlaysInFlight, pending, "f");
743
+ try {
744
+ return [...(await pending)];
745
+ }
746
+ finally {
747
+ if (__classPrivateFieldGet(this, _PerspectiveProxy_overlaysInFlight, "f") === pending) {
748
+ __classPrivateFieldSet(this, _PerspectiveProxy_overlaysInFlight, null, "f");
749
+ }
750
+ }
728
751
  }
729
752
  /**
730
753
  * Accept an interpretation overlay's suggestion(s): the LLM's staged value
@@ -732,7 +755,13 @@ export class PerspectiveProxy {
732
755
  * `property` to accept a single predicate; omit it for the whole base.
733
756
  */
734
757
  async acceptInterpretation(base, property) {
735
- return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").acceptInterpretation(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, base, property);
758
+ try {
759
+ return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").acceptInterpretation(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, base, property);
760
+ }
761
+ finally {
762
+ // A read already in flight may predate this write; later callers must not join it.
763
+ __classPrivateFieldSet(this, _PerspectiveProxy_overlaysInFlight, null, "f");
764
+ }
736
765
  }
737
766
  /**
738
767
  * Reject an interpretation overlay's suggestion(s). Omit `property` to reject
@@ -740,7 +769,59 @@ export class PerspectiveProxy {
740
769
  * rejected `update` drops the overlay and keeps the real value.
741
770
  */
742
771
  async rejectInterpretation(base, property) {
743
- return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").rejectInterpretation(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, base, property);
772
+ try {
773
+ return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").rejectInterpretation(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, base, property);
774
+ }
775
+ finally {
776
+ // A read already in flight may predate this write; later callers must not join it.
777
+ __classPrivateFieldSet(this, _PerspectiveProxy_overlaysInFlight, null, "f");
778
+ }
779
+ }
780
+ /**
781
+ * `outputs` names the instances a run produces, as `{ className, id }`
782
+ * pairs, for a transition into a terminal state. The proposal signs a
783
+ * hash over their content, and a receipt for the run can only speak for
784
+ * exactly these instances, as they stood at completion. Naming outputs
785
+ * for a non-terminal state is refused.
786
+ */
787
+ async proposeFlowTransition(instanceUri, toState, rationale, outputs) {
788
+ return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").proposeFlowTransition(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, instanceUri, toState, rationale, outputs);
789
+ }
790
+ async acceptFlowProposal(proposalUri) {
791
+ return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").acceptFlowProposal(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, proposalUri);
792
+ }
793
+ /** Withdraw our own links from a proposal; resolves to how many went. */
794
+ async rejectFlowProposal(proposalUri) {
795
+ return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").rejectFlowProposal(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, proposalUri);
796
+ }
797
+ /**
798
+ * Re-decide a flow receipt under this perspective's own flow catalogue.
799
+ * The verdict is three-way — see {@link FlowReceiptVerdict}: branch on
800
+ * `outcome`, never on a boolean you derive from it.
801
+ */
802
+ async verifyFlowReceipt(receipt) {
803
+ return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").verifyFlowReceipt(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, receipt);
804
+ }
805
+ /**
806
+ * Which instances are, as they stand, valid outputs of `flow`?
807
+ *
808
+ * Backed by receipt verification executor-side (see
809
+ * {@link FlowValidOutput}); an instance without a verifying receipt, or
810
+ * edited since its run completed, is not listed. The same predicate is
811
+ * available as a model-query filter:
812
+ * `where: { producedByFlow: { flow, state? } }`.
813
+ *
814
+ * Rejects — never resolves to `[]` — when the flow is not on this
815
+ * perspective, or when it carries more receipt candidates than the
816
+ * executor's per-flow budget (256): "could not read every receipt" is not
817
+ * "no valid outputs". The filter rejects the same way.
818
+ */
819
+ async flowValidOutputs(flow, state) {
820
+ return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").flowValidOutputs(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, flow, state);
821
+ }
822
+ /** Mint and store the receipt for a completed flow run. */
823
+ async mintFlowReceipt(instanceUri) {
824
+ return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").mintFlowReceipt(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, instanceUri);
744
825
  }
745
826
  /** Subscribe to this perspective's auto-processor step signals. */
746
827
  async addAutoProcessorEventListener(cb) {
@@ -986,11 +1067,48 @@ export class PerspectiveProxy {
986
1067
  /**
987
1068
  * Removes a link from the perspective.
988
1069
  *
989
- * @param link - The link to remove
1070
+ * Accepts either a full `LinkExpressionInput` (as returned by `add`) or a bare
1071
+ * `Link` (source/predicate/target only). When a bare Link is passed the method
1072
+ * resolves it to the first stored `LinkExpression` whose source, predicate, and
1073
+ * target match, then removes that expression. A bare Link without a predicate
1074
+ * (or with the constructor's `""` stand-in) matches only stored links that
1075
+ * themselves have no predicate. If no match is found an error is thrown
1076
+ * naming the link so the caller knows what was expected.
1077
+ *
1078
+ * @param link - The link to remove (LinkExpressionInput or bare Link)
990
1079
  * @param batchId - Optional batch ID to group this operation with others
991
1080
  */
992
1081
  async remove(link, batchId) {
993
- const result = await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").removeLink(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, link, batchId);
1082
+ let resolvedLink;
1083
+ if (!('data' in link) || link.data === undefined) {
1084
+ // bare Link — resolve to stored expression
1085
+ const bare = link;
1086
+ // The Link constructor coerces an absent predicate to "" and the
1087
+ // store reports predicate-less links as predicate null — so ""
1088
+ // and undefined both mean "no predicate" here, and neither may
1089
+ // widen the query: dropping the filter would resolve (and
1090
+ // remove!) an arbitrary source→target link under a *different*
1091
+ // predicate. LinkQuery cannot express "predicate is absent", so
1092
+ // in that case we query on source/target only and require the
1093
+ // absence ourselves.
1094
+ const predicateGiven = bare.predicate !== undefined && bare.predicate !== '';
1095
+ const candidates = await this.get(new LinkQuery({
1096
+ source: bare.source || undefined,
1097
+ predicate: predicateGiven ? bare.predicate : undefined,
1098
+ target: bare.target || undefined,
1099
+ }));
1100
+ const matches = predicateGiven
1101
+ ? candidates
1102
+ : candidates.filter(m => !m.data.predicate);
1103
+ if (matches.length === 0) {
1104
+ throw new Error(`PerspectiveProxy.remove: no stored LinkExpression matches Link { source: "${bare.source}", predicate: "${bare.predicate}", target: "${bare.target}" }`);
1105
+ }
1106
+ resolvedLink = matches[0];
1107
+ }
1108
+ else {
1109
+ resolvedLink = link;
1110
+ }
1111
+ const result = await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").removeLink(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, resolvedLink, batchId);
994
1112
  invalidatePerspectiveCache(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid);
995
1113
  return result;
996
1114
  }
@@ -1578,6 +1696,38 @@ export class PerspectiveProxy {
1578
1696
  return [];
1579
1697
  }
1580
1698
  }
1699
+ /**
1700
+ * Return the full target-class URIs of every registered SubjectClass.
1701
+ *
1702
+ * Unlike {@link subjectClasses}, which strips the namespace and returns bare
1703
+ * names (`"Space"`, `"Channel"`), this method returns the complete URIs
1704
+ * (`"we://Space"`, `"flux://Channel"`). The full URI is the key that
1705
+ * `load_shape` resolves against, so it is the only collision-safe identifier
1706
+ * — two apps can both declare a class called `"Template"` under different
1707
+ * namespaces, and the bare name cannot distinguish them.
1708
+ *
1709
+ * Callers that need to check whether a *set* of models are already
1710
+ * registered should call this once and test membership against the returned
1711
+ * set, rather than issuing one `queryLinks` per model.
1712
+ *
1713
+ * One `queryLinks` round trip, no executor-side changes.
1714
+ */
1715
+ async subjectClassTargetClasses() {
1716
+ try {
1717
+ const classLinks = await this.get(new LinkQuery({
1718
+ predicate: "rdf://type",
1719
+ target: "ad4m://SubjectClass"
1720
+ }));
1721
+ const uris = classLinks
1722
+ .map(l => l.data.source)
1723
+ .filter(source => source.length > 0);
1724
+ return [...new Set(uris)];
1725
+ }
1726
+ catch (e) {
1727
+ console.warn('subjectClassTargetClasses: lookup failed:', e);
1728
+ return [];
1729
+ }
1730
+ }
1581
1731
  async stringOrTemplateObjectToSubjectClassName(subjectClass) {
1582
1732
  if (typeof subjectClass === "string")
1583
1733
  return subjectClass;
@@ -2303,4 +2453,4 @@ export class PerspectiveProxy {
2303
2453
  return subscriptionProxy;
2304
2454
  }
2305
2455
  }
2306
- _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();
2456
+ _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();
@@ -1,10 +1,10 @@
1
1
  /**
2
2
  * WakerSubscriptionManager — manages live query subscriptions for the waker.
3
3
  *
4
- * Lives in core so it can be imported by both the plugin and integration tests
5
- * without ESM/CJS import issues.
6
- *
7
- * NOTE: keep in sync with plugins/ad4m/wakerSubscriptionManager.ts
4
+ * This is the single implementation: it is exported from `@coasys/ad4m` and
5
+ * used by the integration tests, and the OpenClaw AD4M plugin re-exports this
6
+ * module (`plugins/ad4m/wakerSubscriptionManager.ts`) rather than carrying its
7
+ * own copy. Any behaviour change belongs here.
8
8
  */
9
9
  export interface WakerSubscription {
10
10
  id: string;
@@ -43,7 +43,25 @@ export interface WakerSubscriptionManagerOptions {
43
43
  previousSeenMessages?: Record<string, string[]>;
44
44
  /** Optional: provide QuerySubscriptionProxy class directly (avoids require("@coasys/ad4m") at runtime). */
45
45
  QuerySubscriptionProxy?: any;
46
+ /** How long to wait before re-attempting a subscription the executor rejected
47
+ * (default 30000). 0 disables re-attempts. */
48
+ retryPendingMs?: number;
49
+ /**
50
+ * How long the executor gets to answer the subscribe handshake before the
51
+ * attempt is abandoned and queued for re-attempt (default 15000). 0 removes
52
+ * the bound. Covers both `proxy.subscribe()` and `proxy.initialized`: when
53
+ * the executor accepts the socket but never answers, neither settles, and
54
+ * without a deadline the subscription ended up neither active nor pending,
55
+ * so the re-attempt cycle never saw it (#1016).
56
+ */
57
+ subscribeTimeoutMs?: number;
46
58
  }
59
+ /**
60
+ * Add a short cause hint to known subscription failures.
61
+ * The executor needs its main key to register a live query; on a restarted
62
+ * executor whose wallet was never unlocked this surfaces as a bare 403.
63
+ */
64
+ export declare function hintFor(msg: string): string;
47
65
  export declare class WakerSubscriptionManager {
48
66
  private perspectiveClient;
49
67
  private logger;
@@ -52,24 +70,56 @@ export declare class WakerSubscriptionManager {
52
70
  private onPersist?;
53
71
  private QuerySubscriptionProxyCtor;
54
72
  private previousSeenMessages;
73
+ private retryPendingMs;
74
+ private subscribeTimeoutMs;
55
75
  private proxies;
56
76
  private activeSubscriptions;
77
+ /** Subscriptions the executor rejected, waiting to be re-attempted. */
78
+ private pendingSubscriptions;
79
+ private retryTimer;
80
+ /**
81
+ * Cancellation tokens for in-flight `subscribe()` calls.
82
+ *
83
+ * `subscribe()` awaits `proxy.subscribe()` and `proxy.initialized`; a
84
+ * `dispose()` / `disposeAll()` landing during either await used to leave a
85
+ * live subscription behind, because nothing stopped the resumed call from
86
+ * registering the proxy in `proxies` / `activeSubscriptions` afterwards.
87
+ * `epoch` is bumped by `disposeAll()` (which cannot enumerate in-flight
88
+ * ids), `generations` per id by `dispose()` and by each new `subscribe()`.
89
+ */
90
+ private epoch;
91
+ private generations;
57
92
  private debounceTimers;
58
93
  /** Per-subscription set of already-processed message addresses (for mention subs)
59
94
  * or serialized result hash (for channel-messages subs). */
60
95
  private seenMessages;
61
96
  constructor(options: WakerSubscriptionManagerOptions);
97
+ /** A token identifying this attempt at subscribing `id`. */
98
+ private beginAttempt;
99
+ /** Whether this attempt has been superseded by a dispose or a newer one. */
100
+ private isStale;
62
101
  /**
63
102
  * Create a live SPARQL subscription.
64
103
  * If a subscription with the same id already exists, it is disposed first.
65
104
  */
66
105
  subscribe(sub: WakerSubscription): Promise<void>;
106
+ /** Arm the re-attempt timer if pending subscriptions are waiting. */
107
+ private scheduleRetry;
108
+ /**
109
+ * Re-attempt every subscription the executor rejected.
110
+ * Each attempt that fails puts itself back into the pending set and re-arms
111
+ * the timer, so an agent that asked to be subscribed ends up enrolled once
112
+ * the executor can accept the query.
113
+ */
114
+ retryPending(): Promise<void>;
115
+ /** Subscriptions that were rejected and are waiting to be re-attempted. */
116
+ getPending(): WakerSubscription[];
67
117
  /**
68
118
  * Dispose a single subscription.
69
119
  * @param persist — if false, skip calling onPersist (used during batch cleanup).
70
120
  */
71
121
  dispose(id: string, persist?: boolean): void;
72
- /** Dispose all active subscriptions. */
122
+ /** Dispose all active subscriptions and drop anything still pending. */
73
123
  disposeAll(): void;
74
124
  /** Get all active subscriptions. */
75
125
  getActive(): WakerSubscription[];