@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
@@ -24,17 +24,26 @@ var __metadata = (this && this.__metadata) || function (k, v) {
24
24
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
25
25
  };
26
26
  import { Ad4mModel } from "../model/Ad4mModel";
27
- import { Flag, HasMany, Optional, Property } from "../model/decorators";
27
+ import { HasMany, Optional, Property } from "../model/decorators";
28
28
  import { Model } from "../model/decorators";
29
29
  // ── AutoProcessorConfig ─────────────────────────────────────────────────────
30
30
  // Mirrors the Rust `auto_processor::config::AutoProcessorConfig` SDNA.
31
31
  // One node per registered processor; the node URI is
32
32
  // `ad4m://autoprocessor/<processorId>`.
33
+ // Model name = "AutoProcessor" (NOT "AutoProcessorConfig") to match the Rust
34
+ // hardwired subject class in `perspectives/auto_processor/config.rs` — that
35
+ // alignment is what the SDNA parity test in
36
+ // `tests/js/tests/model/interpretation-models.test.ts` guards. The TS class
37
+ // symbol keeps the `Config` suffix for readability (`AutoProcessorConfig` reads
38
+ // better than a bare `AutoProcessor` for an "instances of the config record"
39
+ // query), but the on-graph subject class it registers is `AutoProcessor`.
33
40
  let AutoProcessorConfig = class AutoProcessorConfig extends Ad4mModel {
34
41
  constructor() {
35
42
  super(...arguments);
36
- this.type = "ad4m://AutoProcessor";
37
43
  /** Unique processor id — the dedup key for auto-processor instances. */
44
+ // First-declared property: `buildSHACL` derives the shape namespace from
45
+ // its `through` prefix, so `ad4m://processor_id` → `ad4m://` → target_class
46
+ // `ad4m://AutoProcessor` (matches Rust `AUTO_PROCESSOR_TARGET_CLASS`).
38
47
  this.processorId = "";
39
48
  /** SPARQL SELECT that gathers source items each pass. */
40
49
  this.sourceScopeQuery = "";
@@ -46,12 +55,13 @@ let AutoProcessorConfig = class AutoProcessorConfig extends Ad4mModel {
46
55
  this.batchMax = "32";
47
56
  /** How long a won claim is authoritative before peers may re-claim (ms). */
48
57
  this.claimTtlMs = "60000";
58
+ // No `@Flag` type discriminator (Nico 2026-08-19: "type flags are an
59
+ // anti-pattern for subject classes; match over all the properties
60
+ // instead"). Conformance is by the presence of `processorId` +
61
+ // `sourceScopeQuery` + `interpretationClasses` + `debounceMs` +
62
+ // `batchMax` + `claimTtlMs` — the Rust SDNA takes the same shape.
49
63
  }
50
64
  };
51
- __decorate([
52
- Flag({ through: "rdf://type", value: "ad4m://AutoProcessor" }),
53
- __metadata("design:type", String)
54
- ], AutoProcessorConfig.prototype, "type", void 0);
55
65
  __decorate([
56
66
  Property({ through: "ad4m://processor_id", required: true, identity: true }),
57
67
  __metadata("design:type", String)
@@ -61,11 +71,11 @@ __decorate([
61
71
  __metadata("design:type", String)
62
72
  ], AutoProcessorConfig.prototype, "sourceScopeQuery", void 0);
63
73
  __decorate([
64
- Optional({ through: "ad4m://base_prefix", resolveLanguage: "literal" }),
74
+ Optional({ through: "ad4m://base_prefix" }),
65
75
  __metadata("design:type", String)
66
76
  ], AutoProcessorConfig.prototype, "basePrefix", void 0);
67
77
  __decorate([
68
- HasMany({ through: "ad4m://interpretation_class" }),
78
+ HasMany({ through: "ad4m://interpretation_class", datatype: "xsd:string" }),
69
79
  __metadata("design:type", Array)
70
80
  ], AutoProcessorConfig.prototype, "interpretationClasses", void 0);
71
81
  __decorate([
@@ -73,7 +83,7 @@ __decorate([
73
83
  __metadata("design:type", String)
74
84
  ], AutoProcessorConfig.prototype, "debounceMs", void 0);
75
85
  __decorate([
76
- Optional({ through: "ad4m://batch_min", resolveLanguage: "literal" }),
86
+ Optional({ through: "ad4m://batch_min" }),
77
87
  __metadata("design:type", String)
78
88
  ], AutoProcessorConfig.prototype, "batchMin", void 0);
79
89
  __decorate([
@@ -81,7 +91,7 @@ __decorate([
81
91
  __metadata("design:type", String)
82
92
  ], AutoProcessorConfig.prototype, "batchMax", void 0);
83
93
  __decorate([
84
- Optional({ through: "ad4m://max_wait_ms", resolveLanguage: "literal" }),
94
+ Optional({ through: "ad4m://max_wait_ms" }),
85
95
  __metadata("design:type", String)
86
96
  ], AutoProcessorConfig.prototype, "maxWaitMs", void 0);
87
97
  __decorate([
@@ -89,15 +99,35 @@ __decorate([
89
99
  __metadata("design:type", String)
90
100
  ], AutoProcessorConfig.prototype, "claimTtlMs", void 0);
91
101
  __decorate([
92
- Optional({ through: "ad4m://source_window_ms", resolveLanguage: "literal" }),
102
+ Optional({ through: "ad4m://source_window_ms" }),
93
103
  __metadata("design:type", String)
94
104
  ], AutoProcessorConfig.prototype, "sourceWindowMs", void 0);
95
105
  __decorate([
96
- Optional({ through: "ad4m://dedup_strategy", resolveLanguage: "literal" }),
106
+ Optional({ through: "ad4m://dedup_strategy" }),
97
107
  __metadata("design:type", String)
98
108
  ], AutoProcessorConfig.prototype, "dedupStrategy", void 0);
109
+ __decorate([
110
+ Optional({ through: "ad4m://existing_scope" }),
111
+ __metadata("design:type", String)
112
+ ], AutoProcessorConfig.prototype, "existingScope", void 0);
113
+ __decorate([
114
+ Optional({ through: "ad4m://mint_scope" }),
115
+ __metadata("design:type", String)
116
+ ], AutoProcessorConfig.prototype, "mintScope", void 0);
117
+ __decorate([
118
+ Optional({ through: "ad4m://debug_mode", resolveLanguage: "literal" }),
119
+ __metadata("design:type", String)
120
+ ], AutoProcessorConfig.prototype, "debugMode", void 0);
121
+ __decorate([
122
+ Optional({ through: "ad4m://persist_debug", resolveLanguage: "literal" }),
123
+ __metadata("design:type", String)
124
+ ], AutoProcessorConfig.prototype, "persistDebug", void 0);
125
+ __decorate([
126
+ Optional({ through: "ad4m://emit_debug_events", resolveLanguage: "literal" }),
127
+ __metadata("design:type", String)
128
+ ], AutoProcessorConfig.prototype, "emitDebugEvents", void 0);
99
129
  AutoProcessorConfig = __decorate([
100
- Model({ name: "AutoProcessorConfig" })
130
+ Model({ name: "AutoProcessor" })
101
131
  ], AutoProcessorConfig);
102
132
  export { AutoProcessorConfig };
103
133
  // ── InterpretationRun ───────────────────────────────────────────────────────
@@ -105,46 +135,54 @@ export { AutoProcessorConfig };
105
135
  // One node per completed pass; the node URI is `ad4m://interp/run/<runId>`.
106
136
  let InterpretationRun = class InterpretationRun extends Ad4mModel {
107
137
  constructor() {
138
+ // No `@Flag` type discriminator — Rust SDNA drops `ad4m://type` too.
139
+ // Conformance is by `runId` (identity) — same pattern
140
+ // `InterpretationOverlay` already uses (`kind` is its discriminator).
108
141
  super(...arguments);
109
- this.type = "ad4m://interpretation-run";
110
142
  /** UUID for this run — the dedup key across run nodes. */
111
143
  this.runId = "";
112
144
  /**
113
145
  * Source item IDs consumed by this pass.
114
146
  * Stored as multiple links with the same predicate; the processed-turn
115
- * cursor uses these to avoid re-interpreting a turn.
147
+ * cursor uses these to avoid re-interpreting a turn. Values are plain
148
+ * strings (turn hex), so the property opts into `sh:datatype`-gated
149
+ * literal decoding on hydration.
116
150
  */
117
151
  this.sources = [];
118
152
  }
119
153
  };
120
- __decorate([
121
- Flag({ through: "ad4m://type", value: "ad4m://interpretation-run" }),
122
- __metadata("design:type", String)
123
- ], InterpretationRun.prototype, "type", void 0);
124
154
  __decorate([
125
155
  Property({ through: "ad4m://interp/run_id", required: true, identity: true }),
126
156
  __metadata("design:type", String)
127
157
  ], InterpretationRun.prototype, "runId", void 0);
128
158
  __decorate([
129
- Optional({ through: "ad4m://interp/model", resolveLanguage: "literal" }),
159
+ Optional({ through: "ad4m://interp/model" }),
130
160
  __metadata("design:type", String)
131
161
  ], InterpretationRun.prototype, "model", void 0);
132
162
  __decorate([
133
- Optional({ through: "ad4m://interp/prompt_version", resolveLanguage: "literal" }),
163
+ Optional({ through: "ad4m://interp/prompt_version" }),
134
164
  __metadata("design:type", String)
135
165
  ], InterpretationRun.prototype, "promptVersion", void 0);
136
166
  __decorate([
137
- Optional({ through: "ad4m://interp/ran_at", resolveLanguage: "literal" }),
167
+ Optional({ through: "ad4m://interp/ran_at" }),
138
168
  __metadata("design:type", String)
139
169
  ], InterpretationRun.prototype, "ranAt", void 0);
140
170
  __decorate([
141
- Optional({ through: "ad4m://interp/processor", resolveLanguage: "literal" }),
171
+ Optional({ through: "ad4m://interp/processor" }),
142
172
  __metadata("design:type", String)
143
173
  ], InterpretationRun.prototype, "processor", void 0);
144
174
  __decorate([
145
- HasMany({ through: "ad4m://interp/sources" }),
175
+ HasMany({ through: "ad4m://interp/sources", datatype: "xsd:string" }),
146
176
  __metadata("design:type", Array)
147
177
  ], InterpretationRun.prototype, "sources", void 0);
178
+ __decorate([
179
+ Optional({ through: "ad4m://interp/debug_prompt", resolveLanguage: "literal" }),
180
+ __metadata("design:type", String)
181
+ ], InterpretationRun.prototype, "debugPrompt", void 0);
182
+ __decorate([
183
+ Optional({ through: "ad4m://interp/debug_response", resolveLanguage: "literal" }),
184
+ __metadata("design:type", String)
185
+ ], InterpretationRun.prototype, "debugResponse", void 0);
148
186
  InterpretationRun = __decorate([
149
187
  Model({ name: "InterpretationRun" })
150
188
  ], InterpretationRun);
@@ -177,11 +215,11 @@ let InterpretationOverlay = class InterpretationOverlay extends Ad4mModel {
177
215
  }
178
216
  };
179
217
  __decorate([
180
- Property({ through: "ad4m://interp/kind", required: true, resolveLanguage: "literal" }),
218
+ Property({ through: "ad4m://interp/kind", required: true }),
181
219
  __metadata("design:type", String)
182
220
  ], InterpretationOverlay.prototype, "kind", void 0);
183
221
  __decorate([
184
- Optional({ through: "ad4m://interp/run", resolveLanguage: "literal" }),
222
+ Optional({ through: "ad4m://interp/run" }),
185
223
  __metadata("design:type", String)
186
224
  ], InterpretationOverlay.prototype, "run", void 0);
187
225
  InterpretationOverlay = __decorate([
@@ -11,7 +11,7 @@ import { LinkStatus, PerspectiveProxy } from './PerspectiveProxy';
11
11
  import { AIClient } from "../ai/AIClient";
12
12
  import { AllInstancesResult } from "../model/types";
13
13
  import type { TranscriptTurn } from "../generated/api";
14
- import type { AddAutoProcessorConfig, AutoProcessorEvent, InterpretationOverlayInfo } from "./AutoProcessor";
14
+ import type { AddAutoProcessorConfig, AutoProcessorEvent, AutoProcessorNeighbourhoodStateEvent, InterpretationOverlayInfo, RawScope } from "./AutoProcessor";
15
15
  export type PerspectiveHandleCallback = (perspective: PerspectiveHandle) => null;
16
16
  export type UuidCallback = (uuid: string) => null;
17
17
  export type LinkCallback = (link: LinkExpression) => null;
@@ -64,8 +64,14 @@ export declare class PerspectiveClient {
64
64
  * retries on parse failure), so it can legitimately take minutes on slower
65
65
  * or CPU-only models. We raise the default 30s RPC timeout here to 20 min
66
66
  * (matches the CI `--timeout 1200000` for the interpretation tests).
67
+ *
68
+ * `existingScope` and `mintScope` match the AutoProcessor semantics:
69
+ * `existingScope` constrains the dedup lookup to instances under a
70
+ * subtree; `mintScope` links every FRESHLY-created base as a child of
71
+ * `mintScope.id` via its predicate (upserts of pre-existing instances
72
+ * are NOT re-parented — same rule as the watcher).
67
73
  */
68
- runInterpretation(uuid: string, transcript: TranscriptTurn[], basePrefix: string, classes?: string[]): Promise<string[]>;
74
+ runInterpretation(uuid: string, transcript: TranscriptTurn[], basePrefix: string, classes?: string[], existingScope?: RawScope, mintScope?: RawScope): Promise<string[]>;
69
75
  /**
70
76
  * Register a neighbourhood auto-processor on this perspective. The executor's
71
77
  * watch loop then runs interpretation automatically over new source items
@@ -87,8 +93,22 @@ export declare class PerspectiveClient {
87
93
  * Subscribe to auto-processor step signals. `cb` fires for every
88
94
  * `auto-processor-event` on `uuid` (BatchReady → Claimed/BackedOff/… →
89
95
  * Processed), letting a UI show progress and await the next batch.
96
+ *
97
+ * Registered on the per-uuid `#linkUnsubscribers` map so
98
+ * `PerspectiveProxy.dispose()` → `removeAllListeners(uuid)` cleans the
99
+ * subscription up; using the global `#unsubscribers` array would leak
100
+ * callbacks across repeated view lifecycles (CodeRabbit #881 review).
90
101
  */
91
102
  addAutoProcessorEventListener(uuid: String, cb: (event: AutoProcessorEvent) => void): Promise<void>;
103
+ /**
104
+ * Subscribe to neighbourhood-state events on a perspective. `cb` fires
105
+ * when THIS executor claims / finishes / abandons a batch for any
106
+ * processor on `uuid` — perspective-scoped observability so a UI can
107
+ * render "someone is auto-processing this" without receiving the batch
108
+ * payload or LLM I/O. Registered on the per-uuid `#linkUnsubscribers`
109
+ * map so `PerspectiveProxy.dispose()` sweeps it up.
110
+ */
111
+ addAutoProcessorNeighbourhoodStateListener(uuid: String, cb: (event: AutoProcessorNeighbourhoodStateEvent) => void): Promise<void>;
92
112
  addLinkExpression(uuid: string, link: LinkExpression, status?: LinkStatus, batchId?: string): Promise<LinkExpression>;
93
113
  updateLink(uuid: string, oldLink: LinkExpressionInput, newLink: Link, batchId?: string): Promise<LinkExpression>;
94
114
  removeLink(uuid: string, link: LinkExpressionInput, batchId?: string): Promise<boolean>;
@@ -202,10 +202,16 @@ export class PerspectiveClient {
202
202
  * retries on parse failure), so it can legitimately take minutes on slower
203
203
  * or CPU-only models. We raise the default 30s RPC timeout here to 20 min
204
204
  * (matches the CI `--timeout 1200000` for the interpretation tests).
205
+ *
206
+ * `existingScope` and `mintScope` match the AutoProcessor semantics:
207
+ * `existingScope` constrains the dedup lookup to instances under a
208
+ * subtree; `mintScope` links every FRESHLY-created base as a child of
209
+ * `mintScope.id` via its predicate (upserts of pre-existing instances
210
+ * are NOT re-parented — same rule as the watcher).
205
211
  */
206
- async runInterpretation(uuid, transcript, basePrefix, classes) {
212
+ async runInterpretation(uuid, transcript, basePrefix, classes, existingScope, mintScope) {
207
213
  const RUN_INTERPRETATION_TIMEOUT_MS = 20 * 60 * 1000;
208
- return __classPrivateFieldGet(this, _PerspectiveClient_apiClient, "f").call('perspective.runInterpretation', { uuid, transcript, basePrefix, classes }, RUN_INTERPRETATION_TIMEOUT_MS);
214
+ return __classPrivateFieldGet(this, _PerspectiveClient_apiClient, "f").call('perspective.runInterpretation', { uuid, transcript, basePrefix, classes, existingScope, mintScope }, RUN_INTERPRETATION_TIMEOUT_MS);
209
215
  }
210
216
  /**
211
217
  * Register a neighbourhood auto-processor on this perspective. The executor's
@@ -236,6 +242,11 @@ export class PerspectiveClient {
236
242
  * Subscribe to auto-processor step signals. `cb` fires for every
237
243
  * `auto-processor-event` on `uuid` (BatchReady → Claimed/BackedOff/… →
238
244
  * Processed), letting a UI show progress and await the next batch.
245
+ *
246
+ * Registered on the per-uuid `#linkUnsubscribers` map so
247
+ * `PerspectiveProxy.dispose()` → `removeAllListeners(uuid)` cleans the
248
+ * subscription up; using the global `#unsubscribers` array would leak
249
+ * callbacks across repeated view lifecycles (CodeRabbit #881 review).
239
250
  */
240
251
  async addAutoProcessorEventListener(uuid, cb) {
241
252
  const unsub = __classPrivateFieldGet(this, _PerspectiveClient_apiClient, "f").subscribe((data) => {
@@ -243,7 +254,28 @@ export class PerspectiveClient {
243
254
  cb(data);
244
255
  }
245
256
  });
246
- __classPrivateFieldGet(this, _PerspectiveClient_unsubscribers, "f").push(unsub);
257
+ let existing = __classPrivateFieldGet(this, _PerspectiveClient_linkUnsubscribers, "f").get(uuid) || [];
258
+ existing.push(unsub);
259
+ __classPrivateFieldGet(this, _PerspectiveClient_linkUnsubscribers, "f").set(uuid, existing);
260
+ await __classPrivateFieldGet(this, _PerspectiveClient_apiClient, "f").waitForSubscription();
261
+ }
262
+ /**
263
+ * Subscribe to neighbourhood-state events on a perspective. `cb` fires
264
+ * when THIS executor claims / finishes / abandons a batch for any
265
+ * processor on `uuid` — perspective-scoped observability so a UI can
266
+ * render "someone is auto-processing this" without receiving the batch
267
+ * payload or LLM I/O. Registered on the per-uuid `#linkUnsubscribers`
268
+ * map so `PerspectiveProxy.dispose()` sweeps it up.
269
+ */
270
+ async addAutoProcessorNeighbourhoodStateListener(uuid, cb) {
271
+ const unsub = __classPrivateFieldGet(this, _PerspectiveClient_apiClient, "f").subscribe((data) => {
272
+ if (data.type === 'auto-processor-neighbourhood-state' && data.perspectiveUuid === uuid) {
273
+ cb(data);
274
+ }
275
+ });
276
+ let existing = __classPrivateFieldGet(this, _PerspectiveClient_linkUnsubscribers, "f").get(uuid) || [];
277
+ existing.push(unsub);
278
+ __classPrivateFieldGet(this, _PerspectiveClient_linkUnsubscribers, "f").set(uuid, existing);
247
279
  await __classPrivateFieldGet(this, _PerspectiveClient_apiClient, "f").waitForSubscription();
248
280
  }
249
281
  async addLinkExpression(uuid, link, status = 'shared', batchId) {
@@ -11,7 +11,7 @@ import { AllInstancesResult } from "../model/types";
11
11
  import type { TranscriptTurn } from "../generated/api";
12
12
  import { SHACLShape } from "../shacl/SHACLShape";
13
13
  import { SHACLFlow } from "../shacl/SHACLFlow";
14
- import type { AddAutoProcessorConfig, AutoProcessorEvent, InterpretationOverlayInfo } from "./AutoProcessor";
14
+ import type { AddAutoProcessorConfig, AutoProcessorEvent, AutoProcessorNeighbourhoodStateEvent, InterpretationOverlayInfo } from "./AutoProcessor";
15
15
  type QueryCallback = (result: AllInstancesResult) => void;
16
16
  /** Proxy object for a subscribed Prolog query that provides real-time updates
17
17
  *
@@ -320,6 +320,14 @@ export declare class PerspectiveProxy {
320
320
  rejectInterpretation(base: string, property?: string): Promise<boolean>;
321
321
  /** Subscribe to this perspective's auto-processor step signals. */
322
322
  addAutoProcessorEventListener(cb: (event: AutoProcessorEvent) => void): Promise<void>;
323
+ /**
324
+ * Subscribe to this perspective's auto-processor neighbourhood-state
325
+ * events — fires when this executor claims / finishes / abandons a
326
+ * batch. Perspective-scoped, so a UI can render "someone is
327
+ * auto-processing this" without receiving the batch payload. See
328
+ * `AutoProcessorNeighbourhoodStateEvent`.
329
+ */
330
+ addAutoProcessorNeighbourhoodStateListener(cb: (event: AutoProcessorNeighbourhoodStateEvent) => void): Promise<void>;
323
331
  /**
324
332
  * Executes a Prolog query against the perspective's knowledge base.
325
333
  * This is a powerful way to find complex patterns in the graph.
@@ -539,6 +539,16 @@ export class PerspectiveProxy {
539
539
  async addAutoProcessorEventListener(cb) {
540
540
  return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").addAutoProcessorEventListener(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, cb);
541
541
  }
542
+ /**
543
+ * Subscribe to this perspective's auto-processor neighbourhood-state
544
+ * events — fires when this executor claims / finishes / abandons a
545
+ * batch. Perspective-scoped, so a UI can render "someone is
546
+ * auto-processing this" without receiving the batch payload. See
547
+ * `AutoProcessorNeighbourhoodStateEvent`.
548
+ */
549
+ async addAutoProcessorNeighbourhoodStateListener(cb) {
550
+ return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").addAutoProcessorNeighbourhoodStateListener(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, cb);
551
+ }
542
552
  /**
543
553
  * Executes a Prolog query against the perspective's knowledge base.
544
554
  * This is a powerful way to find complex patterns in the graph.
@@ -1411,20 +1421,20 @@ export class PerspectiveProxy {
1411
1421
  return null;
1412
1422
  }
1413
1423
  const flowUri = flowUriLinks[0].data.target;
1414
- // Compute alternate prefix for state/transition URIs
1415
- const alternatePrefix = flowUri.endsWith('Flow')
1416
- ? flowUri.slice(0, -4) + '.'
1417
- : flowUri + '.';
1418
- // Fetch flow links using SPARQL to match flowUri source OR alternatePrefix sources
1419
- const sparqlQuery = `SELECT ?s ?p ?o WHERE {
1420
- ?s ?p ?o .
1421
- FILTER(?s = <${flowUri}> || STRSTARTS(STR(?s), "${alternatePrefix}"))
1422
- }`;
1423
- const sparqlResult = await this.querySparql(sparqlQuery);
1424
- const flowLinks = (sparqlResult || []).map((r) => ({
1425
- source: r.s,
1426
- predicate: r.p,
1427
- target: r.o
1424
+ // Fetch flow-level links (hasState, hasTransition, flowable, startAction)
1425
+ const flowLevelLinks = await this.get(new LinkQuery({ source: flowUri }));
1426
+ // Collect state and transition URIs, then fetch their child links
1427
+ const childUris = flowLevelLinks
1428
+ .filter(l => l.data.predicate === "ad4m://hasState"
1429
+ || l.data.predicate === "ad4m://hasTransition")
1430
+ .map(l => l.data.target);
1431
+ const childResults = await Promise.all(childUris.map(uri => this.get(new LinkQuery({ source: uri }))));
1432
+ // Flatten into the {source, predicate, target} shape fromLinks expects
1433
+ const allExprs = [...flowLevelLinks, ...childResults.flat()];
1434
+ const flowLinks = allExprs.map(l => ({
1435
+ source: l.data.source,
1436
+ predicate: l.data.predicate,
1437
+ target: l.data.target
1428
1438
  }));
1429
1439
  return SHACLFlow.fromLinks(flowLinks, flowUri);
1430
1440
  }
@@ -36,9 +36,30 @@ export declare function parseSparqlCount(result: CountBinding[] | undefined | nu
36
36
  /**
37
37
  * Decode a `Literal`-encoded SPARQL binding back to a plain string.
38
38
  *
39
- * Mirrors Flux's local `parseLit` helper. Returns `''` for `undefined`/empty
40
- * input. Falls through to the raw value if decoding fails (defensive — the
41
- * binding may already be a plain string for unwrapped properties).
39
+ * Returns `''` for `undefined`/empty input. Falls through to the raw value
40
+ * if decoding fails — bindings against properties resolved through a custom
41
+ * language are already raw URIs and should pass through unchanged.
42
+ *
43
+ * Signed-envelope literals
44
+ * ------------------------
45
+ * Properties declared with `resolveLanguage: 'literal'` are written through
46
+ * the built-in `literal` language, which wraps the value in a signed
47
+ * expression envelope (`{ author, timestamp, data, proof }`) and encodes
48
+ * the whole envelope as a `literal:json:` URL — see
49
+ * `rust-executor/src/languages/mod.rs::expression_create` (literal branch).
50
+ * On read, `parseLit` unwraps `.data` from that envelope so callers get the
51
+ * original scalar value instead of the envelope JSON.
52
+ *
53
+ * The Channel V refactor moved most scalar properties to deterministic
54
+ * typed XSD literals which no longer round-trip through this envelope — for
55
+ * those properties the SPARQL binding is already the lexical form and this
56
+ * helper decodes to the primitive. Signed-envelope literals still exist
57
+ * for any property that opts back into `resolveLanguage: 'literal'` (e.g.
58
+ * per-message provenance for chat bodies), which is why the `.data` unwrap
59
+ * is preserved here.
60
+ *
61
+ * Non-envelope JSON objects (`literal:json:` payloads that are not signed
62
+ * envelopes) are JSON-stringified for display.
42
63
  */
43
64
  export declare function parseLit(val: string | undefined | null): string;
44
65
  /** Decode a `Literal`-encoded binding to a number. Returns 0 on empty/invalid input. */
@@ -31,23 +31,74 @@ export function parseSparqlCount(result) {
31
31
  /**
32
32
  * Decode a `Literal`-encoded SPARQL binding back to a plain string.
33
33
  *
34
- * Mirrors Flux's local `parseLit` helper. Returns `''` for `undefined`/empty
35
- * input. Falls through to the raw value if decoding fails (defensive — the
36
- * binding may already be a plain string for unwrapped properties).
34
+ * Returns `''` for `undefined`/empty input. Falls through to the raw value
35
+ * if decoding fails — bindings against properties resolved through a custom
36
+ * language are already raw URIs and should pass through unchanged.
37
+ *
38
+ * Signed-envelope literals
39
+ * ------------------------
40
+ * Properties declared with `resolveLanguage: 'literal'` are written through
41
+ * the built-in `literal` language, which wraps the value in a signed
42
+ * expression envelope (`{ author, timestamp, data, proof }`) and encodes
43
+ * the whole envelope as a `literal:json:` URL — see
44
+ * `rust-executor/src/languages/mod.rs::expression_create` (literal branch).
45
+ * On read, `parseLit` unwraps `.data` from that envelope so callers get the
46
+ * original scalar value instead of the envelope JSON.
47
+ *
48
+ * The Channel V refactor moved most scalar properties to deterministic
49
+ * typed XSD literals which no longer round-trip through this envelope — for
50
+ * those properties the SPARQL binding is already the lexical form and this
51
+ * helper decodes to the primitive. Signed-envelope literals still exist
52
+ * for any property that opts back into `resolveLanguage: 'literal'` (e.g.
53
+ * per-message provenance for chat bodies), which is why the `.data` unwrap
54
+ * is preserved here.
55
+ *
56
+ * Non-envelope JSON objects (`literal:json:` payloads that are not signed
57
+ * envelopes) are JSON-stringified for display.
37
58
  */
38
59
  export function parseLit(val) {
39
60
  if (val === undefined || val === null || val === '')
40
61
  return '';
62
+ // Fast-path 1: `literal:*` URLs from properties written through the built-in
63
+ // `literal` language. On Channel V typed-XSD-literal properties, these
64
+ // decode straight to a primitive; on `resolveLanguage: 'literal'` properties
65
+ // (per-message provenance in chat/synergy) they decode to a signed-envelope
66
+ // object we unwrap via `.data`.
41
67
  try {
42
68
  const result = Literal.fromUrl(val).get();
43
- if (result && typeof result === 'object') {
44
- return result.data ?? JSON.stringify(result);
69
+ if (typeof result === 'object' && result !== null) {
70
+ const data = result.data;
71
+ if (typeof data === 'string')
72
+ return data;
73
+ return JSON.stringify(result);
45
74
  }
46
75
  return String(result);
47
76
  }
48
77
  catch {
49
- return val;
78
+ // fall through to plain-JSON envelope detection
79
+ }
80
+ // Fast-path 2: envelope stored/returned as a bare JSON string rather than a
81
+ // `literal:json:*` URL. Depending on the storage backend and query path,
82
+ // SPARQL bindings for `resolveLanguage: 'literal'` properties can surface
83
+ // the envelope object directly as its JSON serialisation (Oxigraph typed
84
+ // xsd:string of the JSON, or a Channel V pass-through) instead of the URL
85
+ // form. Detect that shape by parsing the string and unwrapping `.data`
86
+ // when it looks like a signed envelope; anything else passes through
87
+ // unchanged so plain text (e.g. "just a string") is not corrupted.
88
+ if (val.length >= 2 && val.charCodeAt(0) === 0x7b /* '{' */) {
89
+ try {
90
+ const parsed = JSON.parse(val);
91
+ if (parsed && typeof parsed === 'object') {
92
+ const data = parsed.data;
93
+ if (typeof data === 'string')
94
+ return data;
95
+ }
96
+ }
97
+ catch {
98
+ // not JSON — fall through and return the raw value
99
+ }
50
100
  }
101
+ return val;
51
102
  }
52
103
  /** Decode a `Literal`-encoded binding to a number. Returns 0 on empty/invalid input. */
53
104
  export function parseLitNumber(val) {
@@ -51,7 +51,13 @@ export interface SHACLPropertyShape {
51
51
  local?: boolean;
52
52
  /** AD4M-specific: Writable property */
53
53
  writable?: boolean;
54
- /** AD4M-specific: Language to resolve property values through */
54
+ /** AD4M-specific: sole selector of storage mode:
55
+ * - unset → deterministic typed literal (fast POS-index
56
+ * path, the default for a plain `@Property()`).
57
+ * - `"literal"` → signed envelope on the built-in literal
58
+ * language (per-value provenance, e.g. Flux
59
+ * message bodies).
60
+ * - `<custom address>` → `expression_create` on that custom language. */
55
61
  resolveLanguage?: string;
56
62
  /** AD4M-specific: Setter action for this property */
57
63
  setter?: AD4MAction[];
@@ -96,8 +102,10 @@ export interface SHACLPropertyShape {
96
102
  * hydration via `include`. */
97
103
  filter?: boolean;
98
104
  /** AD4M-specific: Transform expression (SHACL-AF Node Expression).
99
- * Applied to resolved property values in the Rust model query engine.
100
- * Only used for properties with resolveLanguage set. */
105
+ * Applied to a property's resolved value in the Rust model query engine —
106
+ * for values resolved through a `resolveLanguage` (`"literal"` for a signed
107
+ * envelope, or a custom language) and for any property that declares a
108
+ * transform. */
101
109
  transform?: NodeExpression;
102
110
  /** AD4M-specific: Natural-language hint that steers the generic LLM
103
111
  * extractor when producing typed instances from a transcript. Emitted
@@ -185,6 +185,13 @@ export class SHACLShape {
185
185
  if (prop.writable !== undefined) {
186
186
  turtle += ` ad4m:writable ${prop.writable} ;\n`;
187
187
  }
188
+ // Interpreter dedup key: `toLinks()` and `toJSON()` preserve
189
+ // `identity`; a Turtle export must too or the round-trip through
190
+ // Turtle silently drops the interpretation-dedup marker
191
+ // (CodeRabbit #881 review).
192
+ if (prop.identity !== undefined) {
193
+ turtle += ` ad4m:identity ${prop.identity} ;\n`;
194
+ }
188
195
  // Remove trailing semicolon and close bracket
189
196
  turtle = turtle.slice(0, -2) + '\n';
190
197
  turtle += isLast ? ` ] .\n` : ` ] ;\n`;
@@ -574,10 +581,15 @@ export class SHACLShape {
574
581
  val = val.substring(8);
575
582
  prop.writable = val === 'true';
576
583
  }
584
+ // The general language selector (e.g. "literal" or a custom address).
577
585
  const resolveLangLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://resolveLanguage");
578
586
  if (resolveLangLink) {
579
587
  prop.resolveLanguage = resolveLangLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
580
588
  }
589
+ // Storage mode is derived from `resolveLanguage` alone:
590
+ // - unset → deterministic typed literal (fast path)
591
+ // - "literal" → signed envelope on the built-in literal language
592
+ // - <address> → expression on that custom language
581
593
  // Parse action arrays
582
594
  const setterLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://setter");
583
595
  if (setterLink) {
@@ -744,6 +756,7 @@ export class SHACLShape {
744
756
  filter: p.filter,
745
757
  transform: p.transform,
746
758
  interpretation_hint: p.interpretationHint,
759
+ identity: p.identity,
747
760
  })),
748
761
  constructor_actions: this.constructor_actions,
749
762
  destructor_actions: this.destructor_actions,
@@ -775,7 +788,7 @@ export class SHACLShape {
775
788
  hasValue: p.has_value,
776
789
  local: p.local,
777
790
  writable: p.writable,
778
- resolveLanguage: p.resolve_language,
791
+ resolveLanguage: p.resolve_language ?? p.resolveLanguage,
779
792
  setter: p.setter,
780
793
  adder: p.adder,
781
794
  remover: p.remover,
@@ -790,6 +803,7 @@ export class SHACLShape {
790
803
  filter: p.filter,
791
804
  transform: p.transform,
792
805
  interpretationHint: p.interpretation_hint,
806
+ identity: p.identity,
793
807
  });
794
808
  }
795
809
  if (json.constructor_actions) {
@@ -21,7 +21,7 @@ export { focus, literal, path, exists, ifExpr, concat, coalesce, fn, };
21
21
  * ```typescript
22
22
  * @Property({
23
23
  * through: 'we://image',
24
- * resolveLanguage: FILE_STORAGE_LANGUAGE,
24
+ * resolveLanguage: 'literal',
25
25
  * transform: fileToDataUri,
26
26
  * })
27
27
  * avatar?: string;
@@ -20,7 +20,7 @@ export { focus, literal, path, exists, ifExpr, concat, coalesce, fn, };
20
20
  * ```typescript
21
21
  * @Property({
22
22
  * through: 'we://image',
23
- * resolveLanguage: FILE_STORAGE_LANGUAGE,
23
+ * resolveLanguage: 'literal',
24
24
  * transform: fileToDataUri,
25
25
  * })
26
26
  * avatar?: string;
package/package.json CHANGED
@@ -39,7 +39,7 @@
39
39
  "@rollup/plugin-commonjs": "^20.0.0",
40
40
  "@rollup/plugin-node-resolve": "^13.0.4",
41
41
  "@types/jest": "^29",
42
- "@types/node": "*",
42
+ "@types/node": "^24",
43
43
  "concat-md": "^0.5.0",
44
44
  "cross-fetch": "^3.1.4",
45
45
  "honkit": "^4.0.0",
@@ -61,5 +61,5 @@
61
61
  "pako": "2.1.0"
62
62
  }
63
63
  },
64
- "version": "0.13.0-test-interpretation"
64
+ "version": "0.13.0-test-interpretation-2"
65
65
  }
package/src/Literal.ts CHANGED
@@ -73,6 +73,13 @@ export class Literal {
73
73
  return parseFloat(numberString)
74
74
  }
75
75
 
76
+ if(body.startsWith("boolean:")) {
77
+ const boolString = decodeURIComponent(body.substring(8))
78
+ if (boolString === "true") return true
79
+ if (boolString === "false") return false
80
+ throw new Error(`Can't parse boolean literal: ${boolString}`)
81
+ }
82
+
76
83
  if(body.startsWith("json:")) {
77
84
  const json = body.substring(5)
78
85
  return JSON.parse(decodeURIComponent(json))