@coasys/ad4m 0.13.0-test-model-layer → 0.13.0-test-inverse-relations
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.
- package/lib/index.cjs +432 -46
- package/lib/index.js +430 -47
- package/lib/src/ai/AIClient.d.ts +13 -0
- package/lib/src/ai/AIClient.js +15 -0
- package/lib/src/model/Ad4mModel.js +14 -6
- package/lib/src/model/ModelQueryBuilder.js +13 -3
- package/lib/src/model/query-common.d.ts +10 -1
- package/lib/src/model/query-common.js +16 -0
- package/lib/src/model/query-sparql.js +25 -1
- package/lib/src/model/shacl-gen.js +12 -0
- package/lib/src/model/types.d.ts +91 -1
- package/lib/src/model/types.js +9 -0
- package/lib/src/perspectives/AutoProcessor.d.ts +8 -0
- package/lib/src/perspectives/FlowInstance.d.ts +30 -12
- package/lib/src/perspectives/FlowInstance.js +36 -13
- package/lib/src/perspectives/FlowModels.d.ts +7 -1
- package/lib/src/perspectives/FlowModels.js +8 -2
- package/lib/src/perspectives/PerspectiveClient.d.ts +16 -0
- package/lib/src/perspectives/PerspectiveClient.js +12 -0
- package/lib/src/perspectives/PerspectiveProxy.d.ts +31 -3
- package/lib/src/perspectives/PerspectiveProxy.js +78 -2
- package/lib/src/perspectives/WakerSubscriptionManager.d.ts +55 -5
- package/lib/src/perspectives/WakerSubscriptionManager.js +183 -8
- package/package.json +1 -1
- package/src/ai/AIClient.ts +16 -0
- package/src/model/Ad4mModel.test.ts +79 -0
- package/src/model/Ad4mModel.ts +14 -6
- package/src/model/ModelQueryBuilder.ts +13 -3
- package/src/model/query-common.ts +20 -1
- package/src/model/query-sparql.ts +28 -1
- package/src/model/shacl-gen.ts +12 -0
- package/src/model/shacl-roundtrip.test.ts +71 -0
- package/src/model/types.ts +96 -1
- package/src/perspectives/AutoProcessor.ts +8 -0
- package/src/perspectives/FlowInstance.ts +39 -13
- package/src/perspectives/FlowModels.ts +8 -2
- package/src/perspectives/PerspectiveClient.ts +28 -0
- package/src/perspectives/PerspectiveProxy.test.ts +154 -0
- package/src/perspectives/PerspectiveProxy.ts +84 -5
- package/src/perspectives/WakerSubscriptionManager.test.ts +199 -0
- package/src/perspectives/WakerSubscriptionManager.ts +197 -9
package/src/model/Ad4mModel.ts
CHANGED
|
@@ -7,7 +7,7 @@ import { makeRandomId } from "./util";
|
|
|
7
7
|
import { getPropertiesMetadata, getRelationsMetadata, setPropertyRegistryEntry, setRelationRegistryEntry, Model } from "./decorators";
|
|
8
8
|
import type { PropertyOptions, PropertyMetadataEntry, RelationMetadataEntry } from "./decorators";
|
|
9
9
|
import { formatQueryValue, compileWhereClause } from "./query-utils";
|
|
10
|
-
import { resolveParentPredicate } from "./query-common";
|
|
10
|
+
import { requireSingleParent, resolveParentPredicate } from "./query-common";
|
|
11
11
|
import { isArrayType, determinePredicate, determineNamespace, buildModelFromJSONSchema } from "./json-schema";
|
|
12
12
|
import type { SHACLShape } from "../shacl/SHACLShape";
|
|
13
13
|
import type { JSONSchemaProperty, JSONSchema, JSONSchemaToModelOptions } from "./json-schema";
|
|
@@ -24,6 +24,7 @@ import type {
|
|
|
24
24
|
IncludeProjection,
|
|
25
25
|
TypedQuery, IncludeExtras, IncludeOf,
|
|
26
26
|
} from "./types";
|
|
27
|
+
import { isTraverseScope } from "./types";
|
|
27
28
|
|
|
28
29
|
|
|
29
30
|
|
|
@@ -990,7 +991,12 @@ export class Ad4mModel {
|
|
|
990
991
|
const queryInput: any = {};
|
|
991
992
|
if (query.parent) {
|
|
992
993
|
const parentPredicate = resolveParentPredicate(query.parent, this);
|
|
993
|
-
|
|
994
|
+
// A traversal is forwarded as it was written: the executor reads `ids`,
|
|
995
|
+
// and flattening it to one `id` here is how a request for a whole level
|
|
996
|
+
// would quietly become a request for one parent's children.
|
|
997
|
+
queryInput.parent = isTraverseScope(query.parent)
|
|
998
|
+
? { ...query.parent, predicate: parentPredicate }
|
|
999
|
+
: { id: query.parent.id, predicate: parentPredicate };
|
|
994
1000
|
}
|
|
995
1001
|
if (query.properties) queryInput.properties = query.properties;
|
|
996
1002
|
if (query.include) {
|
|
@@ -1880,9 +1886,10 @@ export class Ad4mModel {
|
|
|
1880
1886
|
if (options?.parent && !options?.batchId) {
|
|
1881
1887
|
const batchId = await perspective.createBatch();
|
|
1882
1888
|
await instance.save(batchId);
|
|
1883
|
-
const
|
|
1889
|
+
const parent = requireSingleParent(options.parent);
|
|
1890
|
+
const predicate = resolveParentPredicate(parent, this);
|
|
1884
1891
|
const link = new Link({
|
|
1885
|
-
source:
|
|
1892
|
+
source: parent.id,
|
|
1886
1893
|
predicate,
|
|
1887
1894
|
target: instance.id,
|
|
1888
1895
|
});
|
|
@@ -1898,9 +1905,10 @@ export class Ad4mModel {
|
|
|
1898
1905
|
|
|
1899
1906
|
// Create parent → child link if a parent scope was provided
|
|
1900
1907
|
if (options?.parent) {
|
|
1901
|
-
const
|
|
1908
|
+
const parent = requireSingleParent(options.parent);
|
|
1909
|
+
const predicate = resolveParentPredicate(parent, this);
|
|
1902
1910
|
const link = new Link({
|
|
1903
|
-
source:
|
|
1911
|
+
source: parent.id,
|
|
1904
1912
|
predicate,
|
|
1905
1913
|
target: instance.id,
|
|
1906
1914
|
});
|
|
@@ -407,13 +407,10 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
|
|
|
407
407
|
(rawResult: any) => {
|
|
408
408
|
try {
|
|
409
409
|
const results = parseResults(rawResult);
|
|
410
|
-
console.debug(`[ModelQueryBuilder.subscribe] Update received for ${subscriptionId}: ${results.length} instances`);
|
|
411
410
|
const fp = buildFingerprint(results);
|
|
412
411
|
if (fp === lastResultFingerprint) {
|
|
413
|
-
console.debug(`[ModelQueryBuilder.subscribe] Fingerprint unchanged, skipping callback`);
|
|
414
412
|
return;
|
|
415
413
|
}
|
|
416
|
-
console.debug(`[ModelQueryBuilder.subscribe] Fingerprint changed, calling callback with ${results.length} results`);
|
|
417
414
|
lastResultFingerprint = fp;
|
|
418
415
|
callback(results);
|
|
419
416
|
} catch (e) {
|
|
@@ -711,8 +708,21 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
|
|
|
711
708
|
count: true,
|
|
712
709
|
};
|
|
713
710
|
|
|
711
|
+
// Each server dispatch triggers an independent async re-fetch, and those
|
|
712
|
+
// re-fetches resolve in completion order, not dispatch order. A re-fetch
|
|
713
|
+
// dispatched *before* a write committed can resolve *after* the re-fetch
|
|
714
|
+
// that saw the write, silently rolling the consumer back to a stale page —
|
|
715
|
+
// and no later dispatch ever corrects it. The generation counter drops any
|
|
716
|
+
// fetch that is no longer the newest one started; the newest fetch always
|
|
717
|
+
// delivers, so the callback is monotone in dispatch order.
|
|
718
|
+
let fetchGeneration = 0;
|
|
714
719
|
const processResults = async () => {
|
|
720
|
+
const generation = ++fetchGeneration;
|
|
715
721
|
const { results, totalCount } = await (ctor as any).executeModelQuery(this.perspective, paginatedQuery, this.modelClassName);
|
|
722
|
+
if (generation !== fetchGeneration) {
|
|
723
|
+
console.debug(`[ModelQueryBuilder.paginateSubscribe] Dropping stale re-fetch result (generation ${generation}, newest ${fetchGeneration})`);
|
|
724
|
+
return;
|
|
725
|
+
}
|
|
716
726
|
callback({ results, totalCount, pageSize, pageNumber });
|
|
717
727
|
};
|
|
718
728
|
|
|
@@ -2,7 +2,8 @@
|
|
|
2
2
|
* Shared query helpers used by both the Prolog and SPARQL query pipelines.
|
|
3
3
|
*/
|
|
4
4
|
|
|
5
|
-
import type { Scope } from "./types";
|
|
5
|
+
import type { Scope, TraverseScope } from "./types";
|
|
6
|
+
import { isTraverseScope } from "./types";
|
|
6
7
|
import { getRelationsMetadata } from "./decorators";
|
|
7
8
|
|
|
8
9
|
/**
|
|
@@ -14,6 +15,24 @@ import { getRelationsMetadata } from "./decorators";
|
|
|
14
15
|
* - With `field`: direct key lookup
|
|
15
16
|
* - Without `field`: scan for a relation whose `target()` matches `childCtor`
|
|
16
17
|
*/
|
|
18
|
+
/**
|
|
19
|
+
* Narrow a scope to the one-parent forms, for the paths that write a link.
|
|
20
|
+
*
|
|
21
|
+
* A traversal describes a read outward from several anchors. Creating a record
|
|
22
|
+
* "under" one would have to pick which, and nothing in the scope says — so this
|
|
23
|
+
* refuses rather than guessing at the first of the list. The executor's write
|
|
24
|
+
* scopes refuse it for the same reason.
|
|
25
|
+
*/
|
|
26
|
+
export function requireSingleParent(parent: Scope): Exclude<Scope, TraverseScope> {
|
|
27
|
+
if (isTraverseScope(parent)) {
|
|
28
|
+
throw new Error(
|
|
29
|
+
'parent(): a traverse scope describes a read and names no single parent to write under. ' +
|
|
30
|
+
'Use { id, predicate } or { model, id } when creating a record under a parent.',
|
|
31
|
+
);
|
|
32
|
+
}
|
|
33
|
+
return parent;
|
|
34
|
+
}
|
|
35
|
+
|
|
17
36
|
export function resolveParentPredicate(
|
|
18
37
|
parent: Scope,
|
|
19
38
|
childCtor: Function,
|
|
@@ -15,6 +15,7 @@ import { Literal } from "../Literal";
|
|
|
15
15
|
import { resolveParentPredicate } from "./query-common";
|
|
16
16
|
import type { RelationMetadataEntry } from "./decorators";
|
|
17
17
|
import type { Where, Query, ModelMetadata, PropertyMetadata } from "./types";
|
|
18
|
+
import { isTraverseScope } from "./types";
|
|
18
19
|
|
|
19
20
|
/**
|
|
20
21
|
* Check whether a `where` clause contains filters that cannot be pushed down
|
|
@@ -272,8 +273,34 @@ export function buildSPARQLQuery(
|
|
|
272
273
|
// Parent filter — direct triple pattern
|
|
273
274
|
if (query.parent) {
|
|
274
275
|
const parentPredicate = resolveParentPredicate(query.parent, modelClass);
|
|
275
|
-
|
|
276
|
+
if (isTraverseScope(query.parent)) {
|
|
277
|
+
const { ids, transitive, direction, limitPerAnchor } = query.parent;
|
|
278
|
+
// `limitPerAnchor` is applied by the executor between selecting ids and
|
|
279
|
+
// hydrating them, which is a shape this path does not have — it builds one
|
|
280
|
+
// query and reads the rows. Refused rather than ignored: quietly returning
|
|
281
|
+
// every reply where five per parent were asked for is a wrong answer that
|
|
282
|
+
// looks like a right one.
|
|
283
|
+
if (limitPerAnchor !== undefined) {
|
|
284
|
+
throw new Error(
|
|
285
|
+
'buildSPARQLQuery: limitPerAnchor is applied by the executor between query phases and ' +
|
|
286
|
+
'has no equivalent here. Use the model query path for per-anchor limits.',
|
|
287
|
+
);
|
|
288
|
+
}
|
|
289
|
+
const anchors = (Array.isArray(ids) ? ids : [ids]).map(iri).join(' ');
|
|
290
|
+
const path = transitive ? '+' : '';
|
|
291
|
+
joinPatterns.push(`
|
|
292
|
+
VALUES ?_anchor { ${anchors} }`);
|
|
293
|
+
joinPatterns.push(
|
|
294
|
+
direction === 'in'
|
|
295
|
+
? `
|
|
296
|
+
?source ${iri(parentPredicate)}${path} ?_anchor .`
|
|
297
|
+
: `
|
|
298
|
+
?_anchor ${iri(parentPredicate)}${path} ?source .`,
|
|
299
|
+
);
|
|
300
|
+
} else {
|
|
301
|
+
joinPatterns.push(`
|
|
276
302
|
${iri(query.parent.id)} ${iri(parentPredicate)} ?source .`);
|
|
303
|
+
}
|
|
277
304
|
}
|
|
278
305
|
|
|
279
306
|
// Required property JOIN patterns — direct triple patterns
|
package/src/model/shacl-gen.ts
CHANGED
|
@@ -124,6 +124,18 @@ export function buildSHACL(
|
|
|
124
124
|
|
|
125
125
|
if (!propMeta.through) continue; // Skip properties without predicates
|
|
126
126
|
|
|
127
|
+
// `@BelongsToOne`/`@BelongsToMany` register in both maps: the relation
|
|
128
|
+
// registry describes the edge, and `applyPropertyMetadata` marks the
|
|
129
|
+
// accessor read-only so the non-owning side gets no setter. Both loops
|
|
130
|
+
// then emitted a shape for it, so an inverse relation appeared twice in
|
|
131
|
+
// the generated SHACL — once thinly, from here, and once with its target
|
|
132
|
+
// class, polymorphism and ordering, from the relation loop below.
|
|
133
|
+
//
|
|
134
|
+
// The relation loop is the complete description, so this one stands
|
|
135
|
+
// aside. Skipping by presence in the relation map rather than by kind
|
|
136
|
+
// keeps it right for any future decorator that registers in both.
|
|
137
|
+
if (allRelationsMeta[propName]) continue;
|
|
138
|
+
|
|
127
139
|
const propShape: SHACLPropertyShape = {
|
|
128
140
|
name: propName,
|
|
129
141
|
path: propMeta.through,
|
|
@@ -403,3 +403,74 @@ describe("Decorators → SHACL writer round-trip", () => {
|
|
|
403
403
|
).toBeUndefined();
|
|
404
404
|
});
|
|
405
405
|
});
|
|
406
|
+
|
|
407
|
+
/**
|
|
408
|
+
* An inverse relation is registered twice by design: once in the relation
|
|
409
|
+
* registry, which describes the edge, and once as property metadata, which is
|
|
410
|
+
* what makes the accessor read-only. Both were then emitted into the shape, so
|
|
411
|
+
* `generateSHACL()` described the property twice — once thinly and once with
|
|
412
|
+
* its target class and options.
|
|
413
|
+
*
|
|
414
|
+
* A duplicate is not cosmetic. The executor reads the shape to decide what a
|
|
415
|
+
* class has; two entries for one name mean two conformance patterns and two
|
|
416
|
+
* hydration passes for the same predicate, and any consumer comparing a shape
|
|
417
|
+
* against a manifest sees a property the manifest cannot produce.
|
|
418
|
+
*/
|
|
419
|
+
describe("inverse relations appear once in the generated shape", () => {
|
|
420
|
+
@Model({ name: "RoundTripParent" })
|
|
421
|
+
class RoundTripParent extends Ad4mModel {
|
|
422
|
+
@HasMany({ through: "test://child" })
|
|
423
|
+
children: string[] = [];
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
@Model({ name: "RoundTripChild" })
|
|
427
|
+
class RoundTripChild extends Ad4mModel {
|
|
428
|
+
@BelongsToOne({ through: "test://child" })
|
|
429
|
+
parent?: string;
|
|
430
|
+
|
|
431
|
+
@BelongsToMany({ through: "test://tagged" })
|
|
432
|
+
taggedBy: string[] = [];
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
const propertiesOf = (cls: any): any[] =>
|
|
436
|
+
(cls.generateSHACL().shape?.properties ?? []) as any[];
|
|
437
|
+
|
|
438
|
+
it("emits one shape per inverse relation", () => {
|
|
439
|
+
const names = propertiesOf(RoundTripChild).map((p) => p.name);
|
|
440
|
+
expect(names.filter((n) => n === "parent")).toHaveLength(1);
|
|
441
|
+
expect(names.filter((n) => n === "taggedBy")).toHaveLength(1);
|
|
442
|
+
});
|
|
443
|
+
|
|
444
|
+
it("keeps the relation loop's description rather than the property loop's", () => {
|
|
445
|
+
const parent = propertiesOf(RoundTripChild).find((p) => p.name === "parent");
|
|
446
|
+
expect(parent.path).toBe("test://child");
|
|
447
|
+
// maxCount is the relation loop's contribution: belongsToOne is scalar.
|
|
448
|
+
expect(parent.maxCount).toBe(1);
|
|
449
|
+
});
|
|
450
|
+
|
|
451
|
+
it("leaves the owning side alone", () => {
|
|
452
|
+
const names = propertiesOf(RoundTripParent).map((p) => p.name);
|
|
453
|
+
expect(names.filter((n) => n === "children")).toHaveLength(1);
|
|
454
|
+
});
|
|
455
|
+
|
|
456
|
+
/**
|
|
457
|
+
* The forward and inverse of one link share a predicate, so a consumer
|
|
458
|
+
* keying shape properties by path finds two. That is correct and worth
|
|
459
|
+
* pinning: it is what made a downstream sort non-deterministic.
|
|
460
|
+
*/
|
|
461
|
+
it("lets a forward and inverse relation share one predicate", () => {
|
|
462
|
+
@Model({ name: "RoundTripBoth" })
|
|
463
|
+
class RoundTripBoth extends Ad4mModel {
|
|
464
|
+
@HasMany({ through: "test://comment" })
|
|
465
|
+
comments: string[] = [];
|
|
466
|
+
|
|
467
|
+
@BelongsToOne({ through: "test://comment" })
|
|
468
|
+
inReplyTo?: string;
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
const props = propertiesOf(RoundTripBoth).filter(
|
|
472
|
+
(p) => p.path === "test://comment",
|
|
473
|
+
);
|
|
474
|
+
expect(props.map((p) => p.name).sort()).toEqual(["comments", "inReplyTo"]);
|
|
475
|
+
});
|
|
476
|
+
});
|
package/src/model/types.ts
CHANGED
|
@@ -64,10 +64,91 @@ export type Order = { [propertyName: string]: "ASC" | "DESC" };
|
|
|
64
64
|
* predicate to write.
|
|
65
65
|
*
|
|
66
66
|
* **Raw form** — explicit predicate string, no metadata lookup.
|
|
67
|
+
*
|
|
68
|
+
* **Traverse form** — bounded traversal from one or more anchors, for reading
|
|
69
|
+
* a tree rather than one node's children. Read-only: AutoProcessor's write
|
|
70
|
+
* scopes reject it, because it names no single parent to write under.
|
|
67
71
|
*/
|
|
68
72
|
export type Scope =
|
|
69
73
|
| { model: typeof Ad4mModel; id: string; field?: string }
|
|
70
|
-
| { id: string; predicate: string }
|
|
74
|
+
| { id: string; predicate: string }
|
|
75
|
+
| TraverseScope;
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Walk a predicate from several anchors at once, and optionally all the way
|
|
79
|
+
* down.
|
|
80
|
+
*
|
|
81
|
+
* This exists because a tree read one level at a time costs a round trip per
|
|
82
|
+
* level and — under a subscription — one subscription per *parent*. Asking for
|
|
83
|
+
* every anchor in one query makes both proportional to depth instead.
|
|
84
|
+
*/
|
|
85
|
+
export interface TraverseScope {
|
|
86
|
+
/** The anchors to walk from. A bare string is the single-anchor spelling. */
|
|
87
|
+
ids: string | string[];
|
|
88
|
+
predicate: string;
|
|
89
|
+
/**
|
|
90
|
+
* Follow the predicate as far as it goes rather than one step.
|
|
91
|
+
*
|
|
92
|
+
* The result is a flat set of everything reachable, and it does **not**
|
|
93
|
+
* describe the shape it came from: SPARQL property paths bind no intermediate
|
|
94
|
+
* variables, so a row says that it is under the anchor and never where. To
|
|
95
|
+
* rebuild a tree, read the inverse relation (`@BelongsToOne`) alongside it and
|
|
96
|
+
* assemble from the parent each row reports.
|
|
97
|
+
*
|
|
98
|
+
* Excludes the anchor itself.
|
|
99
|
+
*/
|
|
100
|
+
transitive?: boolean;
|
|
101
|
+
/**
|
|
102
|
+
* `'out'` (default) matches `anchor --predicate--> result`; `'in'` matches
|
|
103
|
+
* `result --predicate--> anchor`, which is how to *search* among the things
|
|
104
|
+
* pointing at a node — ordered, filtered, limited. A reverse `include`
|
|
105
|
+
* answers the same question for rows already in hand, but cannot narrow them.
|
|
106
|
+
*/
|
|
107
|
+
direction?: 'out' | 'in';
|
|
108
|
+
/**
|
|
109
|
+
* Keep at most this many results per anchor — "the top 5 replies under each
|
|
110
|
+
* of these 20 comments" in one query.
|
|
111
|
+
*
|
|
112
|
+
* Applied by the executor between selecting ids and hydrating them, because
|
|
113
|
+
* SPARQL has no per-group limit (no window functions, and sub-SELECTs are
|
|
114
|
+
* uncorrelated). The practical consequence is that the over-fetch is paid in
|
|
115
|
+
* ids, not records: a branch with 3,000 replies costs 3,000 strings and
|
|
116
|
+
* hydrates 5.
|
|
117
|
+
*
|
|
118
|
+
* Pair it with `order` — without one the "top" N is whatever the store
|
|
119
|
+
* happened to return first.
|
|
120
|
+
*/
|
|
121
|
+
limitPerAnchor?: number;
|
|
122
|
+
/**
|
|
123
|
+
* Walk the relation level by level, keeping this many results per anchor at each depth —
|
|
124
|
+
* `[10, 5, 3]` is "ten replies, five under each of those, three under each of *those*".
|
|
125
|
+
*
|
|
126
|
+
* The walk happens in the executor, which is the point of it. A caller can drive the same walk by
|
|
127
|
+
* asking for one level and using the ids as the next level's anchors, but each step is then a
|
|
128
|
+
* network round trip, and a UI that draws as each answer lands shows the tree assembling itself a
|
|
129
|
+
* level at a time. Inside the executor the levels are sequential queries against a local store
|
|
130
|
+
* with nothing serialised between them, and the records are hydrated once for the union — so
|
|
131
|
+
* three levels cost one request and one hydration rather than three of each.
|
|
132
|
+
*
|
|
133
|
+
* Results come back flat and breadth-first; read the inverse relation alongside to rebuild the
|
|
134
|
+
* tree, exactly as with `transitive`.
|
|
135
|
+
*
|
|
136
|
+
* Not combinable with `transitive`, which is the unbounded form of the same walk. Nor is
|
|
137
|
+
* `limitPerAnchor` a substitute: with a single anchor at the top there is one group, so it caps
|
|
138
|
+
* the total rather than the breadth at each level.
|
|
139
|
+
*/
|
|
140
|
+
levels?: number[];
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* Whether this scope is a traversal rather than a single named parent.
|
|
145
|
+
*
|
|
146
|
+
* The other two forms carry `id`; this one carries `ids` and may name several,
|
|
147
|
+
* so anything reaching for one parent — every write path — has to ask first.
|
|
148
|
+
*/
|
|
149
|
+
export function isTraverseScope(scope: Scope): scope is TraverseScope {
|
|
150
|
+
return 'ids' in scope;
|
|
151
|
+
}
|
|
71
152
|
|
|
72
153
|
/**
|
|
73
154
|
* Describes which relations to eager-load when querying.
|
|
@@ -117,6 +198,20 @@ export interface IncludeProjection {
|
|
|
117
198
|
from: string;
|
|
118
199
|
/** When true, attaches an integer count instead of a list. */
|
|
119
200
|
count?: true;
|
|
201
|
+
/**
|
|
202
|
+
* Project over everything reachable through `from`, not just one step.
|
|
203
|
+
*
|
|
204
|
+
* `{ from: 'comments', count: true, transitive: true }` is the whole
|
|
205
|
+
* conversation under each row rather than its direct replies — which is what
|
|
206
|
+
* a reader takes "42 replies" on a collapsed branch to mean. The projection
|
|
207
|
+
* query is already grouped per parent and already asked of every row at once,
|
|
208
|
+
* so this adds no round trip.
|
|
209
|
+
*
|
|
210
|
+
* Cannot be combined with a filter on the link's author or timestamp: those
|
|
211
|
+
* read the reification of one link, and a path has none. Such a projection is
|
|
212
|
+
* skipped with a warning rather than silently answering a different question.
|
|
213
|
+
*/
|
|
214
|
+
transitive?: boolean;
|
|
120
215
|
/**
|
|
121
216
|
* Bare class name of the projection target. Set automatically by
|
|
122
217
|
* `prepareModelQueryParams`; the executor resolves the target's shape
|
|
@@ -244,6 +244,14 @@ export interface AddAutoProcessorConfig {
|
|
|
244
244
|
basePrefix?: string;
|
|
245
245
|
/** Class URIs (SHACL `target_class`) to materialize each pass. */
|
|
246
246
|
interpretationClasses: string[];
|
|
247
|
+
/**
|
|
248
|
+
* Canonical flow URIs (`SHACLFlow` `{namespace}{name}Flow`) this processor
|
|
249
|
+
* is flow-aware of. Flow features — the flow-aware prompt, the
|
|
250
|
+
* transition-proposal pass, and auto-spawn on freshly created items — run
|
|
251
|
+
* only on the flows listed here, mirroring the class selection above.
|
|
252
|
+
* Omit (or pass `[]`) for no flow processing.
|
|
253
|
+
*/
|
|
254
|
+
flows?: string[];
|
|
247
255
|
/** Quiet-window (ms) after the last new item before a pass runs. */
|
|
248
256
|
debounceMs: number;
|
|
249
257
|
/** Minimum items before a pass runs (Flux "wait for N inputs"). Default 1. */
|
|
@@ -17,7 +17,7 @@
|
|
|
17
17
|
* than the `wrap` escape hatch, which exists for tests that already own
|
|
18
18
|
* a matched (record, shape) pair.
|
|
19
19
|
*
|
|
20
|
-
* # What's here
|
|
20
|
+
* # What's here, and what is still absent
|
|
21
21
|
*
|
|
22
22
|
* Read surface (implemented today, PR #929):
|
|
23
23
|
* - `uri`, `subject`, `flowName`, `currentStateName`, `startedAtMillis`
|
|
@@ -28,15 +28,22 @@
|
|
|
28
28
|
* - `proposals()` — queries `FlowTransitionProposal` records that
|
|
29
29
|
* target this instance's URI.
|
|
30
30
|
*
|
|
31
|
-
*
|
|
32
|
-
*
|
|
33
|
-
*
|
|
34
|
-
*
|
|
35
|
-
*
|
|
36
|
-
*
|
|
31
|
+
* - `acceptProposal()` / `rejectProposal()` — the consensus write API:
|
|
32
|
+
* accept counts your DID toward the flow's consensusRule and fires the
|
|
33
|
+
* transition at quorum; reject withdraws only the links you signed and
|
|
34
|
+
* resolves to how many went. Reject is not a cancel — another agent's
|
|
35
|
+
* proposal is theirs, and because state is recomputed from the links
|
|
36
|
+
* present now, withdrawing a vote that had settled an edge moves the
|
|
37
|
+
* flow back to where it stood before it.
|
|
38
|
+
*
|
|
39
|
+
* Still absent (rather than shipped as `throw new Error("not yet")`
|
|
40
|
+
* stubs): `proposeTransition`, `fireAction`, and the subscriptions
|
|
41
|
+
* (`onStateChange`, `onProposalAdded`, `onProposalResolved`) — they land
|
|
42
|
+
* with the manual-proposal and subscription-topic slices.
|
|
37
43
|
*/
|
|
38
44
|
|
|
39
45
|
import { PerspectiveProxy } from "./PerspectiveProxy";
|
|
46
|
+
import { FlowFireOutcome } from "./PerspectiveClient";
|
|
40
47
|
import { Ad4mModel } from "../model/Ad4mModel";
|
|
41
48
|
import { FlowInstanceRecord, FlowTransitionProposal } from "./FlowModels";
|
|
42
49
|
import { SHACLFlow, FlowState, FlowTransition } from "../shacl/SHACLFlow";
|
|
@@ -108,9 +115,15 @@ export class FlowInstance {
|
|
|
108
115
|
*
|
|
109
116
|
* The returned wrapper carries the parsed `SHACLFlow` alongside the
|
|
110
117
|
* on-graph record, so `currentState` / `availableTransitions` /
|
|
111
|
-
* `proposals` accessors work without further round-trips.
|
|
112
|
-
*
|
|
113
|
-
*
|
|
118
|
+
* `proposals` accessors work without further round-trips.
|
|
119
|
+
*
|
|
120
|
+
* The record's `currentState` is a per-replica cache the consensus engine
|
|
121
|
+
* writes as a local link. It is read back only for display — the cache-first
|
|
122
|
+
* path in `gather_active_flow_contexts` fills the state rendered into LLM
|
|
123
|
+
* context — and **never as authority**: anything that decides something
|
|
124
|
+
* (the fold, the mint pass) derives state from the signed links present now
|
|
125
|
+
* and does not consult the cache. Treat it as a display hint, not as the
|
|
126
|
+
* flow's state.
|
|
114
127
|
*
|
|
115
128
|
* @param perspective - The perspective the flow instance lives on
|
|
116
129
|
* @param flowName - Name of a `SHACLFlow` already registered on the perspective
|
|
@@ -283,7 +296,7 @@ export class FlowInstance {
|
|
|
283
296
|
* `FlowTransitionProposal.flowInstance` references).
|
|
284
297
|
*/
|
|
285
298
|
get uri(): string {
|
|
286
|
-
return
|
|
299
|
+
return this.record.id;
|
|
287
300
|
}
|
|
288
301
|
|
|
289
302
|
/**
|
|
@@ -358,12 +371,25 @@ export class FlowInstance {
|
|
|
358
371
|
* for the where-filter — one SPARQL round-trip, no client-side
|
|
359
372
|
* filtering.
|
|
360
373
|
*
|
|
361
|
-
*
|
|
362
|
-
*
|
|
374
|
+
* These are written by the executor's consensus pass when it mints a
|
|
375
|
+
* transition, and by clients proposing directly. Superseded proposals are
|
|
376
|
+
* not swept here — a stale one is simply never counted by the fold, and
|
|
377
|
+
* accepting it fails with a stale-state error.
|
|
363
378
|
*/
|
|
364
379
|
async proposals(): Promise<FlowTransitionProposal[]> {
|
|
365
380
|
return FlowTransitionProposal.findAll(this.perspective, {
|
|
366
381
|
where: { flowInstance: this.uri },
|
|
367
382
|
});
|
|
368
383
|
}
|
|
384
|
+
|
|
385
|
+
async acceptProposal(proposal: FlowTransitionProposal | string): Promise<FlowFireOutcome[]> {
|
|
386
|
+
const uri = typeof proposal === "string" ? proposal : proposal.id;
|
|
387
|
+
return this.perspective.acceptFlowProposal(uri);
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
/** Withdraw our own links from a proposal; resolves to how many went. */
|
|
391
|
+
async rejectProposal(proposal: FlowTransitionProposal | string): Promise<number> {
|
|
392
|
+
const uri = typeof proposal === "string" ? proposal : proposal.id;
|
|
393
|
+
return this.perspective.rejectFlowProposal(uri);
|
|
394
|
+
}
|
|
369
395
|
}
|
|
@@ -147,8 +147,14 @@ export class FlowInstanceRecord extends Ad4mModel {
|
|
|
147
147
|
@Property({ through: "ad4m://flow/base", required: true })
|
|
148
148
|
subject: string = "";
|
|
149
149
|
|
|
150
|
-
/**
|
|
151
|
-
|
|
150
|
+
/**
|
|
151
|
+
* The state name this replica's executor last derived for the flow — a
|
|
152
|
+
* per-replica cache written as a `local` link, never the authority (the
|
|
153
|
+
* fold over the signed proposals is). Optional on the shape: a row that
|
|
154
|
+
* synced in from a peer carries no value until the local consensus pass
|
|
155
|
+
* has run, so an empty string means "not yet derived here".
|
|
156
|
+
*/
|
|
157
|
+
@Property({ through: "ad4m://flow/current_state", local: true })
|
|
152
158
|
currentState: string = "";
|
|
153
159
|
|
|
154
160
|
// "When was this flow started?" is answered by `Ad4mModel`'s built-in
|
|
@@ -13,6 +13,16 @@ import { AllInstancesResult } from "../model/types";
|
|
|
13
13
|
import type { TranscriptTurn } from "../generated/api";
|
|
14
14
|
import type { AddAutoProcessorConfig, AutoProcessorEvent, AutoProcessorNeighbourhoodStateEvent, InterpretationOverlayInfo, RawScope, RunInterpretationObserveOptions } from "./AutoProcessor";
|
|
15
15
|
|
|
16
|
+
/** One fired flow transition, as returned by `perspective.acceptFlowProposal`
|
|
17
|
+
* (and, engine-side, by every consensus pass). */
|
|
18
|
+
export interface FlowFireOutcome {
|
|
19
|
+
instanceUri: string;
|
|
20
|
+
fromState: string;
|
|
21
|
+
toState: string;
|
|
22
|
+
voters: string[];
|
|
23
|
+
contributingProposalUris: string[];
|
|
24
|
+
}
|
|
25
|
+
|
|
16
26
|
export type PerspectiveHandleCallback = (perspective: PerspectiveHandle) => null
|
|
17
27
|
export type UuidCallback = (uuid: string) => null
|
|
18
28
|
export type LinkCallback = (link: LinkExpression) => null
|
|
@@ -395,6 +405,24 @@ export class PerspectiveClient {
|
|
|
395
405
|
)
|
|
396
406
|
}
|
|
397
407
|
|
|
408
|
+
async acceptFlowProposal(uuid: string, proposalUri: string): Promise<FlowFireOutcome[]> {
|
|
409
|
+
return this.#apiClient.call<FlowFireOutcome[]>(
|
|
410
|
+
'perspective.acceptFlowProposal', { uuid, proposalUri },
|
|
411
|
+
)
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
/**
|
|
415
|
+
* Withdraw this agent's own links from a proposal. Resolves to how many
|
|
416
|
+
* were retracted — one for a withdrawn vote, more when retracting a
|
|
417
|
+
* proposal this agent opened.
|
|
418
|
+
*/
|
|
419
|
+
async rejectFlowProposal(uuid: string, proposalUri: string): Promise<number> {
|
|
420
|
+
const result = await this.#apiClient.call<{ retractedLinks: number }>(
|
|
421
|
+
'perspective.rejectFlowProposal', { uuid, proposalUri },
|
|
422
|
+
)
|
|
423
|
+
return result.retractedLinks
|
|
424
|
+
}
|
|
425
|
+
|
|
398
426
|
/**
|
|
399
427
|
* Subscribe to auto-processor step signals. `cb` fires for every
|
|
400
428
|
* `auto-processor-event` on `uuid` (BatchReady → Claimed/BackedOff/… →
|