@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 { PerspectiveProxy, QuerySubscriptionProxy } from './PerspectiveProxy';
2
+ import { Link, LinkExpression } from '../links/Links';
2
3
 
3
4
  function createMockPerspectiveClient(): any {
4
5
  return {
@@ -529,3 +530,274 @@ describe('QuerySubscriptionProxy', () => {
529
530
  expect(liveCallbacks).toBe(0);
530
531
  });
531
532
  });
533
+
534
+ describe('PerspectiveProxy.subjectClassTargetClasses', () => {
535
+ function mockLink(source: string) {
536
+ return { data: { source, predicate: 'rdf://type', target: 'ad4m://SubjectClass' } };
537
+ }
538
+
539
+ function proxyWithLinks(links: any[]): PerspectiveProxy {
540
+ const mockClient: any = {
541
+ ...createMockPerspectiveClient(),
542
+ queryLinks: jest.fn().mockResolvedValue(links),
543
+ };
544
+ return createProxy(mockClient);
545
+ }
546
+
547
+ it('returns full URIs, not stripped names', async () => {
548
+ const proxy = proxyWithLinks([
549
+ mockLink('we://Space'),
550
+ mockLink('flux://Channel'),
551
+ mockLink('recipe://Recipe'),
552
+ ]);
553
+
554
+ const result = await proxy.subjectClassTargetClasses();
555
+
556
+ expect(result).toContain('we://Space');
557
+ expect(result).toContain('flux://Channel');
558
+ expect(result).toContain('recipe://Recipe');
559
+ expect(result).toHaveLength(3);
560
+ });
561
+
562
+ it('deduplicates URIs', async () => {
563
+ const proxy = proxyWithLinks([
564
+ mockLink('we://Space'),
565
+ mockLink('we://Space'),
566
+ ]);
567
+
568
+ expect(await proxy.subjectClassTargetClasses()).toEqual(['we://Space']);
569
+ });
570
+
571
+ it('filters out empty sources', async () => {
572
+ const proxy = proxyWithLinks([
573
+ mockLink('we://Space'),
574
+ mockLink(''),
575
+ ]);
576
+
577
+ expect(await proxy.subjectClassTargetClasses()).toEqual(['we://Space']);
578
+ });
579
+
580
+ it('returns an empty array when no classes are registered', async () => {
581
+ const proxy = proxyWithLinks([]);
582
+ expect(await proxy.subjectClassTargetClasses()).toEqual([]);
583
+ });
584
+
585
+ it('returns an empty array on error', async () => {
586
+ const mockClient: any = {
587
+ ...createMockPerspectiveClient(),
588
+ queryLinks: jest.fn().mockRejectedValue(new Error('network error')),
589
+ };
590
+ const proxy = createProxy(mockClient);
591
+
592
+ expect(await proxy.subjectClassTargetClasses()).toEqual([]);
593
+ });
594
+ });
595
+
596
+ describe('PerspectiveProxy.interpretationOverlays coalescing', () => {
597
+ const overlayA = [{ base: 'a', kind: 'create', inferred: [] }];
598
+ const overlayB = [{ base: 'b', kind: 'update', inferred: [] }];
599
+
600
+ it('coalesces concurrent reads into one RPC', async () => {
601
+ let resolveFetch: (v: any) => void;
602
+ let fetchCount = 0;
603
+ const mockClient: any = {
604
+ ...createMockPerspectiveClient(),
605
+ interpretationOverlays: jest.fn(() => {
606
+ fetchCount++;
607
+ return new Promise(r => { resolveFetch = r; });
608
+ }),
609
+ };
610
+ const proxy = createProxy(mockClient);
611
+
612
+ const a = proxy.interpretationOverlays();
613
+ const b = proxy.interpretationOverlays();
614
+ resolveFetch!(overlayA);
615
+ expect(await a).toEqual(overlayA);
616
+ expect(await b).toEqual(overlayA);
617
+ expect(fetchCount).toBe(1);
618
+ });
619
+
620
+ it('gives each caller its own copy of the array', async () => {
621
+ let resolveFetch: (v: any) => void;
622
+ const mockClient: any = {
623
+ ...createMockPerspectiveClient(),
624
+ interpretationOverlays: jest.fn(() => new Promise(r => { resolveFetch = r; })),
625
+ };
626
+ const proxy = createProxy(mockClient);
627
+
628
+ const a = proxy.interpretationOverlays();
629
+ const b = proxy.interpretationOverlays();
630
+ resolveFetch!(overlayA);
631
+ const first = await a;
632
+ const second = await b;
633
+ expect(second).not.toBe(first);
634
+ first.length = 0;
635
+ expect(second).toEqual(overlayA);
636
+ expect(overlayA).toHaveLength(1);
637
+ });
638
+
639
+ it('does not cache: a call after the previous one resolved sends a new RPC', async () => {
640
+ let calls = 0;
641
+ const mockClient: any = {
642
+ ...createMockPerspectiveClient(),
643
+ interpretationOverlays: jest.fn(async () => { calls++; return calls === 1 ? overlayA : overlayB; }),
644
+ };
645
+ const proxy = createProxy(mockClient);
646
+
647
+ expect(await proxy.interpretationOverlays()).toEqual(overlayA);
648
+ expect(await proxy.interpretationOverlays()).toEqual(overlayB);
649
+ expect(calls).toBe(2);
650
+ });
651
+
652
+ it('shares a failed RPC with concurrent callers and does not keep it', async () => {
653
+ let calls = 0;
654
+ const mockClient: any = {
655
+ ...createMockPerspectiveClient(),
656
+ interpretationOverlays: jest.fn(async () => {
657
+ calls++;
658
+ if (calls === 1) throw new Error('boom');
659
+ return overlayA;
660
+ }),
661
+ };
662
+ const proxy = createProxy(mockClient);
663
+
664
+ const a = proxy.interpretationOverlays();
665
+ const b = proxy.interpretationOverlays();
666
+ await expect(a).rejects.toThrow('boom');
667
+ await expect(b).rejects.toThrow('boom');
668
+ expect(await proxy.interpretationOverlays()).toEqual(overlayA);
669
+ expect(calls).toBe(2);
670
+ });
671
+
672
+ it('a read after acceptInterpretation resolves does not join an older in-flight RPC', async () => {
673
+ const resolvers: Array<(v: any) => void> = [];
674
+ const mockClient: any = {
675
+ ...createMockPerspectiveClient(),
676
+ interpretationOverlays: jest.fn(() => new Promise(r => { resolvers.push(r); })),
677
+ acceptInterpretation: jest.fn(async () => true),
678
+ };
679
+ const proxy = createProxy(mockClient);
680
+ const before = proxy.interpretationOverlays();
681
+ await proxy.acceptInterpretation('a');
682
+ const after = proxy.interpretationOverlays();
683
+ expect(resolvers.length).toBe(2);
684
+ resolvers[0](overlayA);
685
+ resolvers[1]([]);
686
+ expect(await before).toEqual(overlayA);
687
+ expect(await after).toEqual([]);
688
+ });
689
+
690
+ it('a read after rejectInterpretation resolves does not join an older in-flight RPC', async () => {
691
+ const resolvers: Array<(v: any) => void> = [];
692
+ const mockClient: any = {
693
+ ...createMockPerspectiveClient(),
694
+ interpretationOverlays: jest.fn(() => new Promise(r => { resolvers.push(r); })),
695
+ rejectInterpretation: jest.fn(async () => { throw new Error('reject failed'); }),
696
+ };
697
+ const proxy = createProxy(mockClient);
698
+ const before = proxy.interpretationOverlays();
699
+ // Detaches even when the write throws: it may have landed before the error.
700
+ await expect(proxy.rejectInterpretation('a')).rejects.toThrow('reject failed');
701
+ const after = proxy.interpretationOverlays();
702
+ expect(resolvers.length).toBe(2);
703
+ // The detached RPC settling first must not clear the newer one.
704
+ resolvers[0](overlayA);
705
+ expect(await before).toEqual(overlayA);
706
+ const joiner = proxy.interpretationOverlays();
707
+ expect(resolvers.length).toBe(2);
708
+ resolvers[1]([]);
709
+ expect(await after).toEqual([]);
710
+ expect(await joiner).toEqual([]);
711
+ });
712
+ });
713
+
714
+ // ── fix #1008: PerspectiveProxy.remove accepts bare Link ────────────────────
715
+ //
716
+ // PerspectiveClient.removeLink does `delete link.data.__typename` which throws
717
+ // when a bare Link (no .data) is passed. The fix resolves the Link to its stored
718
+ // LinkExpression first, so remove(new Link({...})) must work without error.
719
+ describe('PerspectiveProxy.remove with bare Link', () => {
720
+ function makeStoredExpression(source: string, predicate: string, target: string): LinkExpression {
721
+ const expr = new LinkExpression();
722
+ expr.author = 'did:test:agent';
723
+ expr.timestamp = '2026-01-01T00:00:00Z';
724
+ expr.data = new Link({ source, predicate, target });
725
+ expr.proof = { valid: true, invalid: false, signature: 'sig', key: 'key' } as any;
726
+ return expr;
727
+ }
728
+
729
+ it('resolves a bare Link to the stored expression and removes it', async () => {
730
+ const storedExpr = makeStoredExpression('s://a', 'p://b', 't://c');
731
+ const removeLink = jest.fn().mockResolvedValue(true);
732
+ const mockClient: any = {
733
+ ...createMockPerspectiveClient(),
734
+ // queryLinks is what PerspectiveProxy.get calls
735
+ queryLinks: jest.fn().mockResolvedValue([storedExpr]),
736
+ removeLink,
737
+ };
738
+ const proxy = createProxy(mockClient);
739
+
740
+ const result = await proxy.remove(new Link({ source: 's://a', predicate: 'p://b', target: 't://c' }));
741
+
742
+ expect(result).toBe(true);
743
+ // removeLink must have been called with the resolved expression, not the bare Link
744
+ expect(removeLink).toHaveBeenCalledWith('test-uuid', storedExpr, undefined);
745
+ });
746
+
747
+ it('throws a descriptive error when no stored expression matches the bare Link', async () => {
748
+ const mockClient: any = {
749
+ ...createMockPerspectiveClient(),
750
+ queryLinks: jest.fn().mockResolvedValue([]),
751
+ };
752
+ const proxy = createProxy(mockClient);
753
+
754
+ await expect(
755
+ proxy.remove(new Link({ source: 'missing://src', predicate: 'p://pred', target: 'missing://tgt' }))
756
+ ).rejects.toThrow('PerspectiveProxy.remove: no stored LinkExpression matches');
757
+ });
758
+
759
+ // Lal's #1011 review: the bare-Link resolution used `bare.predicate ||
760
+ // undefined`, and the Link constructor coerces a missing predicate to "" —
761
+ // so the predicate filter was silently dropped and matches[0] removed an
762
+ // arbitrary source→target link under a different predicate.
763
+ it('matches only predicate-less stored links when the bare Link has no predicate', async () => {
764
+ const withPredicate = makeStoredExpression('s://a', 'p://b', 't://c');
765
+ const withoutPredicate = makeStoredExpression('s://a', '', 't://c');
766
+ // the store reports a missing predicate as null, not ''
767
+ (withoutPredicate.data as any).predicate = null;
768
+ const removeLink = jest.fn().mockResolvedValue(true);
769
+ // the wrong candidate first: matches[0] of the unfiltered result
770
+ const queryLinks = jest.fn().mockResolvedValue([withPredicate, withoutPredicate]);
771
+ const mockClient: any = { ...createMockPerspectiveClient(), queryLinks, removeLink };
772
+ const proxy = createProxy(mockClient);
773
+
774
+ await proxy.remove(new Link({ source: 's://a', target: 't://c' }));
775
+
776
+ expect(removeLink).toHaveBeenCalledWith('test-uuid', withoutPredicate, undefined);
777
+ });
778
+
779
+ it('throws instead of removing a predicated link when the bare Link has no predicate', async () => {
780
+ const withPredicate = makeStoredExpression('s://a', 'p://b', 't://c');
781
+ const queryLinks = jest.fn().mockResolvedValue([withPredicate]);
782
+ const mockClient: any = { ...createMockPerspectiveClient(), queryLinks };
783
+ const proxy = createProxy(mockClient);
784
+
785
+ await expect(
786
+ proxy.remove(new Link({ source: 's://a', target: 't://c' }))
787
+ ).rejects.toThrow('no stored LinkExpression matches');
788
+ });
789
+
790
+ it('passes a full LinkExpressionInput through unchanged', async () => {
791
+ const storedExpr = makeStoredExpression('s://x', 'p://y', 't://z');
792
+ const removeLink = jest.fn().mockResolvedValue(true);
793
+ const mockClient: any = {
794
+ ...createMockPerspectiveClient(),
795
+ removeLink,
796
+ };
797
+ const proxy = createProxy(mockClient);
798
+
799
+ await proxy.remove(storedExpr as any);
800
+ // Should NOT have called queryLinks — no bare Link resolution needed
801
+ expect(removeLink).toHaveBeenCalledWith('test-uuid', storedExpr, undefined);
802
+ });
803
+ });
@@ -1,4 +1,8 @@
1
1
  import { LinkCallback, PerspectiveClient, SyncStateChangeCallback } from "./PerspectiveClient";
2
+ import type {
3
+ FlowFireOutcome, FlowMintedReceipt, FlowOutputRef, FlowProposeResult,
4
+ FlowReceiptVerdict, FlowValidOutput,
5
+ } from "./FlowInstance";
2
6
  import { CallOptions } from "../apiClient";
3
7
  import { Link, LinkExpression, LinkExpressionInput, LinkExpressionMutations, LinkMutations } from "../links/Links";
4
8
  import { LinkQuery } from "./LinkQuery";
@@ -584,6 +588,8 @@ export class PerspectiveProxy {
584
588
  #perspectiveLinkUpdatedCallbacks: LinkCallback[]
585
589
  #perspectiveSyncStateChangeCallbacks: SyncStateChangeCallback[]
586
590
  #ensuredSubjectClasses = new Set<string>()
591
+ /** The `interpretationOverlays()` RPC currently in flight, shared by concurrent callers. */
592
+ #overlaysInFlight: Promise<InterpretationOverlayInfo[]> | null = null
587
593
 
588
594
  /**
589
595
  * Creates a new PerspectiveProxy instance.
@@ -845,9 +851,27 @@ export class PerspectiveProxy {
845
851
  /**
846
852
  * Pending interpretation overlays on this perspective — LLM suggestions the
847
853
  * §4 divergence gate staged rather than applied, awaiting human accept/reject.
854
+ *
855
+ * Concurrent callers share one in-flight RPC. Nothing is kept after it
856
+ * settles, so every call made after that fetches from the executor again.
857
+ * {@link acceptInterpretation} and {@link rejectInterpretation} detach the
858
+ * in-flight RPC, so a read issued after they resolve never joins a read
859
+ * that started before the write.
860
+ * Each caller gets its own copy of the array.
848
861
  */
849
862
  async interpretationOverlays(): Promise<InterpretationOverlayInfo[]> {
850
- return await this.#client.interpretationOverlays(this.#handle.uuid)
863
+ if (this.#overlaysInFlight) {
864
+ return [...(await this.#overlaysInFlight)]
865
+ }
866
+ const pending = this.#client.interpretationOverlays(this.#handle.uuid)
867
+ this.#overlaysInFlight = pending
868
+ try {
869
+ return [...(await pending)]
870
+ } finally {
871
+ if (this.#overlaysInFlight === pending) {
872
+ this.#overlaysInFlight = null
873
+ }
874
+ }
851
875
  }
852
876
 
853
877
  /**
@@ -856,7 +880,12 @@ export class PerspectiveProxy {
856
880
  * `property` to accept a single predicate; omit it for the whole base.
857
881
  */
858
882
  async acceptInterpretation(base: string, property?: string): Promise<boolean> {
859
- return await this.#client.acceptInterpretation(this.#handle.uuid, base, property)
883
+ try {
884
+ return await this.#client.acceptInterpretation(this.#handle.uuid, base, property)
885
+ } finally {
886
+ // A read already in flight may predate this write; later callers must not join it.
887
+ this.#overlaysInFlight = null
888
+ }
860
889
  }
861
890
 
862
891
  /**
@@ -865,7 +894,64 @@ export class PerspectiveProxy {
865
894
  * rejected `update` drops the overlay and keeps the real value.
866
895
  */
867
896
  async rejectInterpretation(base: string, property?: string): Promise<boolean> {
868
- return await this.#client.rejectInterpretation(this.#handle.uuid, base, property)
897
+ try {
898
+ return await this.#client.rejectInterpretation(this.#handle.uuid, base, property)
899
+ } finally {
900
+ // A read already in flight may predate this write; later callers must not join it.
901
+ this.#overlaysInFlight = null
902
+ }
903
+ }
904
+
905
+ /**
906
+ * `outputs` names the instances a run produces, as `{ className, id }`
907
+ * pairs, for a transition into a terminal state. The proposal signs a
908
+ * hash over their content, and a receipt for the run can only speak for
909
+ * exactly these instances, as they stood at completion. Naming outputs
910
+ * for a non-terminal state is refused.
911
+ */
912
+ async proposeFlowTransition(instanceUri: string, toState: string, rationale?: string, outputs?: FlowOutputRef[]): Promise<FlowProposeResult> {
913
+ return await this.#client.proposeFlowTransition(this.#handle.uuid, instanceUri, toState, rationale, outputs)
914
+ }
915
+
916
+ async acceptFlowProposal(proposalUri: string): Promise<FlowFireOutcome[]> {
917
+ return await this.#client.acceptFlowProposal(this.#handle.uuid, proposalUri)
918
+ }
919
+
920
+ /** Withdraw our own links from a proposal; resolves to how many went. */
921
+ async rejectFlowProposal(proposalUri: string): Promise<number> {
922
+ return await this.#client.rejectFlowProposal(this.#handle.uuid, proposalUri)
923
+ }
924
+
925
+ /**
926
+ * Re-decide a flow receipt under this perspective's own flow catalogue.
927
+ * The verdict is three-way — see {@link FlowReceiptVerdict}: branch on
928
+ * `outcome`, never on a boolean you derive from it.
929
+ */
930
+ async verifyFlowReceipt(receipt: object): Promise<FlowReceiptVerdict> {
931
+ return await this.#client.verifyFlowReceipt(this.#handle.uuid, receipt)
932
+ }
933
+
934
+ /**
935
+ * Which instances are, as they stand, valid outputs of `flow`?
936
+ *
937
+ * Backed by receipt verification executor-side (see
938
+ * {@link FlowValidOutput}); an instance without a verifying receipt, or
939
+ * edited since its run completed, is not listed. The same predicate is
940
+ * available as a model-query filter:
941
+ * `where: { producedByFlow: { flow, state? } }`.
942
+ *
943
+ * Rejects — never resolves to `[]` — when the flow is not on this
944
+ * perspective, or when it carries more receipt candidates than the
945
+ * executor's per-flow budget (256): "could not read every receipt" is not
946
+ * "no valid outputs". The filter rejects the same way.
947
+ */
948
+ async flowValidOutputs(flow: string, state?: string): Promise<FlowValidOutput[]> {
949
+ return await this.#client.flowValidOutputs(this.#handle.uuid, flow, state)
950
+ }
951
+
952
+ /** Mint and store the receipt for a completed flow run. */
953
+ async mintFlowReceipt(instanceUri: string): Promise<FlowMintedReceipt> {
954
+ return await this.#client.mintFlowReceipt(this.#handle.uuid, instanceUri)
869
955
  }
870
956
 
871
957
  /** Subscribe to this perspective's auto-processor step signals. */
@@ -1131,12 +1217,50 @@ export class PerspectiveProxy {
1131
1217
 
1132
1218
  /**
1133
1219
  * Removes a link from the perspective.
1134
- *
1135
- * @param link - The link to remove
1220
+ *
1221
+ * Accepts either a full `LinkExpressionInput` (as returned by `add`) or a bare
1222
+ * `Link` (source/predicate/target only). When a bare Link is passed the method
1223
+ * resolves it to the first stored `LinkExpression` whose source, predicate, and
1224
+ * target match, then removes that expression. A bare Link without a predicate
1225
+ * (or with the constructor's `""` stand-in) matches only stored links that
1226
+ * themselves have no predicate. If no match is found an error is thrown
1227
+ * naming the link so the caller knows what was expected.
1228
+ *
1229
+ * @param link - The link to remove (LinkExpressionInput or bare Link)
1136
1230
  * @param batchId - Optional batch ID to group this operation with others
1137
1231
  */
1138
- async remove(link: LinkExpressionInput, batchId?: string): Promise<boolean> {
1139
- const result = await this.#client.removeLink(this.#handle.uuid, link, batchId)
1232
+ async remove(link: LinkExpressionInput | Link, batchId?: string): Promise<boolean> {
1233
+ let resolvedLink: LinkExpressionInput;
1234
+ if (!('data' in link) || (link as any).data === undefined) {
1235
+ // bare Link — resolve to stored expression
1236
+ const bare = link as Link;
1237
+ // The Link constructor coerces an absent predicate to "" and the
1238
+ // store reports predicate-less links as predicate null — so ""
1239
+ // and undefined both mean "no predicate" here, and neither may
1240
+ // widen the query: dropping the filter would resolve (and
1241
+ // remove!) an arbitrary source→target link under a *different*
1242
+ // predicate. LinkQuery cannot express "predicate is absent", so
1243
+ // in that case we query on source/target only and require the
1244
+ // absence ourselves.
1245
+ const predicateGiven = bare.predicate !== undefined && bare.predicate !== '';
1246
+ const candidates = await this.get(new LinkQuery({
1247
+ source: bare.source || undefined,
1248
+ predicate: predicateGiven ? bare.predicate : undefined,
1249
+ target: bare.target || undefined,
1250
+ }));
1251
+ const matches = predicateGiven
1252
+ ? candidates
1253
+ : candidates.filter(m => !m.data.predicate);
1254
+ if (matches.length === 0) {
1255
+ throw new Error(
1256
+ `PerspectiveProxy.remove: no stored LinkExpression matches Link { source: "${bare.source}", predicate: "${bare.predicate}", target: "${bare.target}" }`
1257
+ );
1258
+ }
1259
+ resolvedLink = matches[0] as unknown as LinkExpressionInput;
1260
+ } else {
1261
+ resolvedLink = link as LinkExpressionInput;
1262
+ }
1263
+ const result = await this.#client.removeLink(this.#handle.uuid, resolvedLink, batchId)
1140
1264
  invalidatePerspectiveCache(this.#handle.uuid);
1141
1265
  return result;
1142
1266
  }
@@ -1767,6 +1891,38 @@ export class PerspectiveProxy {
1767
1891
  }
1768
1892
  }
1769
1893
 
1894
+ /**
1895
+ * Return the full target-class URIs of every registered SubjectClass.
1896
+ *
1897
+ * Unlike {@link subjectClasses}, which strips the namespace and returns bare
1898
+ * names (`"Space"`, `"Channel"`), this method returns the complete URIs
1899
+ * (`"we://Space"`, `"flux://Channel"`). The full URI is the key that
1900
+ * `load_shape` resolves against, so it is the only collision-safe identifier
1901
+ * — two apps can both declare a class called `"Template"` under different
1902
+ * namespaces, and the bare name cannot distinguish them.
1903
+ *
1904
+ * Callers that need to check whether a *set* of models are already
1905
+ * registered should call this once and test membership against the returned
1906
+ * set, rather than issuing one `queryLinks` per model.
1907
+ *
1908
+ * One `queryLinks` round trip, no executor-side changes.
1909
+ */
1910
+ async subjectClassTargetClasses(): Promise<string[]> {
1911
+ try {
1912
+ const classLinks = await this.get(new LinkQuery({
1913
+ predicate: "rdf://type",
1914
+ target: "ad4m://SubjectClass"
1915
+ }));
1916
+ const uris = classLinks
1917
+ .map(l => l.data.source)
1918
+ .filter(source => source.length > 0);
1919
+ return [...new Set(uris)];
1920
+ } catch (e) {
1921
+ console.warn('subjectClassTargetClasses: lookup failed:', e);
1922
+ return [];
1923
+ }
1924
+ }
1925
+
1770
1926
  async stringOrTemplateObjectToSubjectClassName<T>(subjectClass: T): Promise<string> {
1771
1927
  if(typeof subjectClass === "string")
1772
1928
  return subjectClass