@coasys/ad4m 0.13.0-test-interpretation → 0.13.0-test-interpretation-2

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 (54) hide show
  1. package/lib/index.cjs +451 -149
  2. package/lib/index.js +449 -150
  3. package/lib/src/Literal.js +8 -0
  4. package/lib/src/generated/api/RunInterpretationRequest.d.ts +16 -0
  5. package/lib/src/model/Ad4mModel.d.ts +28 -11
  6. package/lib/src/model/Ad4mModel.js +57 -35
  7. package/lib/src/model/ModelQueryBuilder.js +2 -2
  8. package/lib/src/model/decorators.d.ts +52 -8
  9. package/lib/src/model/decorators.js +18 -8
  10. package/lib/src/model/json-schema.js +7 -21
  11. package/lib/src/model/query-common.d.ts +2 -2
  12. package/lib/src/model/query-sparql.d.ts +62 -0
  13. package/lib/src/model/query-sparql.js +78 -15
  14. package/lib/src/model/query-utils.d.ts +7 -2
  15. package/lib/src/model/query-utils.js +21 -11
  16. package/lib/src/model/shacl-gen.js +44 -15
  17. package/lib/src/model/types.d.ts +23 -8
  18. package/lib/src/perspectives/AutoProcessor.d.ts +132 -2
  19. package/lib/src/perspectives/InterpretationModels.d.ts +51 -3
  20. package/lib/src/perspectives/InterpretationModels.js +64 -26
  21. package/lib/src/perspectives/PerspectiveClient.d.ts +22 -2
  22. package/lib/src/perspectives/PerspectiveClient.js +35 -3
  23. package/lib/src/perspectives/PerspectiveProxy.d.ts +9 -1
  24. package/lib/src/perspectives/PerspectiveProxy.js +24 -14
  25. package/lib/src/perspectives/SparqlBindings.d.ts +24 -3
  26. package/lib/src/perspectives/SparqlBindings.js +57 -6
  27. package/lib/src/shacl/SHACLShape.d.ts +11 -3
  28. package/lib/src/shacl/SHACLShape.js +15 -1
  29. package/lib/src/shacl/index.d.ts +1 -1
  30. package/lib/src/shacl/index.js +1 -1
  31. package/package.json +2 -2
  32. package/src/Literal.ts +7 -0
  33. package/src/generated/api/RunInterpretationRequest.ts +19 -3
  34. package/src/model/Ad4mModel.test.ts +84 -22
  35. package/src/model/Ad4mModel.ts +61 -41
  36. package/src/model/ModelQueryBuilder.ts +2 -2
  37. package/src/model/decorators.ts +62 -9
  38. package/src/model/json-schema.ts +10 -25
  39. package/src/model/query-common.ts +2 -2
  40. package/src/model/query-sparql.test.ts +114 -13
  41. package/src/model/query-sparql.ts +83 -14
  42. package/src/model/query-utils.ts +22 -12
  43. package/src/model/shacl-gen.ts +42 -13
  44. package/src/model/shacl-roundtrip.test.ts +4 -2
  45. package/src/model/types.ts +23 -8
  46. package/src/perspectives/AutoProcessor.ts +133 -1
  47. package/src/perspectives/InterpretationModels.ts +103 -21
  48. package/src/perspectives/PerspectiveClient.ts +50 -4
  49. package/src/perspectives/PerspectiveProxy.ts +37 -21
  50. package/src/perspectives/SparqlBindings.test.ts +134 -0
  51. package/src/perspectives/SparqlBindings.ts +57 -6
  52. package/src/shacl/SHACLShape.test.ts +56 -4
  53. package/src/shacl/SHACLShape.ts +30 -6
  54. package/src/shacl/index.ts +1 -1
package/lib/index.js CHANGED
@@ -779,6 +779,14 @@ class Literal {
779
779
  const numberString = body.substring(7);
780
780
  return parseFloat(numberString);
781
781
  }
782
+ if (body.startsWith("boolean:")) {
783
+ const boolString = decodeURIComponent(body.substring(8));
784
+ if (boolString === "true")
785
+ return true;
786
+ if (boolString === "false")
787
+ return false;
788
+ throw new Error(`Can't parse boolean literal: ${boolString}`);
789
+ }
782
790
  if (body.startsWith("json:")) {
783
791
  const json = body.substring(5);
784
792
  return JSON.parse(decodeURIComponent(json));
@@ -1189,6 +1197,13 @@ class SHACLShape {
1189
1197
  if (prop.writable !== undefined) {
1190
1198
  turtle += ` ad4m:writable ${prop.writable} ;\n`;
1191
1199
  }
1200
+ // Interpreter dedup key: `toLinks()` and `toJSON()` preserve
1201
+ // `identity`; a Turtle export must too or the round-trip through
1202
+ // Turtle silently drops the interpretation-dedup marker
1203
+ // (CodeRabbit #881 review).
1204
+ if (prop.identity !== undefined) {
1205
+ turtle += ` ad4m:identity ${prop.identity} ;\n`;
1206
+ }
1192
1207
  // Remove trailing semicolon and close bracket
1193
1208
  turtle = turtle.slice(0, -2) + '\n';
1194
1209
  turtle += isLast ? ` ] .\n` : ` ] ;\n`;
@@ -1578,10 +1593,15 @@ class SHACLShape {
1578
1593
  val = val.substring(8);
1579
1594
  prop.writable = val === 'true';
1580
1595
  }
1596
+ // The general language selector (e.g. "literal" or a custom address).
1581
1597
  const resolveLangLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://resolveLanguage");
1582
1598
  if (resolveLangLink) {
1583
1599
  prop.resolveLanguage = resolveLangLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
1584
1600
  }
1601
+ // Storage mode is derived from `resolveLanguage` alone:
1602
+ // - unset → deterministic typed literal (fast path)
1603
+ // - "literal" → signed envelope on the built-in literal language
1604
+ // - <address> → expression on that custom language
1585
1605
  // Parse action arrays
1586
1606
  const setterLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://setter");
1587
1607
  if (setterLink) {
@@ -1748,6 +1768,7 @@ class SHACLShape {
1748
1768
  filter: p.filter,
1749
1769
  transform: p.transform,
1750
1770
  interpretation_hint: p.interpretationHint,
1771
+ identity: p.identity,
1751
1772
  })),
1752
1773
  constructor_actions: this.constructor_actions,
1753
1774
  destructor_actions: this.destructor_actions,
@@ -1779,7 +1800,7 @@ class SHACLShape {
1779
1800
  hasValue: p.has_value,
1780
1801
  local: p.local,
1781
1802
  writable: p.writable,
1782
- resolveLanguage: p.resolve_language,
1803
+ resolveLanguage: p.resolve_language ?? p.resolveLanguage,
1783
1804
  setter: p.setter,
1784
1805
  adder: p.adder,
1785
1806
  remover: p.remover,
@@ -1794,6 +1815,7 @@ class SHACLShape {
1794
1815
  filter: p.filter,
1795
1816
  transform: p.transform,
1796
1817
  interpretationHint: p.interpretation_hint,
1818
+ identity: p.identity,
1797
1819
  });
1798
1820
  }
1799
1821
  if (json.constructor_actions) {
@@ -1918,20 +1940,38 @@ interpretationHint) {
1918
1940
  name: propName,
1919
1941
  path: propMeta.through,
1920
1942
  };
1921
- // Determine datatype from initial value or resolveLanguage
1922
- if (propMeta.resolveLanguage === "literal") {
1923
- propShape.datatype = "xsd://string";
1943
+ // Determine datatype from JS field value type; the resolve* options
1944
+ // control storage mode (deterministic vs envelope), not scalar type.
1945
+ // A value stored on the literal language (deterministic or envelope,
1946
+ // i.e. resolveLanguage unset or "literal") gets a string datatype when
1947
+ // no initial value pins a more specific type. A custom resolveLanguage
1948
+ // yields an expression URI, not a literal.
1949
+ //
1950
+ // Skip auto-datatype for properties with a custom `getter` — those
1951
+ // typically return URIs (e.g. `@Optional({ getter: "SELECT ?target ..." })`
1952
+ // that hops through a link to another instance's URI). Autosetting
1953
+ // `sh:datatype xsd:string` there would trip the hydration decode gate
1954
+ // and silently transform `literal:string:<hex>` URIs into their inner
1955
+ // plain-string form on read. Users who want a getter to return literal
1956
+ // values can opt in explicitly by setting `datatype` on the property
1957
+ // options (handled below).
1958
+ if (propMeta.datatype) {
1959
+ // Explicit opt-in from PropertyOptions always wins over inference.
1960
+ propShape.datatype = propMeta.datatype;
1924
1961
  }
1925
- else if (propMeta.initial) {
1926
- const initialType = typeof obj[propName];
1927
- if (initialType === "number") {
1928
- propShape.datatype = "xsd://integer";
1929
- }
1930
- else if (initialType === "boolean") {
1931
- propShape.datatype = "xsd://boolean";
1932
- }
1933
- else if (initialType === "string") {
1934
- propShape.datatype = "xsd://string";
1962
+ else {
1963
+ const isLiteral = propMeta.resolveLanguage === undefined || propMeta.resolveLanguage === "literal";
1964
+ if ((propMeta.initial !== undefined || isLiteral) && !propMeta.getter) {
1965
+ const initialType = typeof obj[propName];
1966
+ if (initialType === "number") {
1967
+ propShape.datatype = "xsd://integer";
1968
+ }
1969
+ else if (initialType === "boolean") {
1970
+ propShape.datatype = "xsd://boolean";
1971
+ }
1972
+ else if (initialType === "string" || isLiteral) {
1973
+ propShape.datatype = "xsd://string";
1974
+ }
1935
1975
  }
1936
1976
  }
1937
1977
  // Cardinality constraints
@@ -2033,8 +2073,19 @@ interpretationHint) {
2033
2073
  name: relName,
2034
2074
  path: synthesizedPath,
2035
2075
  };
2036
- // Relations typically contain IRIs
2037
- relShape.nodeKind = 'IRI';
2076
+ // A relation with a declared `datatype` holds encoded literal
2077
+ // values (e.g. `HasMany<string>` with `datatype: "xsd:string"`).
2078
+ // Everything else is a URI relation pointing at another
2079
+ // instance. The executor uses `sh:datatype` on hydration to
2080
+ // decide whether to decode `literal:<type>:<value>` wire form
2081
+ // (yes for literals, no for URIs).
2082
+ if (relMeta.datatype) {
2083
+ relShape.datatype = relMeta.datatype;
2084
+ relShape.nodeKind = 'Literal';
2085
+ }
2086
+ else {
2087
+ relShape.nodeKind = 'IRI';
2088
+ }
2038
2089
  // Encode relation kind so the executor can derive direction and
2039
2090
  // scalar-vs-collection rendering without consulting the JS class.
2040
2091
  relShape.relationKind = relMeta.kind;
@@ -2458,7 +2509,7 @@ function applyPropertyMetadata(opts) {
2458
2509
  *
2459
2510
  * @description
2460
2511
  * Equivalent to `@Property` but defaults `required` to `false` and does not
2461
- * apply `resolveLanguage` or `initial` defaults. Use this when a property
2512
+ * apply any `initial` defaults. Use this when a property
2462
2513
  * may or may not have a value, and you want full control over its configuration.
2463
2514
  *
2464
2515
  * @example
@@ -2581,8 +2632,7 @@ function Flag(opts) {
2581
2632
  * @Model({ name: "Recipe" })
2582
2633
  * class Recipe extends Ad4mModel {
2583
2634
  * @Property({
2584
- * through: "recipe://name",
2585
- * resolveLanguage: "literal"
2635
+ * through: "recipe://name"
2586
2636
  * })
2587
2637
  * name: string = "";
2588
2638
  *
@@ -2639,7 +2689,9 @@ function Model$1(opts) {
2639
2689
  * Smart defaults (all overridable):
2640
2690
  * - `required` → `false`
2641
2691
  * - `readOnly` → `false`
2642
- * - `resolveLanguage` → `"literal"`
2692
+ * - `resolveLanguage` → unset → deterministic typed literal storage
2693
+ * (the perf default). Set `resolveLanguage: "literal"` for a signed-envelope
2694
+ * value, or a custom language address to resolve through that language.
2643
2695
  * - `initial` → `undefined` (no link created until a value is explicitly set)
2644
2696
  *
2645
2697
  * Properties are optional by default. When a model instance is created without
@@ -2672,7 +2724,8 @@ function Model$1(opts) {
2672
2724
  * })
2673
2725
  * role: string = "";
2674
2726
  *
2675
- * // Optional property with literal resolution
2727
+ * // Optional property with signed-envelope literal storage
2728
+ * // (per-value provenance)
2676
2729
  * @Property({
2677
2730
  * through: "user://bio",
2678
2731
  * resolveLanguage: "literal"
@@ -2685,18 +2738,22 @@ function Model$1(opts) {
2685
2738
  * @param {string} opts.through - The predicate URI for the property
2686
2739
  * @param {boolean} [opts.required=false] - Whether the property is required (adds query filters and sentinel initial value)
2687
2740
  * @param {string} [opts.initial] - Initial value (defaults to "literal:string:uninitialized" when required)
2688
- * @param {string} [opts.resolveLanguage] - Language to use for value resolution (e.g. "literal")
2741
+ * @param {string} [opts.resolveLanguage] - Value-resolution language: unset (deterministic typed literal, the perf default), "literal" (signed envelope), or a custom language address
2689
2742
  * @param {string} [opts.prologGetter] - Custom Prolog code for getting the property value
2690
2743
  * @param {string} [opts.prologSetter] - Custom Prolog code for setting the property value
2691
2744
  * @param {boolean} [opts.local] - Whether the property should only be stored locally
2692
2745
  */
2693
2746
  function Property(opts) {
2694
2747
  const required = opts.required ?? false;
2748
+ // `resolveLanguage` is intentionally NOT defaulted here.
2749
+ // The effective storage mode is derived from what the user explicitly set:
2750
+ // - unset → deterministic typed literal (the perf default)
2751
+ // - "literal" → signed literal envelope (per-value provenance)
2752
+ // - <custom address> → expression on that custom language
2695
2753
  return applyPropertyMetadata({
2696
2754
  ...opts,
2697
2755
  required,
2698
2756
  readOnly: opts.readOnly ?? false,
2699
- resolveLanguage: opts.resolveLanguage ?? "literal",
2700
2757
  initial: opts.initial ?? (required ? "literal:string:uninitialized" : undefined),
2701
2758
  });
2702
2759
  }
@@ -2751,7 +2808,7 @@ function Property(opts) {
2751
2808
  * @param {PropertyOptions} opts - Property configuration
2752
2809
  * @param {string} opts.through - The predicate URI for the property
2753
2810
  * @param {string} [opts.initial] - Initial value (if property should have one)
2754
- * @param {string} [opts.resolveLanguage] - Language to use for value resolution (e.g. "literal")
2811
+ * @param {string} [opts.resolveLanguage] - Value-resolution language: unset (deterministic typed literal, the perf default), "literal" (signed envelope), or a custom language address
2755
2812
  * @param {string} [opts.prologGetter] - Custom Prolog code for getting the property value
2756
2813
  * @param {boolean} [opts.local] - Whether the property should only be stored locally
2757
2814
  */
@@ -2819,6 +2876,7 @@ function HasMany(first, second) {
2819
2876
  ...(opts.getter && { getter: opts.getter }),
2820
2877
  ...(opts.filter !== undefined && { filter: opts.filter }),
2821
2878
  ...(opts.where && { where: opts.where }),
2879
+ ...(opts.datatype && { datatype: opts.datatype }),
2822
2880
  };
2823
2881
  const relKey = key;
2824
2882
  // Only add mutation methods when a predicate is available
@@ -2852,6 +2910,7 @@ function HasOne(first, second) {
2852
2910
  local: opts.local,
2853
2911
  ...(opts.filter !== undefined && { filter: opts.filter }),
2854
2912
  ...(opts.where && { where: opts.where }),
2913
+ ...(opts.datatype && { datatype: opts.datatype }),
2855
2914
  };
2856
2915
  const relKey = key;
2857
2916
  if (opts.through) {
@@ -2892,6 +2951,7 @@ function BelongsToOne(first, second) {
2892
2951
  local: opts.local,
2893
2952
  ...(opts.filter !== undefined && { filter: opts.filter }),
2894
2953
  ...(opts.where && { where: opts.where }),
2954
+ ...(opts.datatype && { datatype: opts.datatype }),
2895
2955
  };
2896
2956
  if (opts.through) {
2897
2957
  // Read-only property (the owning side manages the link)
@@ -2921,6 +2981,7 @@ function BelongsToMany(first, second) {
2921
2981
  ...(opts.getter && { getter: opts.getter }),
2922
2982
  ...(opts.filter !== undefined && { filter: opts.filter }),
2923
2983
  ...(opts.where && { where: opts.where }),
2984
+ ...(opts.datatype && { datatype: opts.datatype }),
2924
2985
  };
2925
2986
  // @BelongsToMany is the inverse/read-only side — do NOT generate add*/remove*/set*
2926
2987
  // prototype methods. Mutation must go through the owning side's @HasMany decorator.
@@ -3900,6 +3961,16 @@ class PerspectiveProxy {
3900
3961
  async addAutoProcessorEventListener(cb) {
3901
3962
  return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").addAutoProcessorEventListener(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, cb);
3902
3963
  }
3964
+ /**
3965
+ * Subscribe to this perspective's auto-processor neighbourhood-state
3966
+ * events — fires when this executor claims / finishes / abandons a
3967
+ * batch. Perspective-scoped, so a UI can render "someone is
3968
+ * auto-processing this" without receiving the batch payload. See
3969
+ * `AutoProcessorNeighbourhoodStateEvent`.
3970
+ */
3971
+ async addAutoProcessorNeighbourhoodStateListener(cb) {
3972
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").addAutoProcessorNeighbourhoodStateListener(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, cb);
3973
+ }
3903
3974
  /**
3904
3975
  * Executes a Prolog query against the perspective's knowledge base.
3905
3976
  * This is a powerful way to find complex patterns in the graph.
@@ -4772,20 +4843,20 @@ class PerspectiveProxy {
4772
4843
  return null;
4773
4844
  }
4774
4845
  const flowUri = flowUriLinks[0].data.target;
4775
- // Compute alternate prefix for state/transition URIs
4776
- const alternatePrefix = flowUri.endsWith('Flow')
4777
- ? flowUri.slice(0, -4) + '.'
4778
- : flowUri + '.';
4779
- // Fetch flow links using SPARQL to match flowUri source OR alternatePrefix sources
4780
- const sparqlQuery = `SELECT ?s ?p ?o WHERE {
4781
- ?s ?p ?o .
4782
- FILTER(?s = <${flowUri}> || STRSTARTS(STR(?s), "${alternatePrefix}"))
4783
- }`;
4784
- const sparqlResult = await this.querySparql(sparqlQuery);
4785
- const flowLinks = (sparqlResult || []).map((r) => ({
4786
- source: r.s,
4787
- predicate: r.p,
4788
- target: r.o
4846
+ // Fetch flow-level links (hasState, hasTransition, flowable, startAction)
4847
+ const flowLevelLinks = await this.get(new LinkQuery({ source: flowUri }));
4848
+ // Collect state and transition URIs, then fetch their child links
4849
+ const childUris = flowLevelLinks
4850
+ .filter(l => l.data.predicate === "ad4m://hasState"
4851
+ || l.data.predicate === "ad4m://hasTransition")
4852
+ .map(l => l.data.target);
4853
+ const childResults = await Promise.all(childUris.map(uri => this.get(new LinkQuery({ source: uri }))));
4854
+ // Flatten into the {source, predicate, target} shape fromLinks expects
4855
+ const allExprs = [...flowLevelLinks, ...childResults.flat()];
4856
+ const flowLinks = allExprs.map(l => ({
4857
+ source: l.data.source,
4858
+ predicate: l.data.predicate,
4859
+ target: l.data.target
4789
4860
  }));
4790
4861
  return SHACLFlow.fromLinks(flowLinks, flowUri);
4791
4862
  }
@@ -5740,10 +5811,16 @@ class PerspectiveClient {
5740
5811
  * retries on parse failure), so it can legitimately take minutes on slower
5741
5812
  * or CPU-only models. We raise the default 30s RPC timeout here to 20 min
5742
5813
  * (matches the CI `--timeout 1200000` for the interpretation tests).
5814
+ *
5815
+ * `existingScope` and `mintScope` match the AutoProcessor semantics:
5816
+ * `existingScope` constrains the dedup lookup to instances under a
5817
+ * subtree; `mintScope` links every FRESHLY-created base as a child of
5818
+ * `mintScope.id` via its predicate (upserts of pre-existing instances
5819
+ * are NOT re-parented — same rule as the watcher).
5743
5820
  */
5744
- async runInterpretation(uuid, transcript, basePrefix, classes) {
5821
+ async runInterpretation(uuid, transcript, basePrefix, classes, existingScope, mintScope) {
5745
5822
  const RUN_INTERPRETATION_TIMEOUT_MS = 20 * 60 * 1000;
5746
- return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.runInterpretation', { uuid, transcript, basePrefix, classes }, RUN_INTERPRETATION_TIMEOUT_MS);
5823
+ return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.runInterpretation', { uuid, transcript, basePrefix, classes, existingScope, mintScope }, RUN_INTERPRETATION_TIMEOUT_MS);
5747
5824
  }
5748
5825
  /**
5749
5826
  * Register a neighbourhood auto-processor on this perspective. The executor's
@@ -5774,6 +5851,11 @@ class PerspectiveClient {
5774
5851
  * Subscribe to auto-processor step signals. `cb` fires for every
5775
5852
  * `auto-processor-event` on `uuid` (BatchReady → Claimed/BackedOff/… →
5776
5853
  * Processed), letting a UI show progress and await the next batch.
5854
+ *
5855
+ * Registered on the per-uuid `#linkUnsubscribers` map so
5856
+ * `PerspectiveProxy.dispose()` → `removeAllListeners(uuid)` cleans the
5857
+ * subscription up; using the global `#unsubscribers` array would leak
5858
+ * callbacks across repeated view lifecycles (CodeRabbit #881 review).
5777
5859
  */
5778
5860
  async addAutoProcessorEventListener(uuid, cb) {
5779
5861
  const unsub = __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").subscribe((data) => {
@@ -5781,7 +5863,28 @@ class PerspectiveClient {
5781
5863
  cb(data);
5782
5864
  }
5783
5865
  });
5784
- __classPrivateFieldGet$9(this, _PerspectiveClient_unsubscribers, "f").push(unsub);
5866
+ let existing = __classPrivateFieldGet$9(this, _PerspectiveClient_linkUnsubscribers, "f").get(uuid) || [];
5867
+ existing.push(unsub);
5868
+ __classPrivateFieldGet$9(this, _PerspectiveClient_linkUnsubscribers, "f").set(uuid, existing);
5869
+ await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").waitForSubscription();
5870
+ }
5871
+ /**
5872
+ * Subscribe to neighbourhood-state events on a perspective. `cb` fires
5873
+ * when THIS executor claims / finishes / abandons a batch for any
5874
+ * processor on `uuid` — perspective-scoped observability so a UI can
5875
+ * render "someone is auto-processing this" without receiving the batch
5876
+ * payload or LLM I/O. Registered on the per-uuid `#linkUnsubscribers`
5877
+ * map so `PerspectiveProxy.dispose()` sweeps it up.
5878
+ */
5879
+ async addAutoProcessorNeighbourhoodStateListener(uuid, cb) {
5880
+ const unsub = __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").subscribe((data) => {
5881
+ if (data.type === 'auto-processor-neighbourhood-state' && data.perspectiveUuid === uuid) {
5882
+ cb(data);
5883
+ }
5884
+ });
5885
+ let existing = __classPrivateFieldGet$9(this, _PerspectiveClient_linkUnsubscribers, "f").get(uuid) || [];
5886
+ existing.push(unsub);
5887
+ __classPrivateFieldGet$9(this, _PerspectiveClient_linkUnsubscribers, "f").set(uuid, existing);
5785
5888
  await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").waitForSubscription();
5786
5889
  }
5787
5890
  async addLinkExpression(uuid, link, status = 'shared', batchId) {
@@ -14447,13 +14550,7 @@ function buildModelFromJSONSchema(BaseClass, schema, options) {
14447
14550
  }
14448
14551
  else {
14449
14552
  // Handle regular properties
14450
- let resolveLanguage = getPropertyOption(propertyName, propertySchema, options, 'resolveLanguage');
14451
- // If no specific resolveLanguage for this property, use the global one
14452
- if (!resolveLanguage && options.resolveLanguage) {
14453
- resolveLanguage = options.resolveLanguage;
14454
- }
14455
14553
  const local = getPropertyOption(propertyName, propertySchema, options, 'local');
14456
- // Determine readOnly: check PropertyOptions first, then x-ad4m.writable (inverted) for JSON Schema wire format
14457
14554
  let readOnly = getPropertyOption(propertyName, propertySchema, options, 'readOnly');
14458
14555
  if (readOnly === undefined) {
14459
14556
  const xWritable = propertySchema["x-ad4m"]?.writable;
@@ -14461,22 +14558,14 @@ function buildModelFromJSONSchema(BaseClass, schema, options) {
14461
14558
  }
14462
14559
  const writable = !readOnly;
14463
14560
  let initial = getPropertyOption(propertyName, propertySchema, options, 'initial');
14464
- // Handle nested objects by serializing to JSON
14465
- if (isObjectType(propertySchema) && !resolveLanguage) {
14466
- resolveLanguage = 'literal';
14561
+ // Not defaulted — absence means "deterministic typed literal" (the
14562
+ // perf default); an explicit `resolveLanguage: "literal"` selects the
14563
+ // signed-envelope path; any other value selects a custom language.
14564
+ // See effectiveLiteralStorage().
14565
+ const resolveLanguage = getPropertyOption(propertyName, propertySchema, options, 'resolveLanguage');
14566
+ if (isObjectType(propertySchema)) {
14467
14567
  console.warn(`Property "${propertyName}" is an object type. It will be stored as JSON. Consider flattening complex objects for better semantic querying.`);
14468
14568
  }
14469
- // Ensure numeric properties use literal language for correct typing
14470
- if ((resolveLanguage === undefined || resolveLanguage === null) && isNumericType(propertySchema)) {
14471
- resolveLanguage = 'literal';
14472
- }
14473
- // Default resolveLanguage to 'literal' for all remaining property types,
14474
- // matching the @Property decorator behaviour. Without this, string values
14475
- // stored as literal: URLs are returned unparsed.
14476
- if (resolveLanguage === undefined || resolveLanguage === null) {
14477
- resolveLanguage = 'literal';
14478
- }
14479
- // If property is required, ensure it has an initial value
14480
14569
  if (isRequired && !initial) {
14481
14570
  if (isObjectType(propertySchema)) {
14482
14571
  initial = 'literal:json:{}';
@@ -14489,7 +14578,7 @@ function buildModelFromJSONSchema(BaseClass, schema, options) {
14489
14578
  through: predicate,
14490
14579
  required: isRequired,
14491
14580
  writable: writable,
14492
- ...(resolveLanguage && { resolveLanguage }),
14581
+ ...(resolveLanguage !== undefined && { resolveLanguage }),
14493
14582
  ...(local !== undefined && { local }),
14494
14583
  ...(initial && { initial })
14495
14584
  };
@@ -14604,20 +14693,108 @@ function hasJsOnlyWhereFilters(metadata, allRelationsMetadata, where) {
14604
14693
  return false;
14605
14694
  }
14606
14695
  /**
14607
- * Determine if a property stores values as literal: IRIs (needs parse_literal for comparisons).
14608
- * Properties with resolveLanguage === "literal" AND properties without resolveLanguage
14609
- * both store values as literal: URIs. Only properties with a non-literal resolveLanguage
14610
- * (e.g. file storage) or flag properties store raw URIs.
14696
+ * Check whether a string value is a well-formed absolute IRI that can be
14697
+ * stored verbatim as a link target (raw `NamedNode`) instead of being
14698
+ * wrapped in a `literal:string:*` URI.
14699
+ *
14700
+ * This mirrors the Rust `is_safe_iri_target` /
14701
+ * `looks_like_absolute_iri` predicate in
14702
+ * `rust-executor/src/perspectives/model_query/utils.rs` and is
14703
+ * **load-bearing**: a value that returns `true` here MUST also be safely
14704
+ * queryable on the Rust side (`validate_iri` gate on the SPARQL
14705
+ * `UNION { ?s <pred> <val> }` IRI arm), otherwise scheme-lookalike prose
14706
+ * such as `"Note: buy milk"`, `"Re: standup"`, `"TODO: fix this"` slips
14707
+ * through the write regex, is stored as an invalid `NamedNode`, and
14708
+ * becomes a silent no-match on read.
14709
+ *
14710
+ * Fast-path scheme check (`^[a-zA-Z][a-zA-Z0-9+\-._]*:`) followed by the
14711
+ * same rejection set the Rust `validate_iri` applies: any Unicode
14712
+ * whitespace, C0/C1 control chars, and the SPARQL-breaking characters
14713
+ * `< > { } "`.
14611
14714
  */
14612
- function isLiteralStoredProperty(propMeta) {
14613
- if (propMeta.flag)
14715
+ function looksLikeUri(value) {
14716
+ if (!/^[a-zA-Z][a-zA-Z0-9+\-._]*:/.test(value))
14614
14717
  return false;
14615
- // If resolveLanguage is set to something other than "literal", it's a language expression URI
14616
- if (propMeta.resolveLanguage && propMeta.resolveLanguage !== "literal")
14718
+ // Reject anything the Rust-side `validate_iri` rejects so the two
14719
+ // predicates stay in sync. `\s` covers ASCII whitespace *and*
14720
+ // U+00A0/other Unicode whitespace under the default JS regex semantics.
14721
+ if (/[\s<>{}"\u0000-\u001F\u007F-\u009F]/.test(value))
14617
14722
  return false;
14618
- // Everything else (resolveLanguage === "literal" or undefined) stores as literal: URIs
14619
14723
  return true;
14620
14724
  }
14725
+ /**
14726
+ * Convert a JS value to its literal: IRI form, matching how the Rust executor
14727
+ * stores property values in the default deterministic-literal path
14728
+ * (`resolveLanguage` unset). Strings that already look like URIs are returned
14729
+ * as-is.
14730
+ *
14731
+ * Exported so write-side helpers (e.g. `Ad4mModel.setProperty`'s literal
14732
+ * resolve path) can keep their on-disk form aligned with what
14733
+ * `queryToSPARQL()` filters against — otherwise the same value can be
14734
+ * stored as `<literal:string:https%3A...>` from one path while WHERE
14735
+ * builders probe `<https://example.com>` from the other.
14736
+ *
14737
+ * The object/array arm mirrors Rust's `Literal::from_json` in
14738
+ * `perspective_instance.rs::resolve_property_value` (which routes
14739
+ * `Value::Object | Value::Array` through JSON encoding). Without it, JS
14740
+ * would fall through to `String(value)` and turn `{a: 1}` into
14741
+ * `"[object Object]"` and `[1, 2, 3]` into `"1,2,3"` before wrapping.
14742
+ */
14743
+ function valueToLiteralIri(value) {
14744
+ if (typeof value === 'string') {
14745
+ if (looksLikeUri(value))
14746
+ return value;
14747
+ return Literal.from(value).toUrl();
14748
+ }
14749
+ if (typeof value === 'number') {
14750
+ return Literal.from(value).toUrl();
14751
+ }
14752
+ if (typeof value === 'boolean') {
14753
+ return Literal.from(value).toUrl();
14754
+ }
14755
+ // Objects and arrays: route through Literal.from so we emit
14756
+ // `literal:json:*` (mirrors Rust `Literal::from_json`). Without this
14757
+ // arm we fall through to `String(value)` which turns objects into
14758
+ // `"[object Object]"` and arrays into `"1,2"` — silently storing the
14759
+ // wrong shape and breaking equality filters (`findAll({ where:
14760
+ // { config: {...} } })` would match against `"[object Object]"`).
14761
+ // The `value !== null` guard preserves the historical fallthrough for
14762
+ // `null` (→ `literal:string:null`), since `Literal.from(null).toUrl()`
14763
+ // throws on the empty-literal check.
14764
+ if (value !== null && typeof value === 'object') {
14765
+ return Literal.from(value).toUrl();
14766
+ }
14767
+ return Literal.from(String(value)).toUrl();
14768
+ }
14769
+ /**
14770
+ * Derive the effective storage mode from a property's explicit options.
14771
+ * `resolveLanguage` is the sole selector and is NOT defaulted at the
14772
+ * decorator level:
14773
+ * - unset → deterministic typed literal (the perf default
14774
+ * for a plain `@Property()`)
14775
+ * - `"literal"` → signed envelope on the built-in literal language
14776
+ * (per-value provenance, e.g. Flux message bodies)
14777
+ * - `<custom address>` → signed expression on that custom language
14778
+ */
14779
+ function effectiveLiteralStorage(meta) {
14780
+ const lang = meta.resolveLanguage;
14781
+ if (lang === undefined)
14782
+ return { kind: "deterministic" };
14783
+ if (lang === "literal")
14784
+ return { kind: "envelope" };
14785
+ return { kind: "custom", language: lang };
14786
+ }
14787
+ /**
14788
+ * Determine if a property stores values as deterministic literal: IRIs (so WHERE
14789
+ * filters can match typed literals directly). Envelope / custom-language
14790
+ * properties resolve through expressions, and flag properties store raw URIs —
14791
+ * none is a deterministic literal.
14792
+ */
14793
+ function isLiteralStoredProperty(propMeta) {
14794
+ if (propMeta.flag)
14795
+ return false;
14796
+ return effectiveLiteralStorage(propMeta).kind === "deterministic";
14797
+ }
14621
14798
  /**
14622
14799
  * Escape a string for use as a SPARQL string literal.
14623
14800
  */
@@ -15158,11 +15335,11 @@ class ModelQueryBuilder {
15158
15335
  }
15159
15336
  const field = options?.field;
15160
15337
  if (typeof modelOrPredicate === 'string') {
15161
- // Raw predicate string → raw form of ParentScope
15338
+ // Raw predicate string → raw form of Scope
15162
15339
  this.queryParams.parent = { id, predicate: modelOrPredicate };
15163
15340
  }
15164
15341
  else if (typeof modelOrPredicate === 'function') {
15165
- // Model class → model form of ParentScope
15342
+ // Model class → model form of Scope
15166
15343
  this.queryParams.parent = { id, model: modelOrPredicate, ...(field && { field }) };
15167
15344
  }
15168
15345
  else if (typeof idOrInstance !== 'string') {
@@ -15814,12 +15991,28 @@ function jsonToModelInstance(ModelClass, perspective, json, include, properties)
15814
15991
  * // Define a recipe model
15815
15992
  * @Model({ name: "Recipe" })
15816
15993
  * class Recipe extends Ad4mModel {
15817
- * // Required property with literal value
15994
+ * // Plain property — no `resolveLanguage` → deterministic typed literal
15995
+ * // storage (fast POS-index path). This is the perf default.
15996
+ * @Property({ through: "recipe://name" })
15997
+ * name: string = "";
15998
+ *
15999
+ * // Property that needs per-value provenance (e.g. a signed message body):
16000
+ * // `resolveLanguage: "literal"` routes values through expression_create on
16001
+ * // the built-in literal language, producing a signed envelope URI
16002
+ * // (author/timestamp/proof) instead of a bare typed literal.
15818
16003
  * @Property({
15819
- * through: "recipe://name",
16004
+ * through: "recipe://signed_note",
15820
16005
  * resolveLanguage: "literal"
15821
16006
  * })
15822
- * name: string = "";
16007
+ * signedNote: string = "";
16008
+ *
16009
+ * // Property resolved through a custom language: values are routed through
16010
+ * // expression_create on that language (signed expression URIs).
16011
+ * @Optional({
16012
+ * through: "recipe://photo",
16013
+ * resolveLanguage: "QmFileStorageLanguageAddress..."
16014
+ * })
16015
+ * photo: string = "";
15823
16016
  *
15824
16017
  * // Optional property with custom initial value
15825
16018
  * @Optional({
@@ -15959,7 +16152,7 @@ class Ad4mModel {
15959
16152
  * ```typescript
15960
16153
  * @Model({ name: "Recipe" })
15961
16154
  * class Recipe extends Ad4mModel {
15962
- * @Property({ through: "recipe://name", resolveLanguage: "literal" })
16155
+ * @Property({ through: "recipe://name" })
15963
16156
  * name: string = "";
15964
16157
  *
15965
16158
  * @HasMany({ through: "recipe://ingredient" })
@@ -16048,7 +16241,7 @@ class Ad4mModel {
16048
16241
  predicate: predicate,
16049
16242
  required: isRequired,
16050
16243
  readOnly: propertySchema["x-ad4m"]?.writable === false,
16051
- ...(propertySchema["x-ad4m"]?.resolveLanguage && { resolveLanguage: propertySchema["x-ad4m"].resolveLanguage }),
16244
+ ...(propertySchema["x-ad4m"]?.resolveLanguage !== undefined && { resolveLanguage: propertySchema["x-ad4m"].resolveLanguage }),
16052
16245
  ...(propertySchema["x-ad4m"]?.initial && { initial: propertySchema["x-ad4m"].initial }),
16053
16246
  ...(propertySchema["x-ad4m"]?.local !== undefined && { local: propertySchema["x-ad4m"].local })
16054
16247
  };
@@ -16067,7 +16260,9 @@ class Ad4mModel {
16067
16260
  *
16068
16261
  * @param perspective - The perspective where this model will be stored
16069
16262
  * @param baseExpression - Optional expression URI for this instance.
16070
- * If omitted, a random Literal URL is generated.
16263
+ * If omitted, a random `ad4m://obj/<id>` IRI is generated,
16264
+ * independent of any property content — this is what keeps
16265
+ * two instances with identical property values distinct.
16071
16266
  * @param source - Optional source expression this instance is linked to
16072
16267
  *
16073
16268
  * @example
@@ -16076,12 +16271,21 @@ class Ad4mModel {
16076
16271
  * const recipe = new Recipe(perspective);
16077
16272
  *
16078
16273
  * // Create with specific base expression
16079
- * const recipe = new Recipe(perspective, "literal:...");
16274
+ * const recipe = new Recipe(perspective, "ad4m://obj/existing-id");
16080
16275
  * ```
16081
16276
  */
16082
16277
  constructor(perspective, baseExpression) {
16083
16278
  this._snapshot = null;
16084
- this._baseExpression = baseExpression ? baseExpression : Literal.from(makeRandomId(24)).toUrl();
16279
+ // Use a dedicated `ad4m://obj/<id>` scheme for auto-generated
16280
+ // baseExpressions instead of `Literal.from(...).toUrl()`'s
16281
+ // `literal:string:<id>`. After typed-literal storage lands, the storage
16282
+ // layer translates any `literal:string:X` target into a typed
16283
+ // `"X"^^xsd:string` literal — which is correct for property values but
16284
+ // wrong for relation targets (which must remain NamedNode IRIs). Using
16285
+ // a distinct scheme keeps auto-generated instance IDs unambiguously
16286
+ // IRIs, so relation links like `<post> --has_comment--> <comment-id>`
16287
+ // round-trip correctly through the SPARQL store.
16288
+ this._baseExpression = baseExpression ? baseExpression : `ad4m://obj/${makeRandomId(24)}`;
16085
16289
  this._perspective = perspective;
16086
16290
  }
16087
16291
  /**
@@ -16643,14 +16847,22 @@ class Ad4mModel {
16643
16847
  }
16644
16848
  // Generate actions from metadata (replaces Prolog query)
16645
16849
  const actions = this.generatePropertySetterAction(key, metadata);
16646
- // Get resolve language from metadata (replaces Prolog query)
16647
- let resolveLanguage = metadata.resolveLanguage;
16648
16850
  // Skip storing empty/null/undefined values to avoid invalid empty literals (e.g. literal:string:)
16649
16851
  if (value === undefined || value === null || value === "") {
16650
16852
  return;
16651
16853
  }
16652
- if (resolveLanguage) {
16653
- value = await this._perspective.createExpression(value, resolveLanguage);
16854
+ const mode = effectiveLiteralStorage(metadata);
16855
+ if (mode.kind === "custom") {
16856
+ // Custom language: route through expression_create on that language.
16857
+ value = await this._perspective.createExpression(value, mode.language);
16858
+ }
16859
+ else if (mode.kind === "envelope") {
16860
+ // Built-in literal language: signed-envelope expression (provenance).
16861
+ value = await this._perspective.createExpression(value, "literal");
16862
+ }
16863
+ else {
16864
+ // Deterministic literal: IRI (POS-index friendly).
16865
+ value = valueToLiteralIri(value);
16654
16866
  }
16655
16867
  await this._perspective.executeAction(actions, this._baseExpression, [{ name: "value", value }], batchId);
16656
16868
  }
@@ -16769,41 +16981,30 @@ class Ad4mModel {
16769
16981
  // entirely and let innerUpdate write the links directly.
16770
16982
  const metadata = this.constructor.getModelMetadata();
16771
16983
  const hasConstructor = Object.values(metadata.properties).some((p) => p.required || p.flag || p.initial !== undefined);
16772
- // Track properties that have resolveLanguage (non-literal) so they can be
16773
- // set via setProperty after createSubject (which doesn't resolve languages).
16774
- const deferredResolveLanguageProps = [];
16984
+ // Track properties resolved through expression_create — a signed literal
16985
+ // envelope or a custom (non-"literal") resolveLanguage. These may fail
16986
+ // inside a batch context, so defer them to setProperty after createSubject.
16987
+ const deferredExpressionProps = [];
16775
16988
  if (hasConstructor) {
16776
- // First filter out the properties that are not relations (arrays)
16777
16989
  const initialValues = {};
16778
16990
  for (const [key, value] of Object.entries(this)) {
16779
16991
  if (value !== undefined && value !== null && !(Array.isArray(value) && value.length > 0) && !value?.action) {
16780
- // Check if this property requires language resolution (e.g. file storage).
16781
- // If so, resolve the expression *before* passing to createSubject so
16782
- // the constructor receives a valid URI instead of raw data.
16783
16992
  const propMeta = metadata.properties[key];
16784
- if (propMeta?.resolveLanguage && propMeta.resolveLanguage !== 'literal' && typeof value === 'object') {
16785
- // Defer these properties — they need createExpression which may
16786
- // fail inside a batch context on some languages. We'll set them
16787
- // via setProperty after createSubject.
16788
- deferredResolveLanguageProps.push(key);
16993
+ if (propMeta && effectiveLiteralStorage(propMeta).kind !== "deterministic") {
16994
+ deferredExpressionProps.push(key);
16789
16995
  continue;
16790
16996
  }
16791
16997
  initialValues[key] = value;
16792
16998
  }
16793
16999
  }
16794
- // Get the class name instead of passing the instance to avoid Prolog query generation
16795
17000
  const className = await this.perspective.stringOrTemplateObjectToSubjectClassName(this);
16796
- // Create the subject with the initial values
16797
17001
  await this.perspective.createSubject(className, this._baseExpression, initialValues, batchId);
16798
17002
  }
16799
17003
  // Set properties and relations via innerUpdate.
16800
17004
  // When createSubject was skipped (no constructor actions), we must enable
16801
17005
  // property writing so that scalar values are persisted as links.
16802
17006
  await this.innerUpdate(!hasConstructor, batchId);
16803
- // Now handle any deferred resolveLanguage properties that were excluded
16804
- // from initialValues. setProperty will call createExpression to upload
16805
- // the data to the appropriate language and store the resulting URI.
16806
- for (const key of deferredResolveLanguageProps) {
17007
+ for (const key of deferredExpressionProps) {
16807
17008
  const value = this[key];
16808
17009
  if (value !== undefined && value !== null) {
16809
17010
  await this.setProperty(key, value, batchId);
@@ -17098,7 +17299,7 @@ class Ad4mModel {
17098
17299
  * @param perspective - The perspective to create the instance in
17099
17300
  * @param data - Property values to assign before saving
17100
17301
  * @param options - Optional settings:
17101
- * - `parent` — a `ParentScope` (model form or raw form) whose `id` will
17302
+ * - `parent` — a `Scope` (model form or raw form) whose `id` will
17102
17303
  * be used to create an incoming link from the parent to the new instance.
17103
17304
  * - `batchId` — an existing batch id; when provided the link write and
17104
17305
  * `save()` are added to the batch instead of committed immediately.
@@ -17330,8 +17531,7 @@ class Ad4mModel {
17330
17531
  * // With explicit configuration
17331
17532
  * const PersonClass = Ad4mModel.fromJSONSchema(schema, {
17332
17533
  * name: "Person",
17333
- * namespace: "person://",
17334
- * resolveLanguage: "literal"
17534
+ * namespace: "person://"
17335
17535
  * });
17336
17536
  *
17337
17537
  * // With property mapping
@@ -17748,11 +17948,20 @@ var __metadata = (undefined && undefined.__metadata) || function (k, v) {
17748
17948
  // Mirrors the Rust `auto_processor::config::AutoProcessorConfig` SDNA.
17749
17949
  // One node per registered processor; the node URI is
17750
17950
  // `ad4m://autoprocessor/<processorId>`.
17951
+ // Model name = "AutoProcessor" (NOT "AutoProcessorConfig") to match the Rust
17952
+ // hardwired subject class in `perspectives/auto_processor/config.rs` — that
17953
+ // alignment is what the SDNA parity test in
17954
+ // `tests/js/tests/model/interpretation-models.test.ts` guards. The TS class
17955
+ // symbol keeps the `Config` suffix for readability (`AutoProcessorConfig` reads
17956
+ // better than a bare `AutoProcessor` for an "instances of the config record"
17957
+ // query), but the on-graph subject class it registers is `AutoProcessor`.
17751
17958
  let AutoProcessorConfig = class AutoProcessorConfig extends Ad4mModel {
17752
17959
  constructor() {
17753
17960
  super(...arguments);
17754
- this.type = "ad4m://AutoProcessor";
17755
17961
  /** Unique processor id — the dedup key for auto-processor instances. */
17962
+ // First-declared property: `buildSHACL` derives the shape namespace from
17963
+ // its `through` prefix, so `ad4m://processor_id` → `ad4m://` → target_class
17964
+ // `ad4m://AutoProcessor` (matches Rust `AUTO_PROCESSOR_TARGET_CLASS`).
17756
17965
  this.processorId = "";
17757
17966
  /** SPARQL SELECT that gathers source items each pass. */
17758
17967
  this.sourceScopeQuery = "";
@@ -17764,12 +17973,13 @@ let AutoProcessorConfig = class AutoProcessorConfig extends Ad4mModel {
17764
17973
  this.batchMax = "32";
17765
17974
  /** How long a won claim is authoritative before peers may re-claim (ms). */
17766
17975
  this.claimTtlMs = "60000";
17976
+ // No `@Flag` type discriminator (Nico 2026-08-19: "type flags are an
17977
+ // anti-pattern for subject classes; match over all the properties
17978
+ // instead"). Conformance is by the presence of `processorId` +
17979
+ // `sourceScopeQuery` + `interpretationClasses` + `debounceMs` +
17980
+ // `batchMax` + `claimTtlMs` — the Rust SDNA takes the same shape.
17767
17981
  }
17768
17982
  };
17769
- __decorate([
17770
- Flag({ through: "rdf://type", value: "ad4m://AutoProcessor" }),
17771
- __metadata("design:type", String)
17772
- ], AutoProcessorConfig.prototype, "type", void 0);
17773
17983
  __decorate([
17774
17984
  Property({ through: "ad4m://processor_id", required: true, identity: true }),
17775
17985
  __metadata("design:type", String)
@@ -17779,11 +17989,11 @@ __decorate([
17779
17989
  __metadata("design:type", String)
17780
17990
  ], AutoProcessorConfig.prototype, "sourceScopeQuery", void 0);
17781
17991
  __decorate([
17782
- Optional({ through: "ad4m://base_prefix", resolveLanguage: "literal" }),
17992
+ Optional({ through: "ad4m://base_prefix" }),
17783
17993
  __metadata("design:type", String)
17784
17994
  ], AutoProcessorConfig.prototype, "basePrefix", void 0);
17785
17995
  __decorate([
17786
- HasMany({ through: "ad4m://interpretation_class" }),
17996
+ HasMany({ through: "ad4m://interpretation_class", datatype: "xsd:string" }),
17787
17997
  __metadata("design:type", Array)
17788
17998
  ], AutoProcessorConfig.prototype, "interpretationClasses", void 0);
17789
17999
  __decorate([
@@ -17791,7 +18001,7 @@ __decorate([
17791
18001
  __metadata("design:type", String)
17792
18002
  ], AutoProcessorConfig.prototype, "debounceMs", void 0);
17793
18003
  __decorate([
17794
- Optional({ through: "ad4m://batch_min", resolveLanguage: "literal" }),
18004
+ Optional({ through: "ad4m://batch_min" }),
17795
18005
  __metadata("design:type", String)
17796
18006
  ], AutoProcessorConfig.prototype, "batchMin", void 0);
17797
18007
  __decorate([
@@ -17799,7 +18009,7 @@ __decorate([
17799
18009
  __metadata("design:type", String)
17800
18010
  ], AutoProcessorConfig.prototype, "batchMax", void 0);
17801
18011
  __decorate([
17802
- Optional({ through: "ad4m://max_wait_ms", resolveLanguage: "literal" }),
18012
+ Optional({ through: "ad4m://max_wait_ms" }),
17803
18013
  __metadata("design:type", String)
17804
18014
  ], AutoProcessorConfig.prototype, "maxWaitMs", void 0);
17805
18015
  __decorate([
@@ -17807,61 +18017,89 @@ __decorate([
17807
18017
  __metadata("design:type", String)
17808
18018
  ], AutoProcessorConfig.prototype, "claimTtlMs", void 0);
17809
18019
  __decorate([
17810
- Optional({ through: "ad4m://source_window_ms", resolveLanguage: "literal" }),
18020
+ Optional({ through: "ad4m://source_window_ms" }),
17811
18021
  __metadata("design:type", String)
17812
18022
  ], AutoProcessorConfig.prototype, "sourceWindowMs", void 0);
17813
18023
  __decorate([
17814
- Optional({ through: "ad4m://dedup_strategy", resolveLanguage: "literal" }),
18024
+ Optional({ through: "ad4m://dedup_strategy" }),
17815
18025
  __metadata("design:type", String)
17816
18026
  ], AutoProcessorConfig.prototype, "dedupStrategy", void 0);
18027
+ __decorate([
18028
+ Optional({ through: "ad4m://existing_scope" }),
18029
+ __metadata("design:type", String)
18030
+ ], AutoProcessorConfig.prototype, "existingScope", void 0);
18031
+ __decorate([
18032
+ Optional({ through: "ad4m://mint_scope" }),
18033
+ __metadata("design:type", String)
18034
+ ], AutoProcessorConfig.prototype, "mintScope", void 0);
18035
+ __decorate([
18036
+ Optional({ through: "ad4m://debug_mode", resolveLanguage: "literal" }),
18037
+ __metadata("design:type", String)
18038
+ ], AutoProcessorConfig.prototype, "debugMode", void 0);
18039
+ __decorate([
18040
+ Optional({ through: "ad4m://persist_debug", resolveLanguage: "literal" }),
18041
+ __metadata("design:type", String)
18042
+ ], AutoProcessorConfig.prototype, "persistDebug", void 0);
18043
+ __decorate([
18044
+ Optional({ through: "ad4m://emit_debug_events", resolveLanguage: "literal" }),
18045
+ __metadata("design:type", String)
18046
+ ], AutoProcessorConfig.prototype, "emitDebugEvents", void 0);
17817
18047
  AutoProcessorConfig = __decorate([
17818
- Model$1({ name: "AutoProcessorConfig" })
18048
+ Model$1({ name: "AutoProcessor" })
17819
18049
  ], AutoProcessorConfig);
17820
18050
  // ── InterpretationRun ───────────────────────────────────────────────────────
17821
18051
  // Mirrors the Rust `interpretation::overlay::InterpretationRun` SDNA.
17822
18052
  // One node per completed pass; the node URI is `ad4m://interp/run/<runId>`.
17823
18053
  let InterpretationRun = class InterpretationRun extends Ad4mModel {
17824
18054
  constructor() {
18055
+ // No `@Flag` type discriminator — Rust SDNA drops `ad4m://type` too.
18056
+ // Conformance is by `runId` (identity) — same pattern
18057
+ // `InterpretationOverlay` already uses (`kind` is its discriminator).
17825
18058
  super(...arguments);
17826
- this.type = "ad4m://interpretation-run";
17827
18059
  /** UUID for this run — the dedup key across run nodes. */
17828
18060
  this.runId = "";
17829
18061
  /**
17830
18062
  * Source item IDs consumed by this pass.
17831
18063
  * Stored as multiple links with the same predicate; the processed-turn
17832
- * cursor uses these to avoid re-interpreting a turn.
18064
+ * cursor uses these to avoid re-interpreting a turn. Values are plain
18065
+ * strings (turn hex), so the property opts into `sh:datatype`-gated
18066
+ * literal decoding on hydration.
17833
18067
  */
17834
18068
  this.sources = [];
17835
18069
  }
17836
18070
  };
17837
- __decorate([
17838
- Flag({ through: "ad4m://type", value: "ad4m://interpretation-run" }),
17839
- __metadata("design:type", String)
17840
- ], InterpretationRun.prototype, "type", void 0);
17841
18071
  __decorate([
17842
18072
  Property({ through: "ad4m://interp/run_id", required: true, identity: true }),
17843
18073
  __metadata("design:type", String)
17844
18074
  ], InterpretationRun.prototype, "runId", void 0);
17845
18075
  __decorate([
17846
- Optional({ through: "ad4m://interp/model", resolveLanguage: "literal" }),
18076
+ Optional({ through: "ad4m://interp/model" }),
17847
18077
  __metadata("design:type", String)
17848
18078
  ], InterpretationRun.prototype, "model", void 0);
17849
18079
  __decorate([
17850
- Optional({ through: "ad4m://interp/prompt_version", resolveLanguage: "literal" }),
18080
+ Optional({ through: "ad4m://interp/prompt_version" }),
17851
18081
  __metadata("design:type", String)
17852
18082
  ], InterpretationRun.prototype, "promptVersion", void 0);
17853
18083
  __decorate([
17854
- Optional({ through: "ad4m://interp/ran_at", resolveLanguage: "literal" }),
18084
+ Optional({ through: "ad4m://interp/ran_at" }),
17855
18085
  __metadata("design:type", String)
17856
18086
  ], InterpretationRun.prototype, "ranAt", void 0);
17857
18087
  __decorate([
17858
- Optional({ through: "ad4m://interp/processor", resolveLanguage: "literal" }),
18088
+ Optional({ through: "ad4m://interp/processor" }),
17859
18089
  __metadata("design:type", String)
17860
18090
  ], InterpretationRun.prototype, "processor", void 0);
17861
18091
  __decorate([
17862
- HasMany({ through: "ad4m://interp/sources" }),
18092
+ HasMany({ through: "ad4m://interp/sources", datatype: "xsd:string" }),
17863
18093
  __metadata("design:type", Array)
17864
18094
  ], InterpretationRun.prototype, "sources", void 0);
18095
+ __decorate([
18096
+ Optional({ through: "ad4m://interp/debug_prompt", resolveLanguage: "literal" }),
18097
+ __metadata("design:type", String)
18098
+ ], InterpretationRun.prototype, "debugPrompt", void 0);
18099
+ __decorate([
18100
+ Optional({ through: "ad4m://interp/debug_response", resolveLanguage: "literal" }),
18101
+ __metadata("design:type", String)
18102
+ ], InterpretationRun.prototype, "debugResponse", void 0);
17865
18103
  InterpretationRun = __decorate([
17866
18104
  Model$1({ name: "InterpretationRun" })
17867
18105
  ], InterpretationRun);
@@ -17893,11 +18131,11 @@ let InterpretationOverlay = class InterpretationOverlay extends Ad4mModel {
17893
18131
  }
17894
18132
  };
17895
18133
  __decorate([
17896
- Property({ through: "ad4m://interp/kind", required: true, resolveLanguage: "literal" }),
18134
+ Property({ through: "ad4m://interp/kind", required: true }),
17897
18135
  __metadata("design:type", String)
17898
18136
  ], InterpretationOverlay.prototype, "kind", void 0);
17899
18137
  __decorate([
17900
- Optional({ through: "ad4m://interp/run", resolveLanguage: "literal" }),
18138
+ Optional({ through: "ad4m://interp/run" }),
17901
18139
  __metadata("design:type", String)
17902
18140
  ], InterpretationOverlay.prototype, "run", void 0);
17903
18141
  InterpretationOverlay = __decorate([
@@ -17936,23 +18174,74 @@ function parseSparqlCount(result) {
17936
18174
  /**
17937
18175
  * Decode a `Literal`-encoded SPARQL binding back to a plain string.
17938
18176
  *
17939
- * Mirrors Flux's local `parseLit` helper. Returns `''` for `undefined`/empty
17940
- * input. Falls through to the raw value if decoding fails (defensive — the
17941
- * binding may already be a plain string for unwrapped properties).
18177
+ * Returns `''` for `undefined`/empty input. Falls through to the raw value
18178
+ * if decoding fails — bindings against properties resolved through a custom
18179
+ * language are already raw URIs and should pass through unchanged.
18180
+ *
18181
+ * Signed-envelope literals
18182
+ * ------------------------
18183
+ * Properties declared with `resolveLanguage: 'literal'` are written through
18184
+ * the built-in `literal` language, which wraps the value in a signed
18185
+ * expression envelope (`{ author, timestamp, data, proof }`) and encodes
18186
+ * the whole envelope as a `literal:json:` URL — see
18187
+ * `rust-executor/src/languages/mod.rs::expression_create` (literal branch).
18188
+ * On read, `parseLit` unwraps `.data` from that envelope so callers get the
18189
+ * original scalar value instead of the envelope JSON.
18190
+ *
18191
+ * The Channel V refactor moved most scalar properties to deterministic
18192
+ * typed XSD literals which no longer round-trip through this envelope — for
18193
+ * those properties the SPARQL binding is already the lexical form and this
18194
+ * helper decodes to the primitive. Signed-envelope literals still exist
18195
+ * for any property that opts back into `resolveLanguage: 'literal'` (e.g.
18196
+ * per-message provenance for chat bodies), which is why the `.data` unwrap
18197
+ * is preserved here.
18198
+ *
18199
+ * Non-envelope JSON objects (`literal:json:` payloads that are not signed
18200
+ * envelopes) are JSON-stringified for display.
17942
18201
  */
17943
18202
  function parseLit(val) {
17944
18203
  if (val === undefined || val === null || val === '')
17945
18204
  return '';
18205
+ // Fast-path 1: `literal:*` URLs from properties written through the built-in
18206
+ // `literal` language. On Channel V typed-XSD-literal properties, these
18207
+ // decode straight to a primitive; on `resolveLanguage: 'literal'` properties
18208
+ // (per-message provenance in chat/synergy) they decode to a signed-envelope
18209
+ // object we unwrap via `.data`.
17946
18210
  try {
17947
18211
  const result = Literal.fromUrl(val).get();
17948
- if (result && typeof result === 'object') {
17949
- return result.data ?? JSON.stringify(result);
18212
+ if (typeof result === 'object' && result !== null) {
18213
+ const data = result.data;
18214
+ if (typeof data === 'string')
18215
+ return data;
18216
+ return JSON.stringify(result);
17950
18217
  }
17951
18218
  return String(result);
17952
18219
  }
17953
18220
  catch {
17954
- return val;
18221
+ // fall through to plain-JSON envelope detection
18222
+ }
18223
+ // Fast-path 2: envelope stored/returned as a bare JSON string rather than a
18224
+ // `literal:json:*` URL. Depending on the storage backend and query path,
18225
+ // SPARQL bindings for `resolveLanguage: 'literal'` properties can surface
18226
+ // the envelope object directly as its JSON serialisation (Oxigraph typed
18227
+ // xsd:string of the JSON, or a Channel V pass-through) instead of the URL
18228
+ // form. Detect that shape by parsing the string and unwrapping `.data`
18229
+ // when it looks like a signed envelope; anything else passes through
18230
+ // unchanged so plain text (e.g. "just a string") is not corrupted.
18231
+ if (val.length >= 2 && val.charCodeAt(0) === 0x7b /* '{' */) {
18232
+ try {
18233
+ const parsed = JSON.parse(val);
18234
+ if (parsed && typeof parsed === 'object') {
18235
+ const data = parsed.data;
18236
+ if (typeof data === 'string')
18237
+ return data;
18238
+ }
18239
+ }
18240
+ catch {
18241
+ // not JSON — fall through and return the raw value
18242
+ }
17955
18243
  }
18244
+ return val;
17956
18245
  }
17957
18246
  /** Decode a `Literal`-encoded binding to a number. Returns 0 on empty/invalid input. */
17958
18247
  function parseLitNumber(val) {
@@ -18302,16 +18591,21 @@ function formatQueryValue(value) {
18302
18591
  *
18303
18592
  * @param predicate - The predicate URI for the property
18304
18593
  * @param condition - The Where condition value
18305
- * @param opts - Optional settings (e.g. `resolveLanguage`)
18594
+ * @param opts - Optional settings. `isDeterministicLiteral` (default
18595
+ * `true`) selects the direct typed-literal WHERE path.
18596
+ * Set to `false` when the property stores a signed
18597
+ * envelope (`resolveLanguage: "literal"`) or a
18598
+ * custom-language expression — the envelope path unwraps
18599
+ * with `parse_literal` before comparing.
18306
18600
  * @returns A single SPARQL condition string
18307
18601
  */
18308
18602
  function buildWhereCondition(predicate, condition, opts) {
18309
18603
  const escapedPredicate = escapeQueryString(predicate);
18310
- // For literal-resolved properties, we match against the raw IRI (which is a literal: URI)
18311
- // For language-resolved properties, we match against the plain URI
18312
- // For literal-resolved properties, values are stored as IRIs like <literal:string:VALUE>
18313
- // For language-resolved properties, values are plain URIs
18314
- const isLiteral = !opts?.resolveLanguage || opts.resolveLanguage === 'literal';
18604
+ // For deterministic-literal properties, values are stored as typed
18605
+ // literals like `"X"^^xsd:string` (or the legacy `<literal:string:VALUE>`
18606
+ // IRI form). For envelope / custom-language properties the target is a
18607
+ // signed expression URI; comparisons need to unwrap via `parse_literal`.
18608
+ const isLiteral = opts?.isDeterministicLiteral !== false;
18315
18609
  const varSuffix = opts?.varIndex ?? 0;
18316
18610
  function formatValue(v) {
18317
18611
  if (typeof v === 'string') {
@@ -18420,23 +18714,28 @@ function compileWhereClause(where, metadata) {
18420
18714
  if (['id', 'author', 'timestamp'].includes(propertyName))
18421
18715
  continue;
18422
18716
  let predicate;
18423
- let resolveLanguage;
18717
+ // Storage mode is derived from `resolveLanguage` alone:
18718
+ // - undefined → deterministic typed literal (fast POS-index path)
18719
+ // - "literal" → signed envelope on the literal language
18720
+ // - custom address → expression on that custom language
18721
+ // Envelope and custom-language properties both need the `parse_literal`
18722
+ // unwrap path, so we treat any `resolveLanguage`-carrying property as
18723
+ // non-deterministic here.
18724
+ let isDeterministicLiteral;
18424
18725
  if (metadata) {
18425
18726
  const propMeta = metadata.properties[propertyName];
18426
18727
  if (propMeta) {
18427
18728
  predicate = propMeta.predicate;
18428
- resolveLanguage = propMeta.resolveLanguage;
18729
+ isDeterministicLiteral = propMeta.resolveLanguage === undefined;
18429
18730
  }
18430
18731
  else {
18431
- // Property not found in metadata — treat name as raw predicate URI
18432
18732
  predicate = propertyName;
18433
18733
  }
18434
18734
  }
18435
18735
  else {
18436
- // No metadata — treat name as raw predicate URI
18437
18736
  predicate = propertyName;
18438
18737
  }
18439
- const cond = buildWhereCondition(predicate, condition, { resolveLanguage, varIndex: conditions.length });
18738
+ const cond = buildWhereCondition(predicate, condition, { isDeterministicLiteral, varIndex: conditions.length });
18440
18739
  if (cond) {
18441
18740
  conditions.push(cond);
18442
18741
  }
@@ -18572,7 +18871,7 @@ function fn(iri, args = []) {
18572
18871
  * ```typescript
18573
18872
  * @Property({
18574
18873
  * through: 'we://image',
18575
- * resolveLanguage: FILE_STORAGE_LANGUAGE,
18874
+ * resolveLanguage: 'literal',
18576
18875
  * transform: fileToDataUri,
18577
18876
  * })
18578
18877
  * avatar?: string;
@@ -18582,4 +18881,4 @@ const fileToDataUri = ifExpr(exists(path('file_storage://data_base64')))
18582
18881
  .then(concat(literal('data:'), coalesce(path('file_storage://file_type'), literal('image/png')), literal(';base64,'), path('file_storage://data_base64')))
18583
18882
  .else(focus());
18584
18883
 
18585
- 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, 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, 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, normalizeNamespaceString, normalizeSchemaType, normalizeValue, parseExprUrl, parseLit, parseLitBoolean, parseLitNumber, parseSparqlCount, path, queryCacheSize, resolveParentPredicate, setCachedResult, setPropertyRegistryEntry, setRelationRegistryEntry, typeDefsString };
18884
+ 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, 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 };