@coasys/ad4m 0.13.0-test-interpretation-1 → 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 +449 -149
  2. package/lib/index.js +447 -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 +13 -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 +30 -4
  53. package/src/shacl/SHACLShape.ts +28 -6
  54. package/src/shacl/index.ts +1 -1
@@ -6,13 +6,29 @@ import type { TranscriptTurn } from "./TranscriptTurn";
6
6
  * SHACL subject classes. Shapes are resolved server-side from the
7
7
  * perspective's registered classes, so callers pass only the transcript.
8
8
  */
9
- export type RunInterpretationRequest = { uuid: string, transcript: Array<TranscriptTurn>,
9
+ export type RunInterpretationRequest = { uuid: string, transcript: Array<TranscriptTurn>,
10
10
  /**
11
11
  * URI namespace new instance identities are minted under, e.g. `soa://ext/`.
12
12
  */
13
- basePrefix: string,
13
+ basePrefix: string,
14
14
  /**
15
15
  * Local names of the subject classes to extract into (e.g. `["Task","Belief"]`).
16
16
  * `None`/empty selects all subject classes registered in the perspective.
17
17
  */
18
- classes: Array<string> | null, };
18
+ classes: Array<string> | null,
19
+ /**
20
+ * Optional parent-scope filter for the dedup lookup: when set, only
21
+ * existing instances of the target classes that live under this scope
22
+ * are candidates for upsert. `None` = whole-perspective dedup set (the
23
+ * pre-scope default). Same semantics as `AutoProcessorConfig.existingScope`.
24
+ */
25
+ existingScope?: any,
26
+ /**
27
+ * Optional parent-scope target for newly minted instances: when set,
28
+ * every base URI the pass CREATES is additionally linked as a child of
29
+ * `mintScope.id` via the scope's predicate. Upserts of pre-existing
30
+ * instances are NOT linked (would multi-parent unrelated graph state).
31
+ * Must be the `Raw` variant of `Scope` (id + predicate). Same semantics
32
+ * as `AutoProcessorConfig.mintScope`.
33
+ */
34
+ mintScope?: any, };
@@ -18,7 +18,7 @@ describe("Ad4mModel.getModelMetadata()", () => {
18
18
  it("should extract property metadata with all fields", () => {
19
19
  @Model({ name: "PropertyModel" })
20
20
  class PropertyModel extends Ad4mModel {
21
- @Property({ through: "test://name", resolveLanguage: "literal" })
21
+ @Property({ through: "test://name" })
22
22
  name: string = "";
23
23
 
24
24
  @Optional({ through: "test://optional" })
@@ -40,7 +40,9 @@ describe("Ad4mModel.getModelMetadata()", () => {
40
40
  expect(metadata.properties.name.predicate).toBe("test://name");
41
41
  expect(metadata.properties.name.required).toBe(false);
42
42
  expect(metadata.properties.name.readOnly).toBe(false);
43
- expect(metadata.properties.name.resolveLanguage).toBe("literal");
43
+ // A bare @Property has no resolveLanguage → deterministic typed literal
44
+ // storage (default fast path).
45
+ expect(metadata.properties.name.resolveLanguage).toBeUndefined();
44
46
 
45
47
  // Verify "optional" property
46
48
  expect(metadata.properties.optional.predicate).toBe("test://optional");
@@ -148,7 +150,7 @@ describe("Ad4mModel.getModelMetadata()", () => {
148
150
  it("should handle complex model with mixed property and relation types", () => {
149
151
  @Model({ name: "Recipe" })
150
152
  class Recipe extends Ad4mModel {
151
- @Property({ through: "recipe://name", resolveLanguage: "literal" })
153
+ @Property({ through: "recipe://name" })
152
154
  name: string = "";
153
155
 
154
156
  @Optional({ through: "recipe://description" })
@@ -182,7 +184,8 @@ describe("Ad4mModel.getModelMetadata()", () => {
182
184
 
183
185
  // Verify all metadata fields are correctly extracted
184
186
  expect(metadata.properties.name.predicate).toBe("recipe://name");
185
- expect(metadata.properties.name.resolveLanguage).toBe("literal");
187
+ // Bare @Property → no resolveLanguage → deterministic typed literal.
188
+ expect(metadata.properties.name.resolveLanguage).toBeUndefined();
186
189
  expect(metadata.properties.description.predicate).toBe("recipe://description");
187
190
  expect(metadata.properties.rating.predicate).toBe("recipe://rating");
188
191
  expect(metadata.properties.rating.prologGetter).toBe("avg_rating(Base, Value)");
@@ -207,8 +210,7 @@ describe("Ad4mModel.fromJSONSchema() with getModelMetadata()", () => {
207
210
 
208
211
  const ProductClass = Ad4mModel.fromJSONSchema(schema, {
209
212
  name: "Product",
210
- namespace: "product://",
211
- resolveLanguage: "literal"
213
+ namespace: "product://"
212
214
  });
213
215
 
214
216
  const metadata = ProductClass.getModelMetadata();
@@ -222,12 +224,13 @@ describe("Ad4mModel.fromJSONSchema() with getModelMetadata()", () => {
222
224
  expect(metadata.properties.name.predicate).toBe("product://name");
223
225
  expect(metadata.properties.name.required).toBe(true);
224
226
  expect(metadata.properties.name.readOnly).toBe(false);
225
- expect(metadata.properties.name.resolveLanguage).toBe("literal");
227
+ // No resolveLanguage set → deterministic typed literal storage (default).
228
+ expect(metadata.properties.name.resolveLanguage).toBeUndefined();
226
229
 
227
230
  expect(metadata.properties.price).toBeDefined();
228
231
  expect(metadata.properties.price.predicate).toBe("product://price");
229
232
  expect(metadata.properties.price.required).toBe(true);
230
- expect(metadata.properties.price.resolveLanguage).toBe("literal");
233
+ expect(metadata.properties.price.resolveLanguage).toBeUndefined();
231
234
 
232
235
  expect(metadata.properties.description).toBeDefined();
233
236
  expect(metadata.properties.description.predicate).toBe("product://description");
@@ -288,7 +291,6 @@ describe("Ad4mModel.fromJSONSchema() with getModelMetadata()", () => {
288
291
  type: "string",
289
292
  "x-ad4m": {
290
293
  through: "foaf://name",
291
- resolveLanguage: "literal",
292
294
  writable: true
293
295
  }
294
296
  },
@@ -311,7 +313,8 @@ describe("Ad4mModel.fromJSONSchema() with getModelMetadata()", () => {
311
313
 
312
314
  // Verify x-ad4m metadata is respected
313
315
  expect(metadata.properties.name.predicate).toBe("foaf://name");
314
- expect(metadata.properties.name.resolveLanguage).toBe("literal");
316
+ // No resolveLanguage set → deterministic typed literal (default).
317
+ expect(metadata.properties.name.resolveLanguage).toBeUndefined();
315
318
  expect(metadata.properties.name.readOnly).toBe(false);
316
319
  expect(metadata.properties.name.required).toBe(true);
317
320
 
@@ -371,8 +374,7 @@ describe("Ad4mModel.fromJSONSchema() with getModelMetadata()", () => {
371
374
 
372
375
  const ArticleClass = Ad4mModel.fromJSONSchema(schema, {
373
376
  name: "Article",
374
- namespace: "article://",
375
- resolveLanguage: "literal"
377
+ namespace: "article://"
376
378
  });
377
379
 
378
380
  const metadata = ArticleClass.getModelMetadata();
@@ -384,11 +386,12 @@ describe("Ad4mModel.fromJSONSchema() with getModelMetadata()", () => {
384
386
  expect(metadata.properties.title).toBeDefined();
385
387
  expect(metadata.properties.title.predicate).toBe("article://title");
386
388
  expect(metadata.properties.title.required).toBe(true);
387
- expect(metadata.properties.title.resolveLanguage).toBe("literal");
389
+ // No resolveLanguage set → deterministic typed literal (default).
390
+ expect(metadata.properties.title.resolveLanguage).toBeUndefined();
388
391
 
389
392
  expect(metadata.properties.views).toBeDefined();
390
393
  expect(metadata.properties.views.predicate).toBe("article://views");
391
- expect(metadata.properties.views.resolveLanguage).toBe("literal");
394
+ expect(metadata.properties.views.resolveLanguage).toBeUndefined();
392
395
 
393
396
  expect(metadata.properties.published).toBeDefined();
394
397
  expect(metadata.properties.published.predicate).toBe("article://published");
@@ -522,13 +525,13 @@ describe("Ad4mModel.queryToSPARQL()", () => {
522
525
 
523
526
  @Model({ name: "Task" })
524
527
  class Task extends Ad4mModel {
525
- @Property({ through: "task://title", resolveLanguage: "literal", required: true })
528
+ @Property({ through: "task://title", required: true })
526
529
  title: string = "";
527
530
 
528
- @Property({ through: "task://priority", resolveLanguage: "literal" })
531
+ @Property({ through: "task://priority" })
529
532
  priority: number = 0;
530
533
 
531
- @Property({ through: "task://done", resolveLanguage: "literal" })
534
+ @Property({ through: "task://done" })
532
535
  done: boolean = false;
533
536
 
534
537
  @Optional({ through: "task://description" })
@@ -951,7 +954,7 @@ describe("SPARQL direct triple pattern generation", () => {
951
954
  @Flag({ through: "flux://entry_type", value: "flux://channel" })
952
955
  type: string = "";
953
956
 
954
- @Property({ through: "flux://name", resolveLanguage: "literal", required: true })
957
+ @Property({ through: "flux://name", required: true })
955
958
  name: string = "";
956
959
 
957
960
  @Optional({ through: "flux://description" })
@@ -1034,13 +1037,13 @@ describe("buildSPARQLQuery edge cases", () => {
1034
1037
  @Flag({ through: "flag://type", value: "flag://FlagModel" })
1035
1038
  type: string = "";
1036
1039
 
1037
- @Property({ through: "flag://name", resolveLanguage: "literal", required: true })
1040
+ @Property({ through: "flag://name", required: true })
1038
1041
  name: string = "";
1039
1042
  }
1040
1043
 
1041
1044
  @Model({ name: "NoFlagModel" })
1042
1045
  class NoFlagModel extends Ad4mModel {
1043
- @Property({ through: "noflag://title", resolveLanguage: "literal" })
1046
+ @Property({ through: "noflag://title" })
1044
1047
  title: string = "";
1045
1048
  }
1046
1049
 
@@ -1735,7 +1738,7 @@ describe("SHACL recursion — self-referential relations", () => {
1735
1738
  it("should generate SHACL for a directly self-referential model without overflowing the stack", () => {
1736
1739
  @Model({ name: "RecursiveChannel" })
1737
1740
  class RecursiveChannel extends Ad4mModel {
1738
- @Property({ through: "channel://name", resolveLanguage: "literal" })
1741
+ @Property({ through: "channel://name" })
1739
1742
  name: string = "";
1740
1743
 
1741
1744
  @HasMany(() => RecursiveChannel, { through: "channel://child" })
@@ -1862,7 +1865,7 @@ describe("deepQuery — getter evaluation", () => {
1862
1865
  @Flag({ through: "flux://entry_type", value: "flux://message" })
1863
1866
  type: string = "";
1864
1867
 
1865
- @Property({ through: "flux://body", resolveLanguage: "literal" })
1868
+ @Property({ through: "flux://body" })
1866
1869
  body: string = "";
1867
1870
 
1868
1871
  @Property({
@@ -2432,3 +2435,62 @@ describe("IncludeProjection type guard and key splitting", () => {
2432
2435
  expect((results[0] as any).$signalCount).toBe(5);
2433
2436
  });
2434
2437
  });
2438
+
2439
+ describe("Ad4mModel instance identity (uniqueness without envelopes)", () => {
2440
+ // Without a signed envelope, the only thing that keeps two instances from
2441
+ // collapsing onto the same node is their auto-generated base expression.
2442
+ // These tests pin that guarantee down: identity must come from the
2443
+ // instance's own IRI, never from (possibly duplicate) property content.
2444
+ const mockPerspective = {} as any;
2445
+
2446
+ it("auto-generates a distinct id for every instance, even with identical property values", () => {
2447
+ @Model({ name: "IdentityTestMessage" })
2448
+ class IdentityTestMessage extends Ad4mModel {
2449
+ @Property({ through: "identity://body", resolveLanguage: "literal" })
2450
+ body: string = "";
2451
+ }
2452
+
2453
+ const message1 = new IdentityTestMessage(mockPerspective);
2454
+ const message2 = new IdentityTestMessage(mockPerspective);
2455
+
2456
+ message1.body = "hello";
2457
+ message2.body = "hello";
2458
+
2459
+ expect(message1.body).toBe(message2.body);
2460
+ expect(message1.id).not.toBe(message2.id);
2461
+ });
2462
+
2463
+ it("uses the ad4m://obj/<random> scheme, not content-derived addressing", () => {
2464
+ @Model({ name: "IdentityTestSchemeCheck" })
2465
+ class IdentityTestSchemeCheck extends Ad4mModel {}
2466
+
2467
+ const instance = new IdentityTestSchemeCheck(mockPerspective);
2468
+
2469
+ // 24 lowercase a-z chars after the prefix (see makeRandomId in ./util.ts).
2470
+ // Locks in the scheme so a regression toward hashing property content
2471
+ // for the base expression — which would reintroduce the exact collision
2472
+ // this scheme exists to prevent — fails this test.
2473
+ expect(instance.id).toMatch(/^ad4m:\/\/obj\/[a-z]{24}$/);
2474
+ });
2475
+
2476
+ it("never reuses an id across many instances", () => {
2477
+ @Model({ name: "IdentityTestManyInstances" })
2478
+ class IdentityTestManyInstances extends Ad4mModel {}
2479
+
2480
+ const ids = Array.from(
2481
+ { length: 200 },
2482
+ () => new IdentityTestManyInstances(mockPerspective).id
2483
+ );
2484
+
2485
+ expect(new Set(ids).size).toBe(ids.length);
2486
+ });
2487
+
2488
+ it("respects an explicitly-provided base expression instead of generating one", () => {
2489
+ @Model({ name: "IdentityTestExplicitId" })
2490
+ class IdentityTestExplicitId extends Ad4mModel {}
2491
+
2492
+ const instance = new IdentityTestExplicitId(mockPerspective, "flux://existing-instance");
2493
+
2494
+ expect(instance.id).toBe("flux://existing-instance");
2495
+ });
2496
+ });
@@ -11,13 +11,13 @@ import { isArrayType, determinePredicate, determineNamespace, buildModelFromJSON
11
11
  import type { SHACLShape } from "../shacl/SHACLShape";
12
12
  import type { JSONSchemaProperty, JSONSchema, JSONSchemaToModelOptions } from "./json-schema";
13
13
 
14
- import { buildSPARQLQuery } from "./query-sparql";
14
+ import { buildSPARQLQuery, valueToLiteralIri, effectiveLiteralStorage } from "./query-sparql";
15
15
  import { ModelQueryBuilder } from "./ModelQueryBuilder";
16
16
  import {
17
17
  normalizeValue,
18
18
  } from "./hydration";
19
19
  import type {
20
- ParentScope, IncludeMap, Query,
20
+ Scope, IncludeMap, Query,
21
21
  GetOptions, AllInstancesResult, ResultsWithTotalCount,
22
22
  PaginationResult, PropertyMetadata, RelationMetadata, ModelMetadata,
23
23
  IncludeProjection,
@@ -138,13 +138,29 @@ function jsonToModelInstance<T extends Ad4mModel>(
138
138
  * // Define a recipe model
139
139
  * @Model({ name: "Recipe" })
140
140
  * class Recipe extends Ad4mModel {
141
- * // Required property with literal value
141
+ * // Plain property — no `resolveLanguage` → deterministic typed literal
142
+ * // storage (fast POS-index path). This is the perf default.
143
+ * @Property({ through: "recipe://name" })
144
+ * name: string = "";
145
+ *
146
+ * // Property that needs per-value provenance (e.g. a signed message body):
147
+ * // `resolveLanguage: "literal"` routes values through expression_create on
148
+ * // the built-in literal language, producing a signed envelope URI
149
+ * // (author/timestamp/proof) instead of a bare typed literal.
142
150
  * @Property({
143
- * through: "recipe://name",
151
+ * through: "recipe://signed_note",
144
152
  * resolveLanguage: "literal"
145
153
  * })
146
- * name: string = "";
147
- *
154
+ * signedNote: string = "";
155
+ *
156
+ * // Property resolved through a custom language: values are routed through
157
+ * // expression_create on that language (signed expression URIs).
158
+ * @Optional({
159
+ * through: "recipe://photo",
160
+ * resolveLanguage: "QmFileStorageLanguageAddress..."
161
+ * })
162
+ * photo: string = "";
163
+ *
148
164
  * // Optional property with custom initial value
149
165
  * @Optional({
150
166
  * through: "recipe://status",
@@ -300,9 +316,9 @@ export class Ad4mModel {
300
316
  * ```typescript
301
317
  * @Model({ name: "Recipe" })
302
318
  * class Recipe extends Ad4mModel {
303
- * @Property({ through: "recipe://name", resolveLanguage: "literal" })
319
+ * @Property({ through: "recipe://name" })
304
320
  * name: string = "";
305
- *
321
+ *
306
322
  * @HasMany({ through: "recipe://ingredient" })
307
323
  * ingredients: string[] = [];
308
324
  * }
@@ -404,7 +420,7 @@ export class Ad4mModel {
404
420
  predicate: predicate,
405
421
  required: isRequired,
406
422
  readOnly: propertySchema["x-ad4m"]?.writable === false,
407
- ...(propertySchema["x-ad4m"]?.resolveLanguage && { resolveLanguage: propertySchema["x-ad4m"].resolveLanguage }),
423
+ ...(propertySchema["x-ad4m"]?.resolveLanguage !== undefined && { resolveLanguage: propertySchema["x-ad4m"].resolveLanguage }),
408
424
  ...(propertySchema["x-ad4m"]?.initial && { initial: propertySchema["x-ad4m"].initial }),
409
425
  ...(propertySchema["x-ad4m"]?.local !== undefined && { local: propertySchema["x-ad4m"].local })
410
426
  };
@@ -425,20 +441,31 @@ export class Ad4mModel {
425
441
  *
426
442
  * @param perspective - The perspective where this model will be stored
427
443
  * @param baseExpression - Optional expression URI for this instance.
428
- * If omitted, a random Literal URL is generated.
444
+ * If omitted, a random `ad4m://obj/<id>` IRI is generated,
445
+ * independent of any property content — this is what keeps
446
+ * two instances with identical property values distinct.
429
447
  * @param source - Optional source expression this instance is linked to
430
- *
448
+ *
431
449
  * @example
432
450
  * ```typescript
433
451
  * // Create a new recipe with auto-generated base expression
434
452
  * const recipe = new Recipe(perspective);
435
- *
453
+ *
436
454
  * // Create with specific base expression
437
- * const recipe = new Recipe(perspective, "literal:...");
455
+ * const recipe = new Recipe(perspective, "ad4m://obj/existing-id");
438
456
  * ```
439
457
  */
440
458
  constructor(perspective: PerspectiveProxy, baseExpression?: string) {
441
- this._baseExpression = baseExpression ? baseExpression : Literal.from(makeRandomId(24)).toUrl();
459
+ // Use a dedicated `ad4m://obj/<id>` scheme for auto-generated
460
+ // baseExpressions instead of `Literal.from(...).toUrl()`'s
461
+ // `literal:string:<id>`. After typed-literal storage lands, the storage
462
+ // layer translates any `literal:string:X` target into a typed
463
+ // `"X"^^xsd:string` literal — which is correct for property values but
464
+ // wrong for relation targets (which must remain NamedNode IRIs). Using
465
+ // a distinct scheme keeps auto-generated instance IDs unambiguously
466
+ // IRIs, so relation links like `<post> --has_comment--> <comment-id>`
467
+ // round-trip correctly through the SPARQL store.
468
+ this._baseExpression = baseExpression ? baseExpression : `ad4m://obj/${makeRandomId(24)}`;
442
469
  this._perspective = perspective;
443
470
  }
444
471
 
@@ -1082,16 +1109,21 @@ export class Ad4mModel {
1082
1109
  // Generate actions from metadata (replaces Prolog query)
1083
1110
  const actions = this.generatePropertySetterAction(key, metadata);
1084
1111
 
1085
- // Get resolve language from metadata (replaces Prolog query)
1086
- let resolveLanguage = metadata.resolveLanguage;
1087
-
1088
1112
  // Skip storing empty/null/undefined values to avoid invalid empty literals (e.g. literal:string:)
1089
1113
  if (value === undefined || value === null || value === "") {
1090
1114
  return;
1091
1115
  }
1092
1116
 
1093
- if (resolveLanguage) {
1094
- value = await this._perspective.createExpression(value, resolveLanguage);
1117
+ const mode = effectiveLiteralStorage(metadata);
1118
+ if (mode.kind === "custom") {
1119
+ // Custom language: route through expression_create on that language.
1120
+ value = await this._perspective.createExpression(value, mode.language);
1121
+ } else if (mode.kind === "envelope") {
1122
+ // Built-in literal language: signed-envelope expression (provenance).
1123
+ value = await this._perspective.createExpression(value, "literal");
1124
+ } else {
1125
+ // Deterministic literal: IRI (POS-index friendly).
1126
+ value = valueToLiteralIri(value);
1095
1127
  }
1096
1128
 
1097
1129
  await this._perspective.executeAction(actions, this._baseExpression, [{ name: "value", value }], batchId);
@@ -1235,34 +1267,26 @@ export class Ad4mModel {
1235
1267
  (p) => p.required || p.flag || p.initial !== undefined
1236
1268
  );
1237
1269
 
1238
- // Track properties that have resolveLanguage (non-literal) so they can be
1239
- // set via setProperty after createSubject (which doesn't resolve languages).
1240
- const deferredResolveLanguageProps: string[] = [];
1270
+ // Track properties resolved through expression_create — a signed literal
1271
+ // envelope or a custom (non-"literal") resolveLanguage. These may fail
1272
+ // inside a batch context, so defer them to setProperty after createSubject.
1273
+ const deferredExpressionProps: string[] = [];
1241
1274
 
1242
1275
  if (hasConstructor) {
1243
- // First filter out the properties that are not relations (arrays)
1244
1276
  const initialValues = {};
1245
1277
  for (const [key, value] of Object.entries(this)) {
1246
1278
  if (value !== undefined && value !== null && !(Array.isArray(value) && value.length > 0) && !value?.action) {
1247
- // Check if this property requires language resolution (e.g. file storage).
1248
- // If so, resolve the expression *before* passing to createSubject so
1249
- // the constructor receives a valid URI instead of raw data.
1250
1279
  const propMeta = metadata.properties[key];
1251
- if (propMeta?.resolveLanguage && propMeta.resolveLanguage !== 'literal' && typeof value === 'object') {
1252
- // Defer these properties — they need createExpression which may
1253
- // fail inside a batch context on some languages. We'll set them
1254
- // via setProperty after createSubject.
1255
- deferredResolveLanguageProps.push(key);
1280
+ if (propMeta && effectiveLiteralStorage(propMeta).kind !== "deterministic") {
1281
+ deferredExpressionProps.push(key);
1256
1282
  continue;
1257
1283
  }
1258
1284
  initialValues[key] = value;
1259
1285
  }
1260
1286
  }
1261
1287
 
1262
- // Get the class name instead of passing the instance to avoid Prolog query generation
1263
1288
  const className = await this.perspective.stringOrTemplateObjectToSubjectClassName(this);
1264
1289
 
1265
- // Create the subject with the initial values
1266
1290
  await this.perspective.createSubject(
1267
1291
  className,
1268
1292
  this._baseExpression,
@@ -1276,10 +1300,7 @@ export class Ad4mModel {
1276
1300
  // property writing so that scalar values are persisted as links.
1277
1301
  await this.innerUpdate(!hasConstructor, batchId)
1278
1302
 
1279
- // Now handle any deferred resolveLanguage properties that were excluded
1280
- // from initialValues. setProperty will call createExpression to upload
1281
- // the data to the appropriate language and store the resulting URI.
1282
- for (const key of deferredResolveLanguageProps) {
1303
+ for (const key of deferredExpressionProps) {
1283
1304
  const value = (this as any)[key];
1284
1305
  if (value !== undefined && value !== null) {
1285
1306
  await this.setProperty(key, value, batchId);
@@ -1599,7 +1620,7 @@ export class Ad4mModel {
1599
1620
  * @param perspective - The perspective to create the instance in
1600
1621
  * @param data - Property values to assign before saving
1601
1622
  * @param options - Optional settings:
1602
- * - `parent` — a `ParentScope` (model form or raw form) whose `id` will
1623
+ * - `parent` — a `Scope` (model form or raw form) whose `id` will
1603
1624
  * be used to create an incoming link from the parent to the new instance.
1604
1625
  * - `batchId` — an existing batch id; when provided the link write and
1605
1626
  * `save()` are added to the batch instead of committed immediately.
@@ -1628,7 +1649,7 @@ export class Ad4mModel {
1628
1649
  this: typeof Ad4mModel & (new (...args: any[]) => T),
1629
1650
  perspective: PerspectiveProxy,
1630
1651
  data: Record<string, any> = {},
1631
- options?: { parent?: ParentScope; batchId?: string },
1652
+ options?: { parent?: Scope; batchId?: string },
1632
1653
  ): Promise<T> {
1633
1654
  const instance = new this(perspective) as T;
1634
1655
  Object.assign(instance, data);
@@ -1874,8 +1895,7 @@ export class Ad4mModel {
1874
1895
  * // With explicit configuration
1875
1896
  * const PersonClass = Ad4mModel.fromJSONSchema(schema, {
1876
1897
  * name: "Person",
1877
- * namespace: "person://",
1878
- * resolveLanguage: "literal"
1898
+ * namespace: "person://"
1879
1899
  * });
1880
1900
  *
1881
1901
  * // With property mapping
@@ -192,10 +192,10 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
192
192
  const field = options?.field;
193
193
 
194
194
  if (typeof modelOrPredicate === 'string') {
195
- // Raw predicate string → raw form of ParentScope
195
+ // Raw predicate string → raw form of Scope
196
196
  this.queryParams.parent = { id, predicate: modelOrPredicate };
197
197
  } else if (typeof modelOrPredicate === 'function') {
198
- // Model class → model form of ParentScope
198
+ // Model class → model form of Scope
199
199
  this.queryParams.parent = { id, model: modelOrPredicate, ...(field && { field }) };
200
200
  } else if (typeof idOrInstance !== 'string') {
201
201
  // Ad4mModel instance — derive model class from constructor
@@ -48,6 +48,15 @@ export interface RelationMetadataEntry {
48
48
  * Overrides auto-derived conformance when set.
49
49
  */
50
50
  where?: Where;
51
+ /**
52
+ * SHACL `sh:datatype` for the relation's target values. Set when the
53
+ * relation holds encoded literal values (e.g. `"xsd:string"` for a
54
+ * `HasMany<string>` that stores plain strings). Emitted into SHACL
55
+ * so the executor knows to decode `literal:<type>:<value>` wire form
56
+ * on hydration. Omit for URI relations that point at other model
57
+ * instances — those pass through byte-for-byte.
58
+ */
59
+ datatype?: string;
51
60
  }
52
61
 
53
62
  /** Registry of property metadata keyed by constructor → { propName → metadata } */
@@ -280,7 +289,16 @@ export interface PropertyOptions {
280
289
  readOnly?: boolean;
281
290
 
282
291
  /**
283
- * The language used to store the property. Can be the default `Literal` Language or a custom language address.
292
+ * The language used to resolve/store the property value — and the sole
293
+ * selector of storage mode. Not defaulted:
294
+ * - unset (the default for a plain `@Property()`) → deterministic
295
+ * typed literal storage (`literal:string:` / `:number:` / `:boolean:` /
296
+ * `:json:` IRIs stored as XSD-typed RDF literals; POS-index friendly).
297
+ * - `"literal"` → the built-in literal language: values go through
298
+ * `expression_create`, producing a signed-envelope URI with
299
+ * author/timestamp/proof (per-value provenance, e.g. Flux message
300
+ * bodies).
301
+ * - a custom language address → `expression_create` on that language.
284
302
  */
285
303
  resolveLanguage?: string;
286
304
 
@@ -355,6 +373,17 @@ export interface PropertyOptions {
355
373
  * should set this.
356
374
  */
357
375
  identity?: boolean;
376
+
377
+ /**
378
+ * Explicit SHACL `sh:datatype` for the property value. When set, this
379
+ * overrides auto-inference and — importantly — lets custom `getter`
380
+ * properties opt into typed-literal decoding. Auto-inference is disabled
381
+ * for properties with a `getter` (see `shacl-gen.ts`) because such
382
+ * getters typically return URIs; setting `datatype` explicitly declares
383
+ * that this getter returns literal values of the given XSD type
384
+ * (e.g. `"xsd://string"`) and enables the hydration decode gate.
385
+ */
386
+ datatype?: string;
358
387
  }
359
388
 
360
389
 
@@ -398,7 +427,7 @@ function applyPropertyMetadata(opts: PropertyOptions) {
398
427
  *
399
428
  * @description
400
429
  * Equivalent to `@Property` but defaults `required` to `false` and does not
401
- * apply `resolveLanguage` or `initial` defaults. Use this when a property
430
+ * apply any `initial` defaults. Use this when a property
402
431
  * may or may not have a value, and you want full control over its configuration.
403
432
  *
404
433
  * @example
@@ -557,8 +586,7 @@ export interface ModelConfig {
557
586
  * @Model({ name: "Recipe" })
558
587
  * class Recipe extends Ad4mModel {
559
588
  * @Property({
560
- * through: "recipe://name",
561
- * resolveLanguage: "literal"
589
+ * through: "recipe://name"
562
590
  * })
563
591
  * name: string = "";
564
592
  *
@@ -632,7 +660,9 @@ export function Model(opts: ModelConfig) {
632
660
  * Smart defaults (all overridable):
633
661
  * - `required` → `false`
634
662
  * - `readOnly` → `false`
635
- * - `resolveLanguage` → `"literal"`
663
+ * - `resolveLanguage` → unset → deterministic typed literal storage
664
+ * (the perf default). Set `resolveLanguage: "literal"` for a signed-envelope
665
+ * value, or a custom language address to resolve through that language.
636
666
  * - `initial` → `undefined` (no link created until a value is explicitly set)
637
667
  *
638
668
  * Properties are optional by default. When a model instance is created without
@@ -665,7 +695,8 @@ export function Model(opts: ModelConfig) {
665
695
  * })
666
696
  * role: string = "";
667
697
  *
668
- * // Optional property with literal resolution
698
+ * // Optional property with signed-envelope literal storage
699
+ * // (per-value provenance)
669
700
  * @Property({
670
701
  * through: "user://bio",
671
702
  * resolveLanguage: "literal"
@@ -678,18 +709,22 @@ export function Model(opts: ModelConfig) {
678
709
  * @param {string} opts.through - The predicate URI for the property
679
710
  * @param {boolean} [opts.required=false] - Whether the property is required (adds query filters and sentinel initial value)
680
711
  * @param {string} [opts.initial] - Initial value (defaults to "literal:string:uninitialized" when required)
681
- * @param {string} [opts.resolveLanguage] - Language to use for value resolution (e.g. "literal")
712
+ * @param {string} [opts.resolveLanguage] - Value-resolution language: unset (deterministic typed literal, the perf default), "literal" (signed envelope), or a custom language address
682
713
  * @param {string} [opts.prologGetter] - Custom Prolog code for getting the property value
683
714
  * @param {string} [opts.prologSetter] - Custom Prolog code for setting the property value
684
715
  * @param {boolean} [opts.local] - Whether the property should only be stored locally
685
716
  */
686
717
  export function Property(opts: PropertyOptions) {
687
718
  const required = opts.required ?? false;
719
+ // `resolveLanguage` is intentionally NOT defaulted here.
720
+ // The effective storage mode is derived from what the user explicitly set:
721
+ // - unset → deterministic typed literal (the perf default)
722
+ // - "literal" → signed literal envelope (per-value provenance)
723
+ // - <custom address> → expression on that custom language
688
724
  return applyPropertyMetadata({
689
725
  ...opts,
690
726
  required,
691
727
  readOnly: opts.readOnly ?? false,
692
- resolveLanguage: opts.resolveLanguage ?? "literal",
693
728
  initial: opts.initial ?? (required ? "literal:string:uninitialized" : undefined),
694
729
  });
695
730
  }
@@ -745,7 +780,7 @@ export function Property(opts: PropertyOptions) {
745
780
  * @param {PropertyOptions} opts - Property configuration
746
781
  * @param {string} opts.through - The predicate URI for the property
747
782
  * @param {string} [opts.initial] - Initial value (if property should have one)
748
- * @param {string} [opts.resolveLanguage] - Language to use for value resolution (e.g. "literal")
783
+ * @param {string} [opts.resolveLanguage] - Value-resolution language: unset (deterministic typed literal, the perf default), "literal" (signed envelope), or a custom language address
749
784
  * @param {string} [opts.prologGetter] - Custom Prolog code for getting the property value
750
785
  * @param {boolean} [opts.local] - Whether the property should only be stored locally
751
786
  */
@@ -812,6 +847,20 @@ export interface RelationOptions {
812
847
  * ```
813
848
  */
814
849
  where?: Where;
850
+ /**
851
+ * SHACL `sh:datatype` for the relation's target values. Set when the
852
+ * relation holds encoded literal values (e.g. `"xsd:string"` for a
853
+ * `HasMany<string>` that stores plain strings). The executor uses
854
+ * this to decode `literal:<type>:<value>` wire form on hydration.
855
+ * Omit for URI relations that point at other model instances.
856
+ *
857
+ * @example
858
+ * ```typescript
859
+ * @HasMany({ through: "run://source", datatype: "xsd:string" })
860
+ * sources: string[] = [];
861
+ * ```
862
+ */
863
+ datatype?: string;
815
864
  }
816
865
 
817
866
  /**
@@ -938,6 +987,7 @@ export function HasMany(
938
987
  ...(opts.getter && { getter: opts.getter }),
939
988
  ...(opts.filter !== undefined && { filter: opts.filter }),
940
989
  ...(opts.where && { where: opts.where }),
990
+ ...(opts.datatype && { datatype: opts.datatype }),
941
991
  };
942
992
 
943
993
  const relKey = key as string;
@@ -1001,6 +1051,7 @@ export function HasOne(
1001
1051
  local: opts.local,
1002
1052
  ...(opts.filter !== undefined && { filter: opts.filter }),
1003
1053
  ...(opts.where && { where: opts.where }),
1054
+ ...(opts.datatype && { datatype: opts.datatype }),
1004
1055
  };
1005
1056
 
1006
1057
  const relKey = key as string;
@@ -1071,6 +1122,7 @@ export function BelongsToOne(
1071
1122
  local: opts.local,
1072
1123
  ...(opts.filter !== undefined && { filter: opts.filter }),
1073
1124
  ...(opts.where && { where: opts.where }),
1125
+ ...(opts.datatype && { datatype: opts.datatype }),
1074
1126
  };
1075
1127
 
1076
1128
  if (opts.through) {
@@ -1129,6 +1181,7 @@ export function BelongsToMany(
1129
1181
  ...(opts.getter && { getter: opts.getter }),
1130
1182
  ...(opts.filter !== undefined && { filter: opts.filter }),
1131
1183
  ...(opts.where && { where: opts.where }),
1184
+ ...(opts.datatype && { datatype: opts.datatype }),
1132
1185
  };
1133
1186
 
1134
1187
  // @BelongsToMany is the inverse/read-only side — do NOT generate add*/remove*/set*