@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
package/lib/index.js CHANGED
@@ -2093,6 +2093,18 @@ interpretationHint) {
2093
2093
  const propMeta = properties[propName];
2094
2094
  if (!propMeta.through)
2095
2095
  continue; // Skip properties without predicates
2096
+ // `@BelongsToOne`/`@BelongsToMany` register in both maps: the relation
2097
+ // registry describes the edge, and `applyPropertyMetadata` marks the
2098
+ // accessor read-only so the non-owning side gets no setter. Both loops
2099
+ // then emitted a shape for it, so an inverse relation appeared twice in
2100
+ // the generated SHACL — once thinly, from here, and once with its target
2101
+ // class, polymorphism and ordering, from the relation loop below.
2102
+ //
2103
+ // The relation loop is the complete description, so this one stands
2104
+ // aside. Skipping by presence in the relation map rather than by kind
2105
+ // keeps it right for any future decorator that registers in both.
2106
+ if (allRelationsMeta[propName])
2107
+ continue;
2096
2108
  const propShape = {
2097
2109
  name: propName,
2098
2110
  path: propMeta.through,
@@ -4709,6 +4721,13 @@ class PerspectiveProxy {
4709
4721
  async rejectInterpretation(base, property) {
4710
4722
  return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").rejectInterpretation(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, base, property);
4711
4723
  }
4724
+ async acceptFlowProposal(proposalUri) {
4725
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").acceptFlowProposal(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, proposalUri);
4726
+ }
4727
+ /** Withdraw our own links from a proposal; resolves to how many went. */
4728
+ async rejectFlowProposal(proposalUri) {
4729
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").rejectFlowProposal(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, proposalUri);
4730
+ }
4712
4731
  /** Subscribe to this perspective's auto-processor step signals. */
4713
4732
  async addAutoProcessorEventListener(cb) {
4714
4733
  return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").addAutoProcessorEventListener(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, cb);
@@ -4953,11 +4972,48 @@ class PerspectiveProxy {
4953
4972
  /**
4954
4973
  * Removes a link from the perspective.
4955
4974
  *
4956
- * @param link - The link to remove
4975
+ * Accepts either a full `LinkExpressionInput` (as returned by `add`) or a bare
4976
+ * `Link` (source/predicate/target only). When a bare Link is passed the method
4977
+ * resolves it to the first stored `LinkExpression` whose source, predicate, and
4978
+ * target match, then removes that expression. A bare Link without a predicate
4979
+ * (or with the constructor's `""` stand-in) matches only stored links that
4980
+ * themselves have no predicate. If no match is found an error is thrown
4981
+ * naming the link so the caller knows what was expected.
4982
+ *
4983
+ * @param link - The link to remove (LinkExpressionInput or bare Link)
4957
4984
  * @param batchId - Optional batch ID to group this operation with others
4958
4985
  */
4959
4986
  async remove(link, batchId) {
4960
- const result = await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").removeLink(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, link, batchId);
4987
+ let resolvedLink;
4988
+ if (!('data' in link) || link.data === undefined) {
4989
+ // bare Link — resolve to stored expression
4990
+ const bare = link;
4991
+ // The Link constructor coerces an absent predicate to "" and the
4992
+ // store reports predicate-less links as predicate null — so ""
4993
+ // and undefined both mean "no predicate" here, and neither may
4994
+ // widen the query: dropping the filter would resolve (and
4995
+ // remove!) an arbitrary source→target link under a *different*
4996
+ // predicate. LinkQuery cannot express "predicate is absent", so
4997
+ // in that case we query on source/target only and require the
4998
+ // absence ourselves.
4999
+ const predicateGiven = bare.predicate !== undefined && bare.predicate !== '';
5000
+ const candidates = await this.get(new LinkQuery({
5001
+ source: bare.source || undefined,
5002
+ predicate: predicateGiven ? bare.predicate : undefined,
5003
+ target: bare.target || undefined,
5004
+ }));
5005
+ const matches = predicateGiven
5006
+ ? candidates
5007
+ : candidates.filter(m => !m.data.predicate);
5008
+ if (matches.length === 0) {
5009
+ throw new Error(`PerspectiveProxy.remove: no stored LinkExpression matches Link { source: "${bare.source}", predicate: "${bare.predicate}", target: "${bare.target}" }`);
5010
+ }
5011
+ resolvedLink = matches[0];
5012
+ }
5013
+ else {
5014
+ resolvedLink = link;
5015
+ }
5016
+ const result = await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").removeLink(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, resolvedLink, batchId);
4961
5017
  invalidatePerspectiveCache(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid);
4962
5018
  return result;
4963
5019
  }
@@ -5545,6 +5601,38 @@ class PerspectiveProxy {
5545
5601
  return [];
5546
5602
  }
5547
5603
  }
5604
+ /**
5605
+ * Return the full target-class URIs of every registered SubjectClass.
5606
+ *
5607
+ * Unlike {@link subjectClasses}, which strips the namespace and returns bare
5608
+ * names (`"Space"`, `"Channel"`), this method returns the complete URIs
5609
+ * (`"we://Space"`, `"flux://Channel"`). The full URI is the key that
5610
+ * `load_shape` resolves against, so it is the only collision-safe identifier
5611
+ * — two apps can both declare a class called `"Template"` under different
5612
+ * namespaces, and the bare name cannot distinguish them.
5613
+ *
5614
+ * Callers that need to check whether a *set* of models are already
5615
+ * registered should call this once and test membership against the returned
5616
+ * set, rather than issuing one `queryLinks` per model.
5617
+ *
5618
+ * One `queryLinks` round trip, no executor-side changes.
5619
+ */
5620
+ async subjectClassTargetClasses() {
5621
+ try {
5622
+ const classLinks = await this.get(new LinkQuery({
5623
+ predicate: "rdf://type",
5624
+ target: "ad4m://SubjectClass"
5625
+ }));
5626
+ const uris = classLinks
5627
+ .map(l => l.data.source)
5628
+ .filter(source => source.length > 0);
5629
+ return [...new Set(uris)];
5630
+ }
5631
+ catch (e) {
5632
+ console.warn('subjectClassTargetClasses: lookup failed:', e);
5633
+ return [];
5634
+ }
5635
+ }
5548
5636
  async stringOrTemplateObjectToSubjectClassName(subjectClass) {
5549
5637
  if (typeof subjectClass === "string")
5550
5638
  return subjectClass;
@@ -6559,6 +6647,18 @@ class PerspectiveClient {
6559
6647
  async rejectInterpretation(uuid, base, property) {
6560
6648
  return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.rejectInterpretation', { uuid, base, property });
6561
6649
  }
6650
+ async acceptFlowProposal(uuid, proposalUri) {
6651
+ return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.acceptFlowProposal', { uuid, proposalUri });
6652
+ }
6653
+ /**
6654
+ * Withdraw this agent's own links from a proposal. Resolves to how many
6655
+ * were retracted — one for a withdrawn vote, more when retracting a
6656
+ * proposal this agent opened.
6657
+ */
6658
+ async rejectFlowProposal(uuid, proposalUri) {
6659
+ const result = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.rejectFlowProposal', { uuid, proposalUri });
6660
+ return result.retractedLinks;
6661
+ }
6562
6662
  /**
6563
6663
  * Subscribe to auto-processor step signals. `cb` fires for every
6564
6664
  * `auto-processor-event` on `uuid` (BatchReady → Claimed/BackedOff/… →
@@ -14923,6 +15023,21 @@ class AIClient {
14923
15023
  async getModels() {
14924
15024
  return __classPrivateFieldGet$2(this, _AIClient_apiClient, "f").call('ai.models');
14925
15025
  }
15026
+ /**
15027
+ * Ask a remote endpoint which models it serves, before adding one.
15028
+ *
15029
+ * Takes the credentials of a model that does not exist yet — a settings
15030
+ * form is being filled in and wants the list to pick from. Rejects when
15031
+ * the endpoint is unreachable or the key is refused, which makes this the
15032
+ * credential check too: without it a bad key surfaces later as a failed
15033
+ * completion carrying an error from a different layer.
15034
+ *
15035
+ * `apiType` defaults to the OpenAI shape, which is what every endpoint
15036
+ * that is not Anthropic speaks.
15037
+ */
15038
+ async discoverModels(baseUrl, apiKey, apiType) {
15039
+ return __classPrivateFieldGet$2(this, _AIClient_apiClient, "f").call('ai.discoverModels', { baseUrl, apiKey, apiType });
15040
+ }
14926
15041
  async addModel(model) {
14927
15042
  return __classPrivateFieldGet$2(this, _AIClient_apiClient, "f").call('ai.addModel', { model: this.serializeModelInput(model) });
14928
15043
  }
@@ -15033,6 +15148,27 @@ class AIClient {
15033
15148
  }
15034
15149
  _AIClient_apiClient = new WeakMap(), _AIClient_transcriptionUnsubscribers = new WeakMap(), _AIClient_pendingStreamIds = new WeakMap();
15035
15150
 
15151
+ /**
15152
+ * Shared type definitions for the Ad4mModel system.
15153
+ *
15154
+ * Extracted into a standalone module so that utility files
15155
+ * (`query-utils.ts`, `decorators.ts`, etc.) can import types without
15156
+ * creating circular runtime dependencies on `Ad4mModel.ts`.
15157
+ */
15158
+ /**
15159
+ * Whether this scope is a traversal rather than a single named parent.
15160
+ *
15161
+ * The other two forms carry `id`; this one carries `ids` and may name several,
15162
+ * so anything reaching for one parent — every write path — has to ask first.
15163
+ */
15164
+ function isTraverseScope(scope) {
15165
+ return 'ids' in scope;
15166
+ }
15167
+ /** Type guard for IncludeProjection objects. */
15168
+ function isIncludeProjection(val) {
15169
+ return typeof val === 'object' && val !== null && 'from' in val;
15170
+ }
15171
+
15036
15172
  /**
15037
15173
  * Shared query helpers used by both the Prolog and SPARQL query pipelines.
15038
15174
  */
@@ -15045,6 +15181,21 @@ _AIClient_apiClient = new WeakMap(), _AIClient_transcriptionUnsubscribers = new
15045
15181
  * - With `field`: direct key lookup
15046
15182
  * - Without `field`: scan for a relation whose `target()` matches `childCtor`
15047
15183
  */
15184
+ /**
15185
+ * Narrow a scope to the one-parent forms, for the paths that write a link.
15186
+ *
15187
+ * A traversal describes a read outward from several anchors. Creating a record
15188
+ * "under" one would have to pick which, and nothing in the scope says — so this
15189
+ * refuses rather than guessing at the first of the list. The executor's write
15190
+ * scopes refuse it for the same reason.
15191
+ */
15192
+ function requireSingleParent(parent) {
15193
+ if (isTraverseScope(parent)) {
15194
+ throw new Error('parent(): a traverse scope describes a read and names no single parent to write under. ' +
15195
+ 'Use { id, predicate } or { model, id } when creating a record under a parent.');
15196
+ }
15197
+ return parent;
15198
+ }
15048
15199
  function resolveParentPredicate(parent, childCtor) {
15049
15200
  // Raw form — explicit predicate
15050
15201
  if ('predicate' in parent)
@@ -15625,8 +15776,31 @@ function buildSPARQLQuery(metadata, allRelationsMetadata, query, modelClass) {
15625
15776
  // Parent filter — direct triple pattern
15626
15777
  if (query.parent) {
15627
15778
  const parentPredicate = resolveParentPredicate(query.parent, modelClass);
15628
- joinPatterns.push(`
15779
+ if (isTraverseScope(query.parent)) {
15780
+ const { ids, transitive, direction, limitPerAnchor } = query.parent;
15781
+ // `limitPerAnchor` is applied by the executor between selecting ids and
15782
+ // hydrating them, which is a shape this path does not have — it builds one
15783
+ // query and reads the rows. Refused rather than ignored: quietly returning
15784
+ // every reply where five per parent were asked for is a wrong answer that
15785
+ // looks like a right one.
15786
+ if (limitPerAnchor !== undefined) {
15787
+ throw new Error('buildSPARQLQuery: limitPerAnchor is applied by the executor between query phases and ' +
15788
+ 'has no equivalent here. Use the model query path for per-anchor limits.');
15789
+ }
15790
+ const anchors = (Array.isArray(ids) ? ids : [ids]).map(iri).join(' ');
15791
+ const path = transitive ? '+' : '';
15792
+ joinPatterns.push(`
15793
+ VALUES ?_anchor { ${anchors} }`);
15794
+ joinPatterns.push(direction === 'in'
15795
+ ? `
15796
+ ?source ${iri(parentPredicate)}${path} ?_anchor .`
15797
+ : `
15798
+ ?_anchor ${iri(parentPredicate)}${path} ?source .`);
15799
+ }
15800
+ else {
15801
+ joinPatterns.push(`
15629
15802
  ${iri(query.parent.id)} ${iri(parentPredicate)} ?source .`);
15803
+ }
15630
15804
  }
15631
15805
  // Required property JOIN patterns — direct triple patterns
15632
15806
  let hasConformance = false;
@@ -16285,13 +16459,10 @@ class ModelQueryBuilder {
16285
16459
  const unsubscribe = this.perspective.client.subscribeToQueryUpdates(subscriptionId, (rawResult) => {
16286
16460
  try {
16287
16461
  const results = parseResults(rawResult);
16288
- console.debug(`[ModelQueryBuilder.subscribe] Update received for ${subscriptionId}: ${results.length} instances`);
16289
16462
  const fp = buildFingerprint(results);
16290
16463
  if (fp === lastResultFingerprint) {
16291
- console.debug(`[ModelQueryBuilder.subscribe] Fingerprint unchanged, skipping callback`);
16292
16464
  return;
16293
16465
  }
16294
- console.debug(`[ModelQueryBuilder.subscribe] Fingerprint changed, calling callback with ${results.length} results`);
16295
16466
  lastResultFingerprint = fp;
16296
16467
  callback(results);
16297
16468
  }
@@ -16560,8 +16731,21 @@ class ModelQueryBuilder {
16560
16731
  offset: pageSize * (pageNumber - 1),
16561
16732
  count: true,
16562
16733
  };
16734
+ // Each server dispatch triggers an independent async re-fetch, and those
16735
+ // re-fetches resolve in completion order, not dispatch order. A re-fetch
16736
+ // dispatched *before* a write committed can resolve *after* the re-fetch
16737
+ // that saw the write, silently rolling the consumer back to a stale page —
16738
+ // and no later dispatch ever corrects it. The generation counter drops any
16739
+ // fetch that is no longer the newest one started; the newest fetch always
16740
+ // delivers, so the callback is monotone in dispatch order.
16741
+ let fetchGeneration = 0;
16563
16742
  const processResults = async () => {
16743
+ const generation = ++fetchGeneration;
16564
16744
  const { results, totalCount } = await ctor.executeModelQuery(this.perspective, paginatedQuery, this.modelClassName);
16745
+ if (generation !== fetchGeneration) {
16746
+ console.debug(`[ModelQueryBuilder.paginateSubscribe] Dropping stale re-fetch result (generation ${generation}, newest ${fetchGeneration})`);
16747
+ return;
16748
+ }
16565
16749
  callback({ results, totalCount, pageSize, pageNumber });
16566
16750
  };
16567
16751
  const unsubscribe = this.perspective.client.subscribeToQueryUpdates(subscriptionId, (rawResult) => {
@@ -17536,7 +17720,12 @@ class Ad4mModel {
17536
17720
  const queryInput = {};
17537
17721
  if (query.parent) {
17538
17722
  const parentPredicate = resolveParentPredicate(query.parent, this);
17539
- queryInput.parent = { id: query.parent.id, predicate: parentPredicate };
17723
+ // A traversal is forwarded as it was written: the executor reads `ids`,
17724
+ // and flattening it to one `id` here is how a request for a whole level
17725
+ // would quietly become a request for one parent's children.
17726
+ queryInput.parent = isTraverseScope(query.parent)
17727
+ ? { ...query.parent, predicate: parentPredicate }
17728
+ : { id: query.parent.id, predicate: parentPredicate };
17540
17729
  }
17541
17730
  if (query.properties)
17542
17731
  queryInput.properties = query.properties;
@@ -18308,9 +18497,10 @@ class Ad4mModel {
18308
18497
  if (options?.parent && !options?.batchId) {
18309
18498
  const batchId = await perspective.createBatch();
18310
18499
  await instance.save(batchId);
18311
- const predicate = resolveParentPredicate(options.parent, this);
18500
+ const parent = requireSingleParent(options.parent);
18501
+ const predicate = resolveParentPredicate(parent, this);
18312
18502
  const link = new Link({
18313
- source: options.parent.id,
18503
+ source: parent.id,
18314
18504
  predicate,
18315
18505
  target: instance.id,
18316
18506
  });
@@ -18324,9 +18514,10 @@ class Ad4mModel {
18324
18514
  await instance.save(options?.batchId);
18325
18515
  // Create parent → child link if a parent scope was provided
18326
18516
  if (options?.parent) {
18327
- const predicate = resolveParentPredicate(options.parent, this);
18517
+ const parent = requireSingleParent(options.parent);
18518
+ const predicate = resolveParentPredicate(parent, this);
18328
18519
  const link = new Link({
18329
- source: options.parent.id,
18520
+ source: parent.id,
18330
18521
  predicate,
18331
18522
  target: instance.id,
18332
18523
  });
@@ -19267,7 +19458,13 @@ let FlowInstanceRecord = class FlowInstanceRecord extends Ad4mModel {
19267
19458
  * on read.
19268
19459
  */
19269
19460
  this.subject = "";
19270
- /** Name of the state the flow is currently in. */
19461
+ /**
19462
+ * The state name this replica's executor last derived for the flow — a
19463
+ * per-replica cache written as a `local` link, never the authority (the
19464
+ * fold over the signed proposals is). Optional on the shape: a row that
19465
+ * synced in from a peer carries no value until the local consensus pass
19466
+ * has run, so an empty string means "not yet derived here".
19467
+ */
19271
19468
  this.currentState = "";
19272
19469
  // "When was this flow started?" is answered by `Ad4mModel`'s built-in
19273
19470
  // `createdAt`, synthesized on hydration from the earliest link timestamp
@@ -19283,7 +19480,7 @@ __decorate([
19283
19480
  __metadata("design:type", String)
19284
19481
  ], FlowInstanceRecord.prototype, "subject", void 0);
19285
19482
  __decorate([
19286
- Property({ through: "ad4m://flow/current_state", required: true }),
19483
+ Property({ through: "ad4m://flow/current_state", local: true }),
19287
19484
  __metadata("design:type", String)
19288
19485
  ], FlowInstanceRecord.prototype, "currentState", void 0);
19289
19486
  FlowInstanceRecord = __decorate([
@@ -19309,7 +19506,7 @@ FlowInstanceRecord = __decorate([
19309
19506
  * than the `wrap` escape hatch, which exists for tests that already own
19310
19507
  * a matched (record, shape) pair.
19311
19508
  *
19312
- * # What's here vs. what's coming in §7 / slice 10.6
19509
+ * # What's here, and what is still absent
19313
19510
  *
19314
19511
  * Read surface (implemented today, PR #929):
19315
19512
  * - `uri`, `subject`, `flowName`, `currentStateName`, `startedAtMillis`
@@ -19320,12 +19517,18 @@ FlowInstanceRecord = __decorate([
19320
19517
  * - `proposals()` — queries `FlowTransitionProposal` records that
19321
19518
  * target this instance's URI.
19322
19519
  *
19323
- * Mutations + subscriptions (`proposeTransition`, `accept`, `reject`,
19324
- * `fireAction`, `onStateChange`, `onProposalAdded`, `onProposalResolved`)
19325
- * land with the consensus-engine slice (§4.3 / slice 10.6). Rather than
19326
- * ship them as `throw new Error("not yet")` stubs — which is a type-level
19327
- * lie the caller only discovers at runtime — they are simply absent from
19328
- * this class until the engine is wired.
19520
+ * - `acceptProposal()` / `rejectProposal()` — the consensus write API:
19521
+ * accept counts your DID toward the flow's consensusRule and fires the
19522
+ * transition at quorum; reject withdraws only the links you signed and
19523
+ * resolves to how many went. Reject is not a cancel — another agent's
19524
+ * proposal is theirs, and because state is recomputed from the links
19525
+ * present now, withdrawing a vote that had settled an edge moves the
19526
+ * flow back to where it stood before it.
19527
+ *
19528
+ * Still absent (rather than shipped as `throw new Error("not yet")`
19529
+ * stubs): `proposeTransition`, `fireAction`, and the subscriptions
19530
+ * (`onStateChange`, `onProposalAdded`, `onProposalResolved`) — they land
19531
+ * with the manual-proposal and subscription-topic slices.
19329
19532
  */
19330
19533
  /**
19331
19534
  * Extract the flow's human-readable name from its canonical URI.
@@ -19388,9 +19591,15 @@ class FlowInstance {
19388
19591
  *
19389
19592
  * The returned wrapper carries the parsed `SHACLFlow` alongside the
19390
19593
  * on-graph record, so `currentState` / `availableTransitions` /
19391
- * `proposals` accessors work without further round-trips. The consensus
19392
- * engine (slice 10.6) will read the record's `currentState` when it
19393
- * fires transitions.
19594
+ * `proposals` accessors work without further round-trips.
19595
+ *
19596
+ * The record's `currentState` is a per-replica cache the consensus engine
19597
+ * writes as a local link. It is read back only for display — the cache-first
19598
+ * path in `gather_active_flow_contexts` fills the state rendered into LLM
19599
+ * context — and **never as authority**: anything that decides something
19600
+ * (the fold, the mint pass) derives state from the signed links present now
19601
+ * and does not consult the cache. Treat it as a display hint, not as the
19602
+ * flow's state.
19394
19603
  *
19395
19604
  * @param perspective - The perspective the flow instance lives on
19396
19605
  * @param flowName - Name of a `SHACLFlow` already registered on the perspective
@@ -19550,7 +19759,7 @@ class FlowInstance {
19550
19759
  * `FlowTransitionProposal.flowInstance` references).
19551
19760
  */
19552
19761
  get uri() {
19553
- return this.record.baseExpression;
19762
+ return this.record.id;
19554
19763
  }
19555
19764
  /**
19556
19765
  * URI of the base expression this flow runs on — matches the
@@ -19615,14 +19824,25 @@ class FlowInstance {
19615
19824
  * for the where-filter — one SPARQL round-trip, no client-side
19616
19825
  * filtering.
19617
19826
  *
19618
- * Note: the consensus engine (slice 10.6) will start writing these; today
19619
- * they only exist when a client wrote one directly (or a test seeded one).
19827
+ * These are written by the executor's consensus pass when it mints a
19828
+ * transition, and by clients proposing directly. Superseded proposals are
19829
+ * not swept here — a stale one is simply never counted by the fold, and
19830
+ * accepting it fails with a stale-state error.
19620
19831
  */
19621
19832
  async proposals() {
19622
19833
  return FlowTransitionProposal.findAll(this.perspective, {
19623
19834
  where: { flowInstance: this.uri },
19624
19835
  });
19625
19836
  }
19837
+ async acceptProposal(proposal) {
19838
+ const uri = typeof proposal === "string" ? proposal : proposal.id;
19839
+ return this.perspective.acceptFlowProposal(uri);
19840
+ }
19841
+ /** Withdraw our own links from a proposal; resolves to how many went. */
19842
+ async rejectProposal(proposal) {
19843
+ const uri = typeof proposal === "string" ? proposal : proposal.id;
19844
+ return this.perspective.rejectFlowProposal(uri);
19845
+ }
19626
19846
  }
19627
19847
 
19628
19848
  /**
@@ -19744,15 +19964,73 @@ function parseLitBoolean(val) {
19744
19964
  /**
19745
19965
  * WakerSubscriptionManager — manages live query subscriptions for the waker.
19746
19966
  *
19747
- * Lives in core so it can be imported by both the plugin and integration tests
19748
- * without ESM/CJS import issues.
19967
+ * This is the single implementation: it is exported from `@coasys/ad4m` and
19968
+ * used by the integration tests, and the OpenClaw AD4M plugin re-exports this
19969
+ * module (`plugins/ad4m/wakerSubscriptionManager.ts`) rather than carrying its
19970
+ * own copy. Any behaviour change belongs here.
19971
+ */
19972
+ /**
19973
+ * Add a short cause hint to known subscription failures.
19974
+ * The executor needs its main key to register a live query; on a restarted
19975
+ * executor whose wallet was never unlocked this surfaces as a bare 403.
19976
+ */
19977
+ function hintFor(msg) {
19978
+ // "Executor is locked" is the current executor's message; "main key not
19979
+ // found" is what older executors (and unrelated key lookups) say for the
19980
+ // same locked state. Either way the caller cannot fix it themselves: keys
19981
+ // live in memory only, so every restart locks the node again and only its
19982
+ // operator can unlock it.
19983
+ if (/executor is locked/i.test(msg) || /main key not found/i.test(msg)) {
19984
+ return " — the executor is locked (its keys live in memory only, so every restart locks it again). Only the node's operator can unlock it: contact them and ask for unlockAgent, then subscribe again — a pending subscription re-attempts on its own once the node is unlocked";
19985
+ }
19986
+ if (/timed out after \d+ms/i.test(msg)) {
19987
+ return " — the executor accepted the waker's connection but never answered; check that the waker is pointed at the right executor host and API port (executorUrl in the plugin config) and that the node is unlocked";
19988
+ }
19989
+ return "";
19990
+ }
19991
+ /**
19992
+ * Reject `promise` after `ms` instead of waiting forever.
19749
19993
  *
19750
- * NOTE: keep in sync with plugins/ad4m/wakerSubscriptionManager.ts
19994
+ * The pending set only catches rejections. A handshake that hangs — the
19995
+ * executor accepted the socket but never answers — settles nothing, so the
19996
+ * subscription was recorded nowhere and the caller's tool invocation died at
19997
+ * the harness timeout instead (#1016). The underlying promise is left as is:
19998
+ * the caller disposes the proxy, so a late answer backs out on its own.
19751
19999
  */
20000
+ async function withTimeout(promise, ms, message) {
20001
+ let timer;
20002
+ try {
20003
+ return await Promise.race([
20004
+ promise,
20005
+ new Promise((_resolve, reject) => {
20006
+ timer = setTimeout(() => reject(new Error(message)), ms);
20007
+ }),
20008
+ ]);
20009
+ }
20010
+ finally {
20011
+ if (timer)
20012
+ clearTimeout(timer);
20013
+ }
20014
+ }
19752
20015
  class WakerSubscriptionManager {
19753
20016
  constructor(options) {
19754
20017
  this.proxies = new Map();
19755
20018
  this.activeSubscriptions = new Map();
20019
+ /** Subscriptions the executor rejected, waiting to be re-attempted. */
20020
+ this.pendingSubscriptions = new Map();
20021
+ this.retryTimer = null;
20022
+ /**
20023
+ * Cancellation tokens for in-flight `subscribe()` calls.
20024
+ *
20025
+ * `subscribe()` awaits `proxy.subscribe()` and `proxy.initialized`; a
20026
+ * `dispose()` / `disposeAll()` landing during either await used to leave a
20027
+ * live subscription behind, because nothing stopped the resumed call from
20028
+ * registering the proxy in `proxies` / `activeSubscriptions` afterwards.
20029
+ * `epoch` is bumped by `disposeAll()` (which cannot enumerate in-flight
20030
+ * ids), `generations` per id by `dispose()` and by each new `subscribe()`.
20031
+ */
20032
+ this.epoch = 0;
20033
+ this.generations = new Map();
19756
20034
  this.debounceTimers = new Map();
19757
20035
  /** Per-subscription set of already-processed message addresses (for mention subs)
19758
20036
  * or serialized result hash (for channel-messages subs). */
@@ -19764,6 +20042,18 @@ class WakerSubscriptionManager {
19764
20042
  this.onPersist = options.onPersist;
19765
20043
  this.QuerySubscriptionProxyCtor = options.QuerySubscriptionProxy ?? null;
19766
20044
  this.previousSeenMessages = options.previousSeenMessages ?? {};
20045
+ this.retryPendingMs = options.retryPendingMs ?? 30000;
20046
+ this.subscribeTimeoutMs = options.subscribeTimeoutMs ?? 15000;
20047
+ }
20048
+ /** A token identifying this attempt at subscribing `id`. */
20049
+ beginAttempt(id) {
20050
+ const gen = (this.generations.get(id) ?? 0) + 1;
20051
+ this.generations.set(id, gen);
20052
+ return { epoch: this.epoch, gen };
20053
+ }
20054
+ /** Whether this attempt has been superseded by a dispose or a newer one. */
20055
+ isStale(id, token) {
20056
+ return token.epoch !== this.epoch || this.generations.get(id) !== token.gen;
19767
20057
  }
19768
20058
  /**
19769
20059
  * Create a live SPARQL subscription.
@@ -19772,6 +20062,7 @@ class WakerSubscriptionManager {
19772
20062
  async subscribe(sub) {
19773
20063
  // Dispose existing subscription with same id if any
19774
20064
  this.dispose(sub.id, false);
20065
+ const token = this.beginAttempt(sub.id);
19775
20066
  if (!this.QuerySubscriptionProxyCtor) {
19776
20067
  throw new Error("WakerSubscriptionManager: QuerySubscriptionProxy must be provided via constructor options");
19777
20068
  }
@@ -19786,9 +20077,24 @@ class WakerSubscriptionManager {
19786
20077
  if (proxy.initialized && typeof proxy.initialized.catch === "function") {
19787
20078
  proxy.initialized.catch(() => { });
19788
20079
  }
20080
+ // One deadline for the whole handshake: `proxy.subscribe()` and the
20081
+ // `initialized` promise it resolves share the budget, so a hang in either
20082
+ // surfaces as the same loud-but-recoverable failure a rejection does.
20083
+ const budgetMs = this.subscribeTimeoutMs;
20084
+ const startedAt = Date.now();
20085
+ const bounded = (step, what) => budgetMs > 0
20086
+ ? withTimeout(step, Math.max(0, budgetMs - (Date.now() - startedAt)), `${what} timed out after ${budgetMs}ms`)
20087
+ : step;
19789
20088
  try {
19790
- await proxy.subscribe();
19791
- await proxy.initialized;
20089
+ await bounded(proxy.subscribe(), "subscribe handshake");
20090
+ if (this.isStale(sub.id, token)) {
20091
+ try {
20092
+ proxy.dispose();
20093
+ }
20094
+ catch { }
20095
+ return;
20096
+ }
20097
+ await bounded(proxy.initialized, "subscription initialization");
19792
20098
  }
19793
20099
  catch (err) {
19794
20100
  const msg = err?.message ?? String(err);
@@ -19797,12 +20103,36 @@ class WakerSubscriptionManager {
19797
20103
  proxy.dispose();
19798
20104
  }
19799
20105
  catch { }
19800
- // Remove from active state so it doesn't get persisted/retried
20106
+ // A dispose that landed mid-attempt wins: don't re-queue something the
20107
+ // caller has since asked us to forget.
20108
+ if (this.isStale(sub.id, token))
20109
+ return;
20110
+ // Remove from active state — it is not listening, so it must not be
20111
+ // reported as active or persisted as if it were.
19801
20112
  this.activeSubscriptions.delete(sub.id);
19802
20113
  this.seenMessages.delete(sub.id);
19803
20114
  this.persist();
19804
- return; // Don't throw — caller should not crash
20115
+ // Keep it pending and re-attempt: the usual cause (locked wallet, executor
20116
+ // mid-restart, a handshake the executor never answered) clears on its
20117
+ // own, and the caller asked to be enrolled.
20118
+ this.pendingSubscriptions.set(sub.id, sub);
20119
+ this.scheduleRetry();
20120
+ // Throw so callers can report the real outcome. Background callers
20121
+ // (auto-subscribe, restore-on-start) catch and log; the subscribe tools
20122
+ // turn this into an error result instead of a false "Subscribed" reply.
20123
+ throw new Error(`Waker subscription ${sub.id} failed: ${msg}${hintFor(msg)}` +
20124
+ (this.retryPendingMs > 0
20125
+ ? `. Not listening yet — re-attempting every ${Math.round(this.retryPendingMs / 1000)}s; check ad4m_list_waker_subscriptions.`
20126
+ : ""));
20127
+ }
20128
+ if (this.isStale(sub.id, token)) {
20129
+ try {
20130
+ proxy.dispose();
20131
+ }
20132
+ catch { }
20133
+ return;
19805
20134
  }
20135
+ this.pendingSubscriptions.delete(sub.id);
19806
20136
  this.logger.info(`[waker] ${sub.id}: subscription initialized successfully`);
19807
20137
  // Seed from persisted seen messages so we don't re-wake after restart
19808
20138
  const seen = new Set(this.previousSeenMessages[sub.id] ?? []);
@@ -19883,16 +20213,72 @@ class WakerSubscriptionManager {
19883
20213
  }, this.debounceMs));
19884
20214
  }
19885
20215
  });
20216
+ if (this.isStale(sub.id, token)) {
20217
+ try {
20218
+ proxy.dispose();
20219
+ }
20220
+ catch { }
20221
+ return;
20222
+ }
19886
20223
  this.proxies.set(sub.id, proxy);
19887
20224
  this.activeSubscriptions.set(sub.id, sub);
19888
20225
  this.persist();
19889
20226
  this.logger.info(`[waker] Subscription ${sub.id} active (type=${sub.type}, perspective=${sub.perspective})`);
19890
20227
  }
20228
+ /** Arm the re-attempt timer if pending subscriptions are waiting. */
20229
+ scheduleRetry() {
20230
+ if (this.retryPendingMs <= 0)
20231
+ return;
20232
+ if (this.retryTimer || this.pendingSubscriptions.size === 0)
20233
+ return;
20234
+ this.retryTimer = setTimeout(() => {
20235
+ this.retryTimer = null;
20236
+ void this.retryPending();
20237
+ }, this.retryPendingMs);
20238
+ if (typeof this.retryTimer.unref === "function")
20239
+ this.retryTimer.unref();
20240
+ }
20241
+ /**
20242
+ * Re-attempt every subscription the executor rejected.
20243
+ * Each attempt that fails puts itself back into the pending set and re-arms
20244
+ * the timer, so an agent that asked to be subscribed ends up enrolled once
20245
+ * the executor can accept the query.
20246
+ */
20247
+ async retryPending() {
20248
+ const waiting = Array.from(this.pendingSubscriptions.values());
20249
+ if (waiting.length === 0)
20250
+ return;
20251
+ this.logger.info(`[waker] re-attempting ${waiting.length} pending subscription(s)`);
20252
+ const epoch = this.epoch;
20253
+ for (const sub of waiting) {
20254
+ // A disposeAll() between two awaits must stop the whole sweep, and a
20255
+ // dispose() of this id must skip just it.
20256
+ if (epoch !== this.epoch)
20257
+ return;
20258
+ if (!this.pendingSubscriptions.has(sub.id))
20259
+ continue;
20260
+ this.pendingSubscriptions.delete(sub.id);
20261
+ try {
20262
+ await this.subscribe(sub);
20263
+ this.logger.info(`[waker] ${sub.id}: enrolled on re-attempt`);
20264
+ }
20265
+ catch (err) {
20266
+ // subscribe() already logged, re-queued and re-armed the timer.
20267
+ this.logger.debug(`[waker] ${sub.id}: still pending — ${err?.message ?? err}`);
20268
+ }
20269
+ }
20270
+ }
20271
+ /** Subscriptions that were rejected and are waiting to be re-attempted. */
20272
+ getPending() {
20273
+ return Array.from(this.pendingSubscriptions.values());
20274
+ }
19891
20275
  /**
19892
20276
  * Dispose a single subscription.
19893
20277
  * @param persist — if false, skip calling onPersist (used during batch cleanup).
19894
20278
  */
19895
20279
  dispose(id, persist = true) {
20280
+ // Invalidate any subscribe() for this id that is still awaiting.
20281
+ this.generations.set(id, (this.generations.get(id) ?? 0) + 1);
19896
20282
  const proxy = this.proxies.get(id);
19897
20283
  if (proxy) {
19898
20284
  try {
@@ -19909,15 +20295,24 @@ class WakerSubscriptionManager {
19909
20295
  this.debounceTimers.delete(id);
19910
20296
  }
19911
20297
  this.activeSubscriptions.delete(id);
20298
+ this.pendingSubscriptions.delete(id);
19912
20299
  this.seenMessages.delete(id);
19913
20300
  if (persist)
19914
20301
  this.persist();
19915
20302
  }
19916
- /** Dispose all active subscriptions. */
20303
+ /** Dispose all active subscriptions and drop anything still pending. */
19917
20304
  disposeAll() {
20305
+ // Bump the epoch first: in-flight subscribe() calls have no proxy in the
20306
+ // map yet, so per-id invalidation alone cannot reach them.
20307
+ this.epoch++;
19918
20308
  for (const [id] of this.proxies) {
19919
20309
  this.dispose(id, false);
19920
20310
  }
20311
+ this.pendingSubscriptions.clear();
20312
+ if (this.retryTimer) {
20313
+ clearTimeout(this.retryTimer);
20314
+ this.retryTimer = null;
20315
+ }
19921
20316
  }
19922
20317
  /** Get all active subscriptions. */
19923
20318
  getActive() {
@@ -20015,18 +20410,6 @@ class SmartLiteral {
20015
20410
  }
20016
20411
  _SmartLiteral_perspective = new WeakMap(), _SmartLiteral_base = new WeakMap();
20017
20412
 
20018
- /**
20019
- * Shared type definitions for the Ad4mModel system.
20020
- *
20021
- * Extracted into a standalone module so that utility files
20022
- * (`query-utils.ts`, `decorators.ts`, etc.) can import types without
20023
- * creating circular runtime dependencies on `Ad4mModel.ts`.
20024
- */
20025
- /** Type guard for IncludeProjection objects. */
20026
- function isIncludeProjection(val) {
20027
- return typeof val === 'object' && val !== null && 'from' in val;
20028
- }
20029
-
20030
20413
  /**
20031
20414
  * Shared query compilation utilities.
20032
20415
  *
@@ -20364,4 +20747,4 @@ const fileToDataUri = ifExpr(exists(path('file_storage://data_base64')))
20364
20747
  .then(concat(literal('data:'), coalesce(path('file_storage://file_type'), literal('image/png')), literal(';base64,'), path('file_storage://data_base64')))
20365
20748
  .else(focus());
20366
20749
 
20367
- export { AIClient, Model as AIModel, AIModelLoadingStatus, AIPromptExamples, AIPromptExamplesInput, AITask, AITaskInput, Ad4mClient, Ad4mModel, Agent, AgentClient, AgentExpression, AgentSignature, AgentStatus, Apps, AuthInfo, AuthInfoInput, AutoProcessorConfig, BelongsToMany, BelongsToOne, Capability, CapabilityInput, ComputeLogEntry, EntanglementProof, EntanglementProofInput, ExceptionInfo, ExceptionType, Expression, ExpressionGeneric, ExpressionGenericInput, ExpressionProof, ExpressionProofInput, ExpressionRef, ExpressionRendered, Flag, FlowInstance, FlowInstanceRecord, FlowTransitionProposal, HasMany, HasOne, HostingUserInfo, IDBCache, Icon, ImportResult, ImportStats, InteractionCall, InteractionMeta, InteractionParameter, InterpretationOverlay, InterpretationRun, LanguageExpression, LanguageHandle, LanguageLanguageInput, LanguageMeta, LanguageMetaInput, LanguageMetaInternal, LanguageRef, Link, LinkExpression, LinkExpressionInput, LinkExpressionMutations, LinkExpressionUpdated, LinkInput, LinkMutations, LinkQuery, Literal, LocalModel, LocalModelInput, Model$1 as Model, ModelApi, ModelApiInput, ModelInput, ModelQueryBuilder, Neighbourhood, NeighbourhoodExpression, NeighbourhoodProxy, Notification, NotificationInput, NullCache, OnlineAgent, Optional, PaymentRequestResult, Perspective, PerspectiveDiff, PerspectiveDiffExpression, PerspectiveExpression, PerspectiveHandle, PerspectiveInput, PerspectiveProxy, PerspectiveState, PerspectiveUnsignedInput, Property, QuerySubscriptionProxy, ReadOnly, Resource, ResourceInput, RpcError as RestError, RpcError, RuntimeInfo, SHACLFlow, SHACLShape, SMART_LITERAL_CONTENT_PREDICATE, SentMessage, SmartLiteral, TokenizerSource, TokenizerSourceInput, TriggeredNotification, UserCreationResult, UserStatistics, VerificationRequestResult, VoiceActivityParamsInput, WakerSubscriptionManager, buildConformanceFilter, buildModelFromJSONSchema, buildPaginationSubquery, buildSDNA, buildSHACL, buildSPARQLQuery, buildWhereCondition, capSentence, clearQueryCache, coalesce, compileWhereClause, concat, createPersistentCache, determineNamespace, determinePredicate, effectiveLiteralStorage, escapeQueryString, exists, exprRef2String, fileToDataUri, fn, focus, formatList, formatQueryValue, formatSPARQLValue, getCachedResult, getDefaultValueForType, getMemoizedSHACL, getPropertiesMetadata, getPropertyOption, getRelationsMetadata, hasJsOnlyWhereFilters, ifExpr, invalidatePerspectiveCache, isArrayType, isExpression, isIncludeProjection, isLink, isNodeExpression, isNumericType, isObjectType, isSchemaType, linkEqual, literal, looksLikeUri, normalizeNamespaceString, normalizeSchemaType, normalizeValue, parseExprUrl, parseLit, parseLitBoolean, parseLitNumber, parseSparqlCount, path, queryCacheSize, resolveParentPredicate, setCachedResult, setPropertyRegistryEntry, setRelationRegistryEntry, typeDefsString, valueToLiteralIri };
20750
+ export { AIClient, Model as AIModel, AIModelLoadingStatus, AIPromptExamples, AIPromptExamplesInput, AITask, AITaskInput, Ad4mClient, Ad4mModel, Agent, AgentClient, AgentExpression, AgentSignature, AgentStatus, Apps, AuthInfo, AuthInfoInput, AutoProcessorConfig, BelongsToMany, BelongsToOne, Capability, CapabilityInput, ComputeLogEntry, EntanglementProof, EntanglementProofInput, ExceptionInfo, ExceptionType, Expression, ExpressionGeneric, ExpressionGenericInput, ExpressionProof, ExpressionProofInput, ExpressionRef, ExpressionRendered, Flag, FlowInstance, FlowInstanceRecord, FlowTransitionProposal, HasMany, HasOne, HostingUserInfo, IDBCache, Icon, ImportResult, ImportStats, InteractionCall, InteractionMeta, InteractionParameter, InterpretationOverlay, InterpretationRun, LanguageExpression, LanguageHandle, LanguageLanguageInput, LanguageMeta, LanguageMetaInput, LanguageMetaInternal, LanguageRef, Link, LinkExpression, LinkExpressionInput, LinkExpressionMutations, LinkExpressionUpdated, LinkInput, LinkMutations, LinkQuery, Literal, LocalModel, LocalModelInput, Model$1 as Model, ModelApi, ModelApiInput, ModelInput, ModelQueryBuilder, Neighbourhood, NeighbourhoodExpression, NeighbourhoodProxy, Notification, NotificationInput, NullCache, OnlineAgent, Optional, PaymentRequestResult, Perspective, PerspectiveDiff, PerspectiveDiffExpression, PerspectiveExpression, PerspectiveHandle, PerspectiveInput, PerspectiveProxy, PerspectiveState, PerspectiveUnsignedInput, Property, QuerySubscriptionProxy, ReadOnly, Resource, ResourceInput, RpcError as RestError, RpcError, RuntimeInfo, SHACLFlow, SHACLShape, SMART_LITERAL_CONTENT_PREDICATE, SentMessage, SmartLiteral, TokenizerSource, TokenizerSourceInput, TriggeredNotification, UserCreationResult, UserStatistics, VerificationRequestResult, VoiceActivityParamsInput, WakerSubscriptionManager, buildConformanceFilter, buildModelFromJSONSchema, buildPaginationSubquery, buildSDNA, buildSHACL, buildSPARQLQuery, buildWhereCondition, capSentence, clearQueryCache, coalesce, compileWhereClause, concat, createPersistentCache, determineNamespace, determinePredicate, effectiveLiteralStorage, escapeQueryString, exists, exprRef2String, fileToDataUri, fn, focus, formatList, formatQueryValue, formatSPARQLValue, getCachedResult, getDefaultValueForType, getMemoizedSHACL, getPropertiesMetadata, getPropertyOption, getRelationsMetadata, hasJsOnlyWhereFilters, hintFor, ifExpr, invalidatePerspectiveCache, isArrayType, isExpression, isIncludeProjection, isLink, isNodeExpression, isNumericType, isObjectType, isSchemaType, isTraverseScope, linkEqual, literal, looksLikeUri, normalizeNamespaceString, normalizeSchemaType, normalizeValue, parseExprUrl, parseLit, parseLitBoolean, parseLitNumber, parseSparqlCount, path, queryCacheSize, requireSingleParent, resolveParentPredicate, setCachedResult, setPropertyRegistryEntry, setRelationRegistryEntry, typeDefsString, valueToLiteralIri };