@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.
Files changed (41) hide show
  1. package/lib/index.cjs +432 -46
  2. package/lib/index.js +430 -47
  3. package/lib/src/ai/AIClient.d.ts +13 -0
  4. package/lib/src/ai/AIClient.js +15 -0
  5. package/lib/src/model/Ad4mModel.js +14 -6
  6. package/lib/src/model/ModelQueryBuilder.js +13 -3
  7. package/lib/src/model/query-common.d.ts +10 -1
  8. package/lib/src/model/query-common.js +16 -0
  9. package/lib/src/model/query-sparql.js +25 -1
  10. package/lib/src/model/shacl-gen.js +12 -0
  11. package/lib/src/model/types.d.ts +91 -1
  12. package/lib/src/model/types.js +9 -0
  13. package/lib/src/perspectives/AutoProcessor.d.ts +8 -0
  14. package/lib/src/perspectives/FlowInstance.d.ts +30 -12
  15. package/lib/src/perspectives/FlowInstance.js +36 -13
  16. package/lib/src/perspectives/FlowModels.d.ts +7 -1
  17. package/lib/src/perspectives/FlowModels.js +8 -2
  18. package/lib/src/perspectives/PerspectiveClient.d.ts +16 -0
  19. package/lib/src/perspectives/PerspectiveClient.js +12 -0
  20. package/lib/src/perspectives/PerspectiveProxy.d.ts +31 -3
  21. package/lib/src/perspectives/PerspectiveProxy.js +78 -2
  22. package/lib/src/perspectives/WakerSubscriptionManager.d.ts +55 -5
  23. package/lib/src/perspectives/WakerSubscriptionManager.js +183 -8
  24. package/package.json +1 -1
  25. package/src/ai/AIClient.ts +16 -0
  26. package/src/model/Ad4mModel.test.ts +79 -0
  27. package/src/model/Ad4mModel.ts +14 -6
  28. package/src/model/ModelQueryBuilder.ts +13 -3
  29. package/src/model/query-common.ts +20 -1
  30. package/src/model/query-sparql.ts +28 -1
  31. package/src/model/shacl-gen.ts +12 -0
  32. package/src/model/shacl-roundtrip.test.ts +71 -0
  33. package/src/model/types.ts +96 -1
  34. package/src/perspectives/AutoProcessor.ts +8 -0
  35. package/src/perspectives/FlowInstance.ts +39 -13
  36. package/src/perspectives/FlowModels.ts +8 -2
  37. package/src/perspectives/PerspectiveClient.ts +28 -0
  38. package/src/perspectives/PerspectiveProxy.test.ts +154 -0
  39. package/src/perspectives/PerspectiveProxy.ts +84 -5
  40. package/src/perspectives/WakerSubscriptionManager.test.ts +199 -0
  41. package/src/perspectives/WakerSubscriptionManager.ts +197 -9
@@ -6,6 +6,19 @@ export declare class AIClient {
6
6
  constructor(baseUrl: string, token?: string, subscribe?: boolean, sharedApiClient?: ApiClient);
7
7
  private serializeModelInput;
8
8
  getModels(): Promise<Model[]>;
9
+ /**
10
+ * Ask a remote endpoint which models it serves, before adding one.
11
+ *
12
+ * Takes the credentials of a model that does not exist yet — a settings
13
+ * form is being filled in and wants the list to pick from. Rejects when
14
+ * the endpoint is unreachable or the key is refused, which makes this the
15
+ * credential check too: without it a bad key surfaces later as a failed
16
+ * completion carrying an error from a different layer.
17
+ *
18
+ * `apiType` defaults to the OpenAI shape, which is what every endpoint
19
+ * that is not Anthropic speaks.
20
+ */
21
+ discoverModels(baseUrl: string, apiKey?: string, apiType?: string): Promise<string[]>;
9
22
  addModel(model: ModelInput): Promise<string>;
10
23
  updateModel(modelId: string, model: ModelInput): Promise<boolean>;
11
24
  removeModel(modelId: string): Promise<boolean>;
@@ -32,6 +32,21 @@ export class AIClient {
32
32
  async getModels() {
33
33
  return __classPrivateFieldGet(this, _AIClient_apiClient, "f").call('ai.models');
34
34
  }
35
+ /**
36
+ * Ask a remote endpoint which models it serves, before adding one.
37
+ *
38
+ * Takes the credentials of a model that does not exist yet — a settings
39
+ * form is being filled in and wants the list to pick from. Rejects when
40
+ * the endpoint is unreachable or the key is refused, which makes this the
41
+ * credential check too: without it a bad key surfaces later as a failed
42
+ * completion carrying an error from a different layer.
43
+ *
44
+ * `apiType` defaults to the OpenAI shape, which is what every endpoint
45
+ * that is not Anthropic speaks.
46
+ */
47
+ async discoverModels(baseUrl, apiKey, apiType) {
48
+ return __classPrivateFieldGet(this, _AIClient_apiClient, "f").call('ai.discoverModels', { baseUrl, apiKey, apiType });
49
+ }
35
50
  async addModel(model) {
36
51
  return __classPrivateFieldGet(this, _AIClient_apiClient, "f").call('ai.addModel', { model: this.serializeModelInput(model) });
37
52
  }
@@ -2,11 +2,12 @@ import { Link } from "../links/Links";
2
2
  import { LinkQuery } from "../perspectives/LinkQuery";
3
3
  import { makeRandomId } from "./util";
4
4
  import { getPropertiesMetadata, getRelationsMetadata, setPropertyRegistryEntry, setRelationRegistryEntry, Model } from "./decorators";
5
- import { resolveParentPredicate } from "./query-common";
5
+ import { requireSingleParent, resolveParentPredicate } from "./query-common";
6
6
  import { isArrayType, determinePredicate, determineNamespace, buildModelFromJSONSchema } from "./json-schema";
7
7
  import { buildSPARQLQuery, valueToLiteralIri, effectiveLiteralStorage } from "./query-sparql";
8
8
  import { ModelQueryBuilder } from "./ModelQueryBuilder";
9
9
  import { normalizeValue, } from "./hydration";
10
+ import { isTraverseScope } from "./types";
10
11
  // ---------------------------------------------------------------------------
11
12
  // Helpers for Rust-side include resolution
12
13
  // ---------------------------------------------------------------------------
@@ -895,7 +896,12 @@ export class Ad4mModel {
895
896
  const queryInput = {};
896
897
  if (query.parent) {
897
898
  const parentPredicate = resolveParentPredicate(query.parent, this);
898
- queryInput.parent = { id: query.parent.id, predicate: parentPredicate };
899
+ // A traversal is forwarded as it was written: the executor reads `ids`,
900
+ // and flattening it to one `id` here is how a request for a whole level
901
+ // would quietly become a request for one parent's children.
902
+ queryInput.parent = isTraverseScope(query.parent)
903
+ ? { ...query.parent, predicate: parentPredicate }
904
+ : { id: query.parent.id, predicate: parentPredicate };
899
905
  }
900
906
  if (query.properties)
901
907
  queryInput.properties = query.properties;
@@ -1667,9 +1673,10 @@ export class Ad4mModel {
1667
1673
  if (options?.parent && !options?.batchId) {
1668
1674
  const batchId = await perspective.createBatch();
1669
1675
  await instance.save(batchId);
1670
- const predicate = resolveParentPredicate(options.parent, this);
1676
+ const parent = requireSingleParent(options.parent);
1677
+ const predicate = resolveParentPredicate(parent, this);
1671
1678
  const link = new Link({
1672
- source: options.parent.id,
1679
+ source: parent.id,
1673
1680
  predicate,
1674
1681
  target: instance.id,
1675
1682
  });
@@ -1683,9 +1690,10 @@ export class Ad4mModel {
1683
1690
  await instance.save(options?.batchId);
1684
1691
  // Create parent → child link if a parent scope was provided
1685
1692
  if (options?.parent) {
1686
- const predicate = resolveParentPredicate(options.parent, this);
1693
+ const parent = requireSingleParent(options.parent);
1694
+ const predicate = resolveParentPredicate(parent, this);
1687
1695
  const link = new Link({
1688
- source: options.parent.id,
1696
+ source: parent.id,
1689
1697
  predicate,
1690
1698
  target: instance.id,
1691
1699
  });
@@ -362,13 +362,10 @@ export class ModelQueryBuilder {
362
362
  const unsubscribe = this.perspective.client.subscribeToQueryUpdates(subscriptionId, (rawResult) => {
363
363
  try {
364
364
  const results = parseResults(rawResult);
365
- console.debug(`[ModelQueryBuilder.subscribe] Update received for ${subscriptionId}: ${results.length} instances`);
366
365
  const fp = buildFingerprint(results);
367
366
  if (fp === lastResultFingerprint) {
368
- console.debug(`[ModelQueryBuilder.subscribe] Fingerprint unchanged, skipping callback`);
369
367
  return;
370
368
  }
371
- console.debug(`[ModelQueryBuilder.subscribe] Fingerprint changed, calling callback with ${results.length} results`);
372
369
  lastResultFingerprint = fp;
373
370
  callback(results);
374
371
  }
@@ -637,8 +634,21 @@ export class ModelQueryBuilder {
637
634
  offset: pageSize * (pageNumber - 1),
638
635
  count: true,
639
636
  };
637
+ // Each server dispatch triggers an independent async re-fetch, and those
638
+ // re-fetches resolve in completion order, not dispatch order. A re-fetch
639
+ // dispatched *before* a write committed can resolve *after* the re-fetch
640
+ // that saw the write, silently rolling the consumer back to a stale page —
641
+ // and no later dispatch ever corrects it. The generation counter drops any
642
+ // fetch that is no longer the newest one started; the newest fetch always
643
+ // delivers, so the callback is monotone in dispatch order.
644
+ let fetchGeneration = 0;
640
645
  const processResults = async () => {
646
+ const generation = ++fetchGeneration;
641
647
  const { results, totalCount } = await ctor.executeModelQuery(this.perspective, paginatedQuery, this.modelClassName);
648
+ if (generation !== fetchGeneration) {
649
+ console.debug(`[ModelQueryBuilder.paginateSubscribe] Dropping stale re-fetch result (generation ${generation}, newest ${fetchGeneration})`);
650
+ return;
651
+ }
642
652
  callback({ results, totalCount, pageSize, pageNumber });
643
653
  };
644
654
  const unsubscribe = this.perspective.client.subscribeToQueryUpdates(subscriptionId, (rawResult) => {
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Shared query helpers used by both the Prolog and SPARQL query pipelines.
3
3
  */
4
- import type { Scope } from "./types";
4
+ import type { Scope, TraverseScope } from "./types";
5
5
  /**
6
6
  * Resolves the predicate for a parent query.
7
7
  *
@@ -11,4 +11,13 @@ import type { Scope } from "./types";
11
11
  * - With `field`: direct key lookup
12
12
  * - Without `field`: scan for a relation whose `target()` matches `childCtor`
13
13
  */
14
+ /**
15
+ * Narrow a scope to the one-parent forms, for the paths that write a link.
16
+ *
17
+ * A traversal describes a read outward from several anchors. Creating a record
18
+ * "under" one would have to pick which, and nothing in the scope says — so this
19
+ * refuses rather than guessing at the first of the list. The executor's write
20
+ * scopes refuse it for the same reason.
21
+ */
22
+ export declare function requireSingleParent(parent: Scope): Exclude<Scope, TraverseScope>;
14
23
  export declare function resolveParentPredicate(parent: Scope, childCtor: Function): string;
@@ -1,6 +1,7 @@
1
1
  /**
2
2
  * Shared query helpers used by both the Prolog and SPARQL query pipelines.
3
3
  */
4
+ import { isTraverseScope } from "./types";
4
5
  import { getRelationsMetadata } from "./decorators";
5
6
  /**
6
7
  * Resolves the predicate for a parent query.
@@ -11,6 +12,21 @@ import { getRelationsMetadata } from "./decorators";
11
12
  * - With `field`: direct key lookup
12
13
  * - Without `field`: scan for a relation whose `target()` matches `childCtor`
13
14
  */
15
+ /**
16
+ * Narrow a scope to the one-parent forms, for the paths that write a link.
17
+ *
18
+ * A traversal describes a read outward from several anchors. Creating a record
19
+ * "under" one would have to pick which, and nothing in the scope says — so this
20
+ * refuses rather than guessing at the first of the list. The executor's write
21
+ * scopes refuse it for the same reason.
22
+ */
23
+ export function requireSingleParent(parent) {
24
+ if (isTraverseScope(parent)) {
25
+ throw new Error('parent(): a traverse scope describes a read and names no single parent to write under. ' +
26
+ 'Use { id, predicate } or { model, id } when creating a record under a parent.');
27
+ }
28
+ return parent;
29
+ }
14
30
  export function resolveParentPredicate(parent, childCtor) {
15
31
  // Raw form — explicit predicate
16
32
  if ('predicate' in parent)
@@ -12,6 +12,7 @@
12
12
  */
13
13
  import { Literal } from "../Literal";
14
14
  import { resolveParentPredicate } from "./query-common";
15
+ import { isTraverseScope } from "./types";
15
16
  /**
16
17
  * Check whether a `where` clause contains filters that cannot be pushed down
17
18
  * to SPARQL and must be evaluated in JS after hydration.
@@ -245,8 +246,31 @@ export function buildSPARQLQuery(metadata, allRelationsMetadata, query, modelCla
245
246
  // Parent filter — direct triple pattern
246
247
  if (query.parent) {
247
248
  const parentPredicate = resolveParentPredicate(query.parent, modelClass);
248
- joinPatterns.push(`
249
+ if (isTraverseScope(query.parent)) {
250
+ const { ids, transitive, direction, limitPerAnchor } = query.parent;
251
+ // `limitPerAnchor` is applied by the executor between selecting ids and
252
+ // hydrating them, which is a shape this path does not have — it builds one
253
+ // query and reads the rows. Refused rather than ignored: quietly returning
254
+ // every reply where five per parent were asked for is a wrong answer that
255
+ // looks like a right one.
256
+ if (limitPerAnchor !== undefined) {
257
+ throw new Error('buildSPARQLQuery: limitPerAnchor is applied by the executor between query phases and ' +
258
+ 'has no equivalent here. Use the model query path for per-anchor limits.');
259
+ }
260
+ const anchors = (Array.isArray(ids) ? ids : [ids]).map(iri).join(' ');
261
+ const path = transitive ? '+' : '';
262
+ joinPatterns.push(`
263
+ VALUES ?_anchor { ${anchors} }`);
264
+ joinPatterns.push(direction === 'in'
265
+ ? `
266
+ ?source ${iri(parentPredicate)}${path} ?_anchor .`
267
+ : `
268
+ ?_anchor ${iri(parentPredicate)}${path} ?source .`);
269
+ }
270
+ else {
271
+ joinPatterns.push(`
249
272
  ${iri(query.parent.id)} ${iri(parentPredicate)} ?source .`);
273
+ }
250
274
  }
251
275
  // Required property JOIN patterns — direct triple patterns
252
276
  let hasConformance = false;
@@ -100,6 +100,18 @@ interpretationHint) {
100
100
  const propMeta = properties[propName];
101
101
  if (!propMeta.through)
102
102
  continue; // Skip properties without predicates
103
+ // `@BelongsToOne`/`@BelongsToMany` register in both maps: the relation
104
+ // registry describes the edge, and `applyPropertyMetadata` marks the
105
+ // accessor read-only so the non-owning side gets no setter. Both loops
106
+ // then emitted a shape for it, so an inverse relation appeared twice in
107
+ // the generated SHACL — once thinly, from here, and once with its target
108
+ // class, polymorphism and ordering, from the relation loop below.
109
+ //
110
+ // The relation loop is the complete description, so this one stands
111
+ // aside. Skipping by presence in the relation map rather than by kind
112
+ // keeps it right for any future decorator that registers in both.
113
+ if (allRelationsMeta[propName])
114
+ continue;
103
115
  const propShape = {
104
116
  name: propName,
105
117
  path: propMeta.through,
@@ -49,6 +49,10 @@ export type Order = {
49
49
  * predicate to write.
50
50
  *
51
51
  * **Raw form** — explicit predicate string, no metadata lookup.
52
+ *
53
+ * **Traverse form** — bounded traversal from one or more anchors, for reading
54
+ * a tree rather than one node's children. Read-only: AutoProcessor's write
55
+ * scopes reject it, because it names no single parent to write under.
52
56
  */
53
57
  export type Scope = {
54
58
  model: typeof Ad4mModel;
@@ -57,7 +61,79 @@ export type Scope = {
57
61
  } | {
58
62
  id: string;
59
63
  predicate: string;
60
- };
64
+ } | TraverseScope;
65
+ /**
66
+ * Walk a predicate from several anchors at once, and optionally all the way
67
+ * down.
68
+ *
69
+ * This exists because a tree read one level at a time costs a round trip per
70
+ * level and — under a subscription — one subscription per *parent*. Asking for
71
+ * every anchor in one query makes both proportional to depth instead.
72
+ */
73
+ export interface TraverseScope {
74
+ /** The anchors to walk from. A bare string is the single-anchor spelling. */
75
+ ids: string | string[];
76
+ predicate: string;
77
+ /**
78
+ * Follow the predicate as far as it goes rather than one step.
79
+ *
80
+ * The result is a flat set of everything reachable, and it does **not**
81
+ * describe the shape it came from: SPARQL property paths bind no intermediate
82
+ * variables, so a row says that it is under the anchor and never where. To
83
+ * rebuild a tree, read the inverse relation (`@BelongsToOne`) alongside it and
84
+ * assemble from the parent each row reports.
85
+ *
86
+ * Excludes the anchor itself.
87
+ */
88
+ transitive?: boolean;
89
+ /**
90
+ * `'out'` (default) matches `anchor --predicate--> result`; `'in'` matches
91
+ * `result --predicate--> anchor`, which is how to *search* among the things
92
+ * pointing at a node — ordered, filtered, limited. A reverse `include`
93
+ * answers the same question for rows already in hand, but cannot narrow them.
94
+ */
95
+ direction?: 'out' | 'in';
96
+ /**
97
+ * Keep at most this many results per anchor — "the top 5 replies under each
98
+ * of these 20 comments" in one query.
99
+ *
100
+ * Applied by the executor between selecting ids and hydrating them, because
101
+ * SPARQL has no per-group limit (no window functions, and sub-SELECTs are
102
+ * uncorrelated). The practical consequence is that the over-fetch is paid in
103
+ * ids, not records: a branch with 3,000 replies costs 3,000 strings and
104
+ * hydrates 5.
105
+ *
106
+ * Pair it with `order` — without one the "top" N is whatever the store
107
+ * happened to return first.
108
+ */
109
+ limitPerAnchor?: number;
110
+ /**
111
+ * Walk the relation level by level, keeping this many results per anchor at each depth —
112
+ * `[10, 5, 3]` is "ten replies, five under each of those, three under each of *those*".
113
+ *
114
+ * The walk happens in the executor, which is the point of it. A caller can drive the same walk by
115
+ * asking for one level and using the ids as the next level's anchors, but each step is then a
116
+ * network round trip, and a UI that draws as each answer lands shows the tree assembling itself a
117
+ * level at a time. Inside the executor the levels are sequential queries against a local store
118
+ * with nothing serialised between them, and the records are hydrated once for the union — so
119
+ * three levels cost one request and one hydration rather than three of each.
120
+ *
121
+ * Results come back flat and breadth-first; read the inverse relation alongside to rebuild the
122
+ * tree, exactly as with `transitive`.
123
+ *
124
+ * Not combinable with `transitive`, which is the unbounded form of the same walk. Nor is
125
+ * `limitPerAnchor` a substitute: with a single anchor at the top there is one group, so it caps
126
+ * the total rather than the breadth at each level.
127
+ */
128
+ levels?: number[];
129
+ }
130
+ /**
131
+ * Whether this scope is a traversal rather than a single named parent.
132
+ *
133
+ * The other two forms carry `id`; this one carries `ids` and may name several,
134
+ * so anything reaching for one parent — every write path — has to ask first.
135
+ */
136
+ export declare function isTraverseScope(scope: Scope): scope is TraverseScope;
61
137
  /**
62
138
  * Describes which relations to eager-load when querying.
63
139
  *
@@ -105,6 +181,20 @@ export interface IncludeProjection {
105
181
  from: string;
106
182
  /** When true, attaches an integer count instead of a list. */
107
183
  count?: true;
184
+ /**
185
+ * Project over everything reachable through `from`, not just one step.
186
+ *
187
+ * `{ from: 'comments', count: true, transitive: true }` is the whole
188
+ * conversation under each row rather than its direct replies — which is what
189
+ * a reader takes "42 replies" on a collapsed branch to mean. The projection
190
+ * query is already grouped per parent and already asked of every row at once,
191
+ * so this adds no round trip.
192
+ *
193
+ * Cannot be combined with a filter on the link's author or timestamp: those
194
+ * read the reification of one link, and a path has none. Such a projection is
195
+ * skipped with a warning rather than silently answering a different question.
196
+ */
197
+ transitive?: boolean;
108
198
  /**
109
199
  * Bare class name of the projection target. Set automatically by
110
200
  * `prepareModelQueryParams`; the executor resolves the target's shape
@@ -5,6 +5,15 @@
5
5
  * (`query-utils.ts`, `decorators.ts`, etc.) can import types without
6
6
  * creating circular runtime dependencies on `Ad4mModel.ts`.
7
7
  */
8
+ /**
9
+ * Whether this scope is a traversal rather than a single named parent.
10
+ *
11
+ * The other two forms carry `id`; this one carries `ids` and may name several,
12
+ * so anything reaching for one parent — every write path — has to ask first.
13
+ */
14
+ export function isTraverseScope(scope) {
15
+ return 'ids' in scope;
16
+ }
8
17
  /** Type guard for IncludeProjection objects. */
9
18
  export function isIncludeProjection(val) {
10
19
  return typeof val === 'object' && val !== null && 'from' in val;
@@ -221,6 +221,14 @@ export interface AddAutoProcessorConfig {
221
221
  basePrefix?: string;
222
222
  /** Class URIs (SHACL `target_class`) to materialize each pass. */
223
223
  interpretationClasses: string[];
224
+ /**
225
+ * Canonical flow URIs (`SHACLFlow` `{namespace}{name}Flow`) this processor
226
+ * is flow-aware of. Flow features — the flow-aware prompt, the
227
+ * transition-proposal pass, and auto-spawn on freshly created items — run
228
+ * only on the flows listed here, mirroring the class selection above.
229
+ * Omit (or pass `[]`) for no flow processing.
230
+ */
231
+ flows?: string[];
224
232
  /** Quiet-window (ms) after the last new item before a pass runs. */
225
233
  debounceMs: number;
226
234
  /** 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 vs. what's coming in §7 / slice 10.6
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,14 +28,21 @@
28
28
  * - `proposals()` — queries `FlowTransitionProposal` records that
29
29
  * target this instance's URI.
30
30
  *
31
- * Mutations + subscriptions (`proposeTransition`, `accept`, `reject`,
32
- * `fireAction`, `onStateChange`, `onProposalAdded`, `onProposalResolved`)
33
- * land with the consensus-engine slice (§4.3 / slice 10.6). Rather than
34
- * ship them as `throw new Error("not yet")` stubs — which is a type-level
35
- * lie the caller only discovers at runtime — they are simply absent from
36
- * this class until the engine is wired.
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
  import { PerspectiveProxy } from "./PerspectiveProxy";
45
+ import { FlowFireOutcome } from "./PerspectiveClient";
39
46
  import { FlowInstanceRecord, FlowTransitionProposal } from "./FlowModels";
40
47
  import { SHACLFlow, FlowState, FlowTransition } from "../shacl/SHACLFlow";
41
48
  export declare class FlowInstance {
@@ -74,9 +81,15 @@ export declare class FlowInstance {
74
81
  *
75
82
  * The returned wrapper carries the parsed `SHACLFlow` alongside the
76
83
  * on-graph record, so `currentState` / `availableTransitions` /
77
- * `proposals` accessors work without further round-trips. The consensus
78
- * engine (slice 10.6) will read the record's `currentState` when it
79
- * fires transitions.
84
+ * `proposals` accessors work without further round-trips.
85
+ *
86
+ * The record's `currentState` is a per-replica cache the consensus engine
87
+ * writes as a local link. It is read back only for display — the cache-first
88
+ * path in `gather_active_flow_contexts` fills the state rendered into LLM
89
+ * context — and **never as authority**: anything that decides something
90
+ * (the fold, the mint pass) derives state from the signed links present now
91
+ * and does not consult the cache. Treat it as a display hint, not as the
92
+ * flow's state.
80
93
  *
81
94
  * @param perspective - The perspective the flow instance lives on
82
95
  * @param flowName - Name of a `SHACLFlow` already registered on the perspective
@@ -180,8 +193,13 @@ export declare class FlowInstance {
180
193
  * for the where-filter — one SPARQL round-trip, no client-side
181
194
  * filtering.
182
195
  *
183
- * Note: the consensus engine (slice 10.6) will start writing these; today
184
- * they only exist when a client wrote one directly (or a test seeded one).
196
+ * These are written by the executor's consensus pass when it mints a
197
+ * transition, and by clients proposing directly. Superseded proposals are
198
+ * not swept here — a stale one is simply never counted by the fold, and
199
+ * accepting it fails with a stale-state error.
185
200
  */
186
201
  proposals(): Promise<FlowTransitionProposal[]>;
202
+ acceptProposal(proposal: FlowTransitionProposal | string): Promise<FlowFireOutcome[]>;
203
+ /** Withdraw our own links from a proposal; resolves to how many went. */
204
+ rejectProposal(proposal: FlowTransitionProposal | string): Promise<number>;
187
205
  }
@@ -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 vs. what's coming in §7 / slice 10.6
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,12 +28,18 @@
28
28
  * - `proposals()` — queries `FlowTransitionProposal` records that
29
29
  * target this instance's URI.
30
30
  *
31
- * Mutations + subscriptions (`proposeTransition`, `accept`, `reject`,
32
- * `fireAction`, `onStateChange`, `onProposalAdded`, `onProposalResolved`)
33
- * land with the consensus-engine slice (§4.3 / slice 10.6). Rather than
34
- * ship them as `throw new Error("not yet")` stubs — which is a type-level
35
- * lie the caller only discovers at runtime — they are simply absent from
36
- * this class until the engine is wired.
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
  import { Ad4mModel } from "../model/Ad4mModel";
39
45
  import { FlowInstanceRecord, FlowTransitionProposal } from "./FlowModels";
@@ -98,9 +104,15 @@ export class FlowInstance {
98
104
  *
99
105
  * The returned wrapper carries the parsed `SHACLFlow` alongside the
100
106
  * on-graph record, so `currentState` / `availableTransitions` /
101
- * `proposals` accessors work without further round-trips. The consensus
102
- * engine (slice 10.6) will read the record's `currentState` when it
103
- * fires transitions.
107
+ * `proposals` accessors work without further round-trips.
108
+ *
109
+ * The record's `currentState` is a per-replica cache the consensus engine
110
+ * writes as a local link. It is read back only for display — the cache-first
111
+ * path in `gather_active_flow_contexts` fills the state rendered into LLM
112
+ * context — and **never as authority**: anything that decides something
113
+ * (the fold, the mint pass) derives state from the signed links present now
114
+ * and does not consult the cache. Treat it as a display hint, not as the
115
+ * flow's state.
104
116
  *
105
117
  * @param perspective - The perspective the flow instance lives on
106
118
  * @param flowName - Name of a `SHACLFlow` already registered on the perspective
@@ -260,7 +272,7 @@ export class FlowInstance {
260
272
  * `FlowTransitionProposal.flowInstance` references).
261
273
  */
262
274
  get uri() {
263
- return this.record.baseExpression;
275
+ return this.record.id;
264
276
  }
265
277
  /**
266
278
  * URI of the base expression this flow runs on — matches the
@@ -325,12 +337,23 @@ export class FlowInstance {
325
337
  * for the where-filter — one SPARQL round-trip, no client-side
326
338
  * filtering.
327
339
  *
328
- * Note: the consensus engine (slice 10.6) will start writing these; today
329
- * they only exist when a client wrote one directly (or a test seeded one).
340
+ * These are written by the executor's consensus pass when it mints a
341
+ * transition, and by clients proposing directly. Superseded proposals are
342
+ * not swept here — a stale one is simply never counted by the fold, and
343
+ * accepting it fails with a stale-state error.
330
344
  */
331
345
  async proposals() {
332
346
  return FlowTransitionProposal.findAll(this.perspective, {
333
347
  where: { flowInstance: this.uri },
334
348
  });
335
349
  }
350
+ async acceptProposal(proposal) {
351
+ const uri = typeof proposal === "string" ? proposal : proposal.id;
352
+ return this.perspective.acceptFlowProposal(uri);
353
+ }
354
+ /** Withdraw our own links from a proposal; resolves to how many went. */
355
+ async rejectProposal(proposal) {
356
+ const uri = typeof proposal === "string" ? proposal : proposal.id;
357
+ return this.perspective.rejectFlowProposal(uri);
358
+ }
336
359
  }
@@ -89,6 +89,12 @@ export declare class FlowInstanceRecord extends Ad4mModel {
89
89
  * on read.
90
90
  */
91
91
  subject: string;
92
- /** Name of the state the flow is currently in. */
92
+ /**
93
+ * The state name this replica's executor last derived for the flow — a
94
+ * per-replica cache written as a `local` link, never the authority (the
95
+ * fold over the signed proposals is). Optional on the shape: a row that
96
+ * synced in from a peer carries no value until the local consensus pass
97
+ * has run, so an empty string means "not yet derived here".
98
+ */
93
99
  currentState: string;
94
100
  }
@@ -157,7 +157,13 @@ let FlowInstanceRecord = class FlowInstanceRecord extends Ad4mModel {
157
157
  * on read.
158
158
  */
159
159
  this.subject = "";
160
- /** Name of the state the flow is currently in. */
160
+ /**
161
+ * The state name this replica's executor last derived for the flow — a
162
+ * per-replica cache written as a `local` link, never the authority (the
163
+ * fold over the signed proposals is). Optional on the shape: a row that
164
+ * synced in from a peer carries no value until the local consensus pass
165
+ * has run, so an empty string means "not yet derived here".
166
+ */
161
167
  this.currentState = "";
162
168
  // "When was this flow started?" is answered by `Ad4mModel`'s built-in
163
169
  // `createdAt`, synthesized on hydration from the earliest link timestamp
@@ -173,7 +179,7 @@ __decorate([
173
179
  __metadata("design:type", String)
174
180
  ], FlowInstanceRecord.prototype, "subject", void 0);
175
181
  __decorate([
176
- Property({ through: "ad4m://flow/current_state", required: true }),
182
+ Property({ through: "ad4m://flow/current_state", local: true }),
177
183
  __metadata("design:type", String)
178
184
  ], FlowInstanceRecord.prototype, "currentState", void 0);
179
185
  FlowInstanceRecord = __decorate([
@@ -12,6 +12,15 @@ import { AIClient } from "../ai/AIClient";
12
12
  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
+ /** One fired flow transition, as returned by `perspective.acceptFlowProposal`
16
+ * (and, engine-side, by every consensus pass). */
17
+ export interface FlowFireOutcome {
18
+ instanceUri: string;
19
+ fromState: string;
20
+ toState: string;
21
+ voters: string[];
22
+ contributingProposalUris: string[];
23
+ }
15
24
  export type PerspectiveHandleCallback = (perspective: PerspectiveHandle) => null;
16
25
  export type UuidCallback = (uuid: string) => null;
17
26
  export type LinkCallback = (link: LinkExpression) => null;
@@ -108,6 +117,13 @@ export declare class PerspectiveClient {
108
117
  /** Reject an overlay's suggestion(s). Omit `property` to reject the whole base
109
118
  * (a rejected `create` deletes the suggested instance). */
110
119
  rejectInterpretation(uuid: string, base: string, property?: string): Promise<boolean>;
120
+ acceptFlowProposal(uuid: string, proposalUri: string): Promise<FlowFireOutcome[]>;
121
+ /**
122
+ * Withdraw this agent's own links from a proposal. Resolves to how many
123
+ * were retracted — one for a withdrawn vote, more when retracting a
124
+ * proposal this agent opened.
125
+ */
126
+ rejectFlowProposal(uuid: string, proposalUri: string): Promise<number>;
111
127
  /**
112
128
  * Subscribe to auto-processor step signals. `cb` fires for every
113
129
  * `auto-processor-event` on `uuid` (BatchReady → Claimed/BackedOff/… →
@@ -291,6 +291,18 @@ export class PerspectiveClient {
291
291
  async rejectInterpretation(uuid, base, property) {
292
292
  return __classPrivateFieldGet(this, _PerspectiveClient_apiClient, "f").call('perspective.rejectInterpretation', { uuid, base, property });
293
293
  }
294
+ async acceptFlowProposal(uuid, proposalUri) {
295
+ return __classPrivateFieldGet(this, _PerspectiveClient_apiClient, "f").call('perspective.acceptFlowProposal', { uuid, proposalUri });
296
+ }
297
+ /**
298
+ * Withdraw this agent's own links from a proposal. Resolves to how many
299
+ * were retracted — one for a withdrawn vote, more when retracting a
300
+ * proposal this agent opened.
301
+ */
302
+ async rejectFlowProposal(uuid, proposalUri) {
303
+ const result = await __classPrivateFieldGet(this, _PerspectiveClient_apiClient, "f").call('perspective.rejectFlowProposal', { uuid, proposalUri });
304
+ return result.retractedLinks;
305
+ }
294
306
  /**
295
307
  * Subscribe to auto-processor step signals. `cb` fires for every
296
308
  * `auto-processor-event` on `uuid` (BatchReady → Claimed/BackedOff/… →