@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.cjs CHANGED
@@ -2097,6 +2097,18 @@ interpretationHint) {
2097
2097
  const propMeta = properties[propName];
2098
2098
  if (!propMeta.through)
2099
2099
  continue; // Skip properties without predicates
2100
+ // `@BelongsToOne`/`@BelongsToMany` register in both maps: the relation
2101
+ // registry describes the edge, and `applyPropertyMetadata` marks the
2102
+ // accessor read-only so the non-owning side gets no setter. Both loops
2103
+ // then emitted a shape for it, so an inverse relation appeared twice in
2104
+ // the generated SHACL — once thinly, from here, and once with its target
2105
+ // class, polymorphism and ordering, from the relation loop below.
2106
+ //
2107
+ // The relation loop is the complete description, so this one stands
2108
+ // aside. Skipping by presence in the relation map rather than by kind
2109
+ // keeps it right for any future decorator that registers in both.
2110
+ if (allRelationsMeta[propName])
2111
+ continue;
2100
2112
  const propShape = {
2101
2113
  name: propName,
2102
2114
  path: propMeta.through,
@@ -4713,6 +4725,13 @@ class PerspectiveProxy {
4713
4725
  async rejectInterpretation(base, property) {
4714
4726
  return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").rejectInterpretation(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, base, property);
4715
4727
  }
4728
+ async acceptFlowProposal(proposalUri) {
4729
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").acceptFlowProposal(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, proposalUri);
4730
+ }
4731
+ /** Withdraw our own links from a proposal; resolves to how many went. */
4732
+ async rejectFlowProposal(proposalUri) {
4733
+ return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").rejectFlowProposal(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, proposalUri);
4734
+ }
4716
4735
  /** Subscribe to this perspective's auto-processor step signals. */
4717
4736
  async addAutoProcessorEventListener(cb) {
4718
4737
  return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").addAutoProcessorEventListener(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, cb);
@@ -4957,11 +4976,48 @@ class PerspectiveProxy {
4957
4976
  /**
4958
4977
  * Removes a link from the perspective.
4959
4978
  *
4960
- * @param link - The link to remove
4979
+ * Accepts either a full `LinkExpressionInput` (as returned by `add`) or a bare
4980
+ * `Link` (source/predicate/target only). When a bare Link is passed the method
4981
+ * resolves it to the first stored `LinkExpression` whose source, predicate, and
4982
+ * target match, then removes that expression. A bare Link without a predicate
4983
+ * (or with the constructor's `""` stand-in) matches only stored links that
4984
+ * themselves have no predicate. If no match is found an error is thrown
4985
+ * naming the link so the caller knows what was expected.
4986
+ *
4987
+ * @param link - The link to remove (LinkExpressionInput or bare Link)
4961
4988
  * @param batchId - Optional batch ID to group this operation with others
4962
4989
  */
4963
4990
  async remove(link, batchId) {
4964
- const result = await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").removeLink(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, link, batchId);
4991
+ let resolvedLink;
4992
+ if (!('data' in link) || link.data === undefined) {
4993
+ // bare Link — resolve to stored expression
4994
+ const bare = link;
4995
+ // The Link constructor coerces an absent predicate to "" and the
4996
+ // store reports predicate-less links as predicate null — so ""
4997
+ // and undefined both mean "no predicate" here, and neither may
4998
+ // widen the query: dropping the filter would resolve (and
4999
+ // remove!) an arbitrary source→target link under a *different*
5000
+ // predicate. LinkQuery cannot express "predicate is absent", so
5001
+ // in that case we query on source/target only and require the
5002
+ // absence ourselves.
5003
+ const predicateGiven = bare.predicate !== undefined && bare.predicate !== '';
5004
+ const candidates = await this.get(new LinkQuery({
5005
+ source: bare.source || undefined,
5006
+ predicate: predicateGiven ? bare.predicate : undefined,
5007
+ target: bare.target || undefined,
5008
+ }));
5009
+ const matches = predicateGiven
5010
+ ? candidates
5011
+ : candidates.filter(m => !m.data.predicate);
5012
+ if (matches.length === 0) {
5013
+ throw new Error(`PerspectiveProxy.remove: no stored LinkExpression matches Link { source: "${bare.source}", predicate: "${bare.predicate}", target: "${bare.target}" }`);
5014
+ }
5015
+ resolvedLink = matches[0];
5016
+ }
5017
+ else {
5018
+ resolvedLink = link;
5019
+ }
5020
+ const result = await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").removeLink(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, resolvedLink, batchId);
4965
5021
  invalidatePerspectiveCache(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid);
4966
5022
  return result;
4967
5023
  }
@@ -5549,6 +5605,38 @@ class PerspectiveProxy {
5549
5605
  return [];
5550
5606
  }
5551
5607
  }
5608
+ /**
5609
+ * Return the full target-class URIs of every registered SubjectClass.
5610
+ *
5611
+ * Unlike {@link subjectClasses}, which strips the namespace and returns bare
5612
+ * names (`"Space"`, `"Channel"`), this method returns the complete URIs
5613
+ * (`"we://Space"`, `"flux://Channel"`). The full URI is the key that
5614
+ * `load_shape` resolves against, so it is the only collision-safe identifier
5615
+ * — two apps can both declare a class called `"Template"` under different
5616
+ * namespaces, and the bare name cannot distinguish them.
5617
+ *
5618
+ * Callers that need to check whether a *set* of models are already
5619
+ * registered should call this once and test membership against the returned
5620
+ * set, rather than issuing one `queryLinks` per model.
5621
+ *
5622
+ * One `queryLinks` round trip, no executor-side changes.
5623
+ */
5624
+ async subjectClassTargetClasses() {
5625
+ try {
5626
+ const classLinks = await this.get(new LinkQuery({
5627
+ predicate: "rdf://type",
5628
+ target: "ad4m://SubjectClass"
5629
+ }));
5630
+ const uris = classLinks
5631
+ .map(l => l.data.source)
5632
+ .filter(source => source.length > 0);
5633
+ return [...new Set(uris)];
5634
+ }
5635
+ catch (e) {
5636
+ console.warn('subjectClassTargetClasses: lookup failed:', e);
5637
+ return [];
5638
+ }
5639
+ }
5552
5640
  async stringOrTemplateObjectToSubjectClassName(subjectClass) {
5553
5641
  if (typeof subjectClass === "string")
5554
5642
  return subjectClass;
@@ -6563,6 +6651,18 @@ class PerspectiveClient {
6563
6651
  async rejectInterpretation(uuid, base, property) {
6564
6652
  return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.rejectInterpretation', { uuid, base, property });
6565
6653
  }
6654
+ async acceptFlowProposal(uuid, proposalUri) {
6655
+ return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.acceptFlowProposal', { uuid, proposalUri });
6656
+ }
6657
+ /**
6658
+ * Withdraw this agent's own links from a proposal. Resolves to how many
6659
+ * were retracted — one for a withdrawn vote, more when retracting a
6660
+ * proposal this agent opened.
6661
+ */
6662
+ async rejectFlowProposal(uuid, proposalUri) {
6663
+ const result = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, "f").call('perspective.rejectFlowProposal', { uuid, proposalUri });
6664
+ return result.retractedLinks;
6665
+ }
6566
6666
  /**
6567
6667
  * Subscribe to auto-processor step signals. `cb` fires for every
6568
6668
  * `auto-processor-event` on `uuid` (BatchReady → Claimed/BackedOff/… →
@@ -14927,6 +15027,21 @@ class AIClient {
14927
15027
  async getModels() {
14928
15028
  return __classPrivateFieldGet$2(this, _AIClient_apiClient, "f").call('ai.models');
14929
15029
  }
15030
+ /**
15031
+ * Ask a remote endpoint which models it serves, before adding one.
15032
+ *
15033
+ * Takes the credentials of a model that does not exist yet — a settings
15034
+ * form is being filled in and wants the list to pick from. Rejects when
15035
+ * the endpoint is unreachable or the key is refused, which makes this the
15036
+ * credential check too: without it a bad key surfaces later as a failed
15037
+ * completion carrying an error from a different layer.
15038
+ *
15039
+ * `apiType` defaults to the OpenAI shape, which is what every endpoint
15040
+ * that is not Anthropic speaks.
15041
+ */
15042
+ async discoverModels(baseUrl, apiKey, apiType) {
15043
+ return __classPrivateFieldGet$2(this, _AIClient_apiClient, "f").call('ai.discoverModels', { baseUrl, apiKey, apiType });
15044
+ }
14930
15045
  async addModel(model) {
14931
15046
  return __classPrivateFieldGet$2(this, _AIClient_apiClient, "f").call('ai.addModel', { model: this.serializeModelInput(model) });
14932
15047
  }
@@ -15037,6 +15152,27 @@ class AIClient {
15037
15152
  }
15038
15153
  _AIClient_apiClient = new WeakMap(), _AIClient_transcriptionUnsubscribers = new WeakMap(), _AIClient_pendingStreamIds = new WeakMap();
15039
15154
 
15155
+ /**
15156
+ * Shared type definitions for the Ad4mModel system.
15157
+ *
15158
+ * Extracted into a standalone module so that utility files
15159
+ * (`query-utils.ts`, `decorators.ts`, etc.) can import types without
15160
+ * creating circular runtime dependencies on `Ad4mModel.ts`.
15161
+ */
15162
+ /**
15163
+ * Whether this scope is a traversal rather than a single named parent.
15164
+ *
15165
+ * The other two forms carry `id`; this one carries `ids` and may name several,
15166
+ * so anything reaching for one parent — every write path — has to ask first.
15167
+ */
15168
+ function isTraverseScope(scope) {
15169
+ return 'ids' in scope;
15170
+ }
15171
+ /** Type guard for IncludeProjection objects. */
15172
+ function isIncludeProjection(val) {
15173
+ return typeof val === 'object' && val !== null && 'from' in val;
15174
+ }
15175
+
15040
15176
  /**
15041
15177
  * Shared query helpers used by both the Prolog and SPARQL query pipelines.
15042
15178
  */
@@ -15049,6 +15185,21 @@ _AIClient_apiClient = new WeakMap(), _AIClient_transcriptionUnsubscribers = new
15049
15185
  * - With `field`: direct key lookup
15050
15186
  * - Without `field`: scan for a relation whose `target()` matches `childCtor`
15051
15187
  */
15188
+ /**
15189
+ * Narrow a scope to the one-parent forms, for the paths that write a link.
15190
+ *
15191
+ * A traversal describes a read outward from several anchors. Creating a record
15192
+ * "under" one would have to pick which, and nothing in the scope says — so this
15193
+ * refuses rather than guessing at the first of the list. The executor's write
15194
+ * scopes refuse it for the same reason.
15195
+ */
15196
+ function requireSingleParent(parent) {
15197
+ if (isTraverseScope(parent)) {
15198
+ throw new Error('parent(): a traverse scope describes a read and names no single parent to write under. ' +
15199
+ 'Use { id, predicate } or { model, id } when creating a record under a parent.');
15200
+ }
15201
+ return parent;
15202
+ }
15052
15203
  function resolveParentPredicate(parent, childCtor) {
15053
15204
  // Raw form — explicit predicate
15054
15205
  if ('predicate' in parent)
@@ -15629,8 +15780,31 @@ function buildSPARQLQuery(metadata, allRelationsMetadata, query, modelClass) {
15629
15780
  // Parent filter — direct triple pattern
15630
15781
  if (query.parent) {
15631
15782
  const parentPredicate = resolveParentPredicate(query.parent, modelClass);
15632
- joinPatterns.push(`
15783
+ if (isTraverseScope(query.parent)) {
15784
+ const { ids, transitive, direction, limitPerAnchor } = query.parent;
15785
+ // `limitPerAnchor` is applied by the executor between selecting ids and
15786
+ // hydrating them, which is a shape this path does not have — it builds one
15787
+ // query and reads the rows. Refused rather than ignored: quietly returning
15788
+ // every reply where five per parent were asked for is a wrong answer that
15789
+ // looks like a right one.
15790
+ if (limitPerAnchor !== undefined) {
15791
+ throw new Error('buildSPARQLQuery: limitPerAnchor is applied by the executor between query phases and ' +
15792
+ 'has no equivalent here. Use the model query path for per-anchor limits.');
15793
+ }
15794
+ const anchors = (Array.isArray(ids) ? ids : [ids]).map(iri).join(' ');
15795
+ const path = transitive ? '+' : '';
15796
+ joinPatterns.push(`
15797
+ VALUES ?_anchor { ${anchors} }`);
15798
+ joinPatterns.push(direction === 'in'
15799
+ ? `
15800
+ ?source ${iri(parentPredicate)}${path} ?_anchor .`
15801
+ : `
15802
+ ?_anchor ${iri(parentPredicate)}${path} ?source .`);
15803
+ }
15804
+ else {
15805
+ joinPatterns.push(`
15633
15806
  ${iri(query.parent.id)} ${iri(parentPredicate)} ?source .`);
15807
+ }
15634
15808
  }
15635
15809
  // Required property JOIN patterns — direct triple patterns
15636
15810
  let hasConformance = false;
@@ -16289,13 +16463,10 @@ class ModelQueryBuilder {
16289
16463
  const unsubscribe = this.perspective.client.subscribeToQueryUpdates(subscriptionId, (rawResult) => {
16290
16464
  try {
16291
16465
  const results = parseResults(rawResult);
16292
- console.debug(`[ModelQueryBuilder.subscribe] Update received for ${subscriptionId}: ${results.length} instances`);
16293
16466
  const fp = buildFingerprint(results);
16294
16467
  if (fp === lastResultFingerprint) {
16295
- console.debug(`[ModelQueryBuilder.subscribe] Fingerprint unchanged, skipping callback`);
16296
16468
  return;
16297
16469
  }
16298
- console.debug(`[ModelQueryBuilder.subscribe] Fingerprint changed, calling callback with ${results.length} results`);
16299
16470
  lastResultFingerprint = fp;
16300
16471
  callback(results);
16301
16472
  }
@@ -16564,8 +16735,21 @@ class ModelQueryBuilder {
16564
16735
  offset: pageSize * (pageNumber - 1),
16565
16736
  count: true,
16566
16737
  };
16738
+ // Each server dispatch triggers an independent async re-fetch, and those
16739
+ // re-fetches resolve in completion order, not dispatch order. A re-fetch
16740
+ // dispatched *before* a write committed can resolve *after* the re-fetch
16741
+ // that saw the write, silently rolling the consumer back to a stale page —
16742
+ // and no later dispatch ever corrects it. The generation counter drops any
16743
+ // fetch that is no longer the newest one started; the newest fetch always
16744
+ // delivers, so the callback is monotone in dispatch order.
16745
+ let fetchGeneration = 0;
16567
16746
  const processResults = async () => {
16747
+ const generation = ++fetchGeneration;
16568
16748
  const { results, totalCount } = await ctor.executeModelQuery(this.perspective, paginatedQuery, this.modelClassName);
16749
+ if (generation !== fetchGeneration) {
16750
+ console.debug(`[ModelQueryBuilder.paginateSubscribe] Dropping stale re-fetch result (generation ${generation}, newest ${fetchGeneration})`);
16751
+ return;
16752
+ }
16569
16753
  callback({ results, totalCount, pageSize, pageNumber });
16570
16754
  };
16571
16755
  const unsubscribe = this.perspective.client.subscribeToQueryUpdates(subscriptionId, (rawResult) => {
@@ -17540,7 +17724,12 @@ class Ad4mModel {
17540
17724
  const queryInput = {};
17541
17725
  if (query.parent) {
17542
17726
  const parentPredicate = resolveParentPredicate(query.parent, this);
17543
- queryInput.parent = { id: query.parent.id, predicate: parentPredicate };
17727
+ // A traversal is forwarded as it was written: the executor reads `ids`,
17728
+ // and flattening it to one `id` here is how a request for a whole level
17729
+ // would quietly become a request for one parent's children.
17730
+ queryInput.parent = isTraverseScope(query.parent)
17731
+ ? { ...query.parent, predicate: parentPredicate }
17732
+ : { id: query.parent.id, predicate: parentPredicate };
17544
17733
  }
17545
17734
  if (query.properties)
17546
17735
  queryInput.properties = query.properties;
@@ -18312,9 +18501,10 @@ class Ad4mModel {
18312
18501
  if (options?.parent && !options?.batchId) {
18313
18502
  const batchId = await perspective.createBatch();
18314
18503
  await instance.save(batchId);
18315
- const predicate = resolveParentPredicate(options.parent, this);
18504
+ const parent = requireSingleParent(options.parent);
18505
+ const predicate = resolveParentPredicate(parent, this);
18316
18506
  const link = new Link({
18317
- source: options.parent.id,
18507
+ source: parent.id,
18318
18508
  predicate,
18319
18509
  target: instance.id,
18320
18510
  });
@@ -18328,9 +18518,10 @@ class Ad4mModel {
18328
18518
  await instance.save(options?.batchId);
18329
18519
  // Create parent → child link if a parent scope was provided
18330
18520
  if (options?.parent) {
18331
- const predicate = resolveParentPredicate(options.parent, this);
18521
+ const parent = requireSingleParent(options.parent);
18522
+ const predicate = resolveParentPredicate(parent, this);
18332
18523
  const link = new Link({
18333
- source: options.parent.id,
18524
+ source: parent.id,
18334
18525
  predicate,
18335
18526
  target: instance.id,
18336
18527
  });
@@ -19271,7 +19462,13 @@ exports.FlowInstanceRecord = class FlowInstanceRecord extends Ad4mModel {
19271
19462
  * on read.
19272
19463
  */
19273
19464
  this.subject = "";
19274
- /** Name of the state the flow is currently in. */
19465
+ /**
19466
+ * The state name this replica's executor last derived for the flow — a
19467
+ * per-replica cache written as a `local` link, never the authority (the
19468
+ * fold over the signed proposals is). Optional on the shape: a row that
19469
+ * synced in from a peer carries no value until the local consensus pass
19470
+ * has run, so an empty string means "not yet derived here".
19471
+ */
19275
19472
  this.currentState = "";
19276
19473
  // "When was this flow started?" is answered by `Ad4mModel`'s built-in
19277
19474
  // `createdAt`, synthesized on hydration from the earliest link timestamp
@@ -19287,7 +19484,7 @@ __decorate([
19287
19484
  __metadata("design:type", String)
19288
19485
  ], exports.FlowInstanceRecord.prototype, "subject", void 0);
19289
19486
  __decorate([
19290
- Property({ through: "ad4m://flow/current_state", required: true }),
19487
+ Property({ through: "ad4m://flow/current_state", local: true }),
19291
19488
  __metadata("design:type", String)
19292
19489
  ], exports.FlowInstanceRecord.prototype, "currentState", void 0);
19293
19490
  exports.FlowInstanceRecord = __decorate([
@@ -19313,7 +19510,7 @@ exports.FlowInstanceRecord = __decorate([
19313
19510
  * than the `wrap` escape hatch, which exists for tests that already own
19314
19511
  * a matched (record, shape) pair.
19315
19512
  *
19316
- * # What's here vs. what's coming in §7 / slice 10.6
19513
+ * # What's here, and what is still absent
19317
19514
  *
19318
19515
  * Read surface (implemented today, PR #929):
19319
19516
  * - `uri`, `subject`, `flowName`, `currentStateName`, `startedAtMillis`
@@ -19324,12 +19521,18 @@ exports.FlowInstanceRecord = __decorate([
19324
19521
  * - `proposals()` — queries `FlowTransitionProposal` records that
19325
19522
  * target this instance's URI.
19326
19523
  *
19327
- * Mutations + subscriptions (`proposeTransition`, `accept`, `reject`,
19328
- * `fireAction`, `onStateChange`, `onProposalAdded`, `onProposalResolved`)
19329
- * land with the consensus-engine slice (§4.3 / slice 10.6). Rather than
19330
- * ship them as `throw new Error("not yet")` stubs — which is a type-level
19331
- * lie the caller only discovers at runtime — they are simply absent from
19332
- * this class until the engine is wired.
19524
+ * - `acceptProposal()` / `rejectProposal()` — the consensus write API:
19525
+ * accept counts your DID toward the flow's consensusRule and fires the
19526
+ * transition at quorum; reject withdraws only the links you signed and
19527
+ * resolves to how many went. Reject is not a cancel — another agent's
19528
+ * proposal is theirs, and because state is recomputed from the links
19529
+ * present now, withdrawing a vote that had settled an edge moves the
19530
+ * flow back to where it stood before it.
19531
+ *
19532
+ * Still absent (rather than shipped as `throw new Error("not yet")`
19533
+ * stubs): `proposeTransition`, `fireAction`, and the subscriptions
19534
+ * (`onStateChange`, `onProposalAdded`, `onProposalResolved`) — they land
19535
+ * with the manual-proposal and subscription-topic slices.
19333
19536
  */
19334
19537
  /**
19335
19538
  * Extract the flow's human-readable name from its canonical URI.
@@ -19392,9 +19595,15 @@ class FlowInstance {
19392
19595
  *
19393
19596
  * The returned wrapper carries the parsed `SHACLFlow` alongside the
19394
19597
  * on-graph record, so `currentState` / `availableTransitions` /
19395
- * `proposals` accessors work without further round-trips. The consensus
19396
- * engine (slice 10.6) will read the record's `currentState` when it
19397
- * fires transitions.
19598
+ * `proposals` accessors work without further round-trips.
19599
+ *
19600
+ * The record's `currentState` is a per-replica cache the consensus engine
19601
+ * writes as a local link. It is read back only for display — the cache-first
19602
+ * path in `gather_active_flow_contexts` fills the state rendered into LLM
19603
+ * context — and **never as authority**: anything that decides something
19604
+ * (the fold, the mint pass) derives state from the signed links present now
19605
+ * and does not consult the cache. Treat it as a display hint, not as the
19606
+ * flow's state.
19398
19607
  *
19399
19608
  * @param perspective - The perspective the flow instance lives on
19400
19609
  * @param flowName - Name of a `SHACLFlow` already registered on the perspective
@@ -19554,7 +19763,7 @@ class FlowInstance {
19554
19763
  * `FlowTransitionProposal.flowInstance` references).
19555
19764
  */
19556
19765
  get uri() {
19557
- return this.record.baseExpression;
19766
+ return this.record.id;
19558
19767
  }
19559
19768
  /**
19560
19769
  * URI of the base expression this flow runs on — matches the
@@ -19619,14 +19828,25 @@ class FlowInstance {
19619
19828
  * for the where-filter — one SPARQL round-trip, no client-side
19620
19829
  * filtering.
19621
19830
  *
19622
- * Note: the consensus engine (slice 10.6) will start writing these; today
19623
- * they only exist when a client wrote one directly (or a test seeded one).
19831
+ * These are written by the executor's consensus pass when it mints a
19832
+ * transition, and by clients proposing directly. Superseded proposals are
19833
+ * not swept here — a stale one is simply never counted by the fold, and
19834
+ * accepting it fails with a stale-state error.
19624
19835
  */
19625
19836
  async proposals() {
19626
19837
  return exports.FlowTransitionProposal.findAll(this.perspective, {
19627
19838
  where: { flowInstance: this.uri },
19628
19839
  });
19629
19840
  }
19841
+ async acceptProposal(proposal) {
19842
+ const uri = typeof proposal === "string" ? proposal : proposal.id;
19843
+ return this.perspective.acceptFlowProposal(uri);
19844
+ }
19845
+ /** Withdraw our own links from a proposal; resolves to how many went. */
19846
+ async rejectProposal(proposal) {
19847
+ const uri = typeof proposal === "string" ? proposal : proposal.id;
19848
+ return this.perspective.rejectFlowProposal(uri);
19849
+ }
19630
19850
  }
19631
19851
 
19632
19852
  /**
@@ -19748,15 +19968,73 @@ function parseLitBoolean(val) {
19748
19968
  /**
19749
19969
  * WakerSubscriptionManager — manages live query subscriptions for the waker.
19750
19970
  *
19751
- * Lives in core so it can be imported by both the plugin and integration tests
19752
- * without ESM/CJS import issues.
19971
+ * This is the single implementation: it is exported from `@coasys/ad4m` and
19972
+ * used by the integration tests, and the OpenClaw AD4M plugin re-exports this
19973
+ * module (`plugins/ad4m/wakerSubscriptionManager.ts`) rather than carrying its
19974
+ * own copy. Any behaviour change belongs here.
19975
+ */
19976
+ /**
19977
+ * Add a short cause hint to known subscription failures.
19978
+ * The executor needs its main key to register a live query; on a restarted
19979
+ * executor whose wallet was never unlocked this surfaces as a bare 403.
19980
+ */
19981
+ function hintFor(msg) {
19982
+ // "Executor is locked" is the current executor's message; "main key not
19983
+ // found" is what older executors (and unrelated key lookups) say for the
19984
+ // same locked state. Either way the caller cannot fix it themselves: keys
19985
+ // live in memory only, so every restart locks the node again and only its
19986
+ // operator can unlock it.
19987
+ if (/executor is locked/i.test(msg) || /main key not found/i.test(msg)) {
19988
+ 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";
19989
+ }
19990
+ if (/timed out after \d+ms/i.test(msg)) {
19991
+ 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";
19992
+ }
19993
+ return "";
19994
+ }
19995
+ /**
19996
+ * Reject `promise` after `ms` instead of waiting forever.
19753
19997
  *
19754
- * NOTE: keep in sync with plugins/ad4m/wakerSubscriptionManager.ts
19998
+ * The pending set only catches rejections. A handshake that hangs — the
19999
+ * executor accepted the socket but never answers — settles nothing, so the
20000
+ * subscription was recorded nowhere and the caller's tool invocation died at
20001
+ * the harness timeout instead (#1016). The underlying promise is left as is:
20002
+ * the caller disposes the proxy, so a late answer backs out on its own.
19755
20003
  */
20004
+ async function withTimeout(promise, ms, message) {
20005
+ let timer;
20006
+ try {
20007
+ return await Promise.race([
20008
+ promise,
20009
+ new Promise((_resolve, reject) => {
20010
+ timer = setTimeout(() => reject(new Error(message)), ms);
20011
+ }),
20012
+ ]);
20013
+ }
20014
+ finally {
20015
+ if (timer)
20016
+ clearTimeout(timer);
20017
+ }
20018
+ }
19756
20019
  class WakerSubscriptionManager {
19757
20020
  constructor(options) {
19758
20021
  this.proxies = new Map();
19759
20022
  this.activeSubscriptions = new Map();
20023
+ /** Subscriptions the executor rejected, waiting to be re-attempted. */
20024
+ this.pendingSubscriptions = new Map();
20025
+ this.retryTimer = null;
20026
+ /**
20027
+ * Cancellation tokens for in-flight `subscribe()` calls.
20028
+ *
20029
+ * `subscribe()` awaits `proxy.subscribe()` and `proxy.initialized`; a
20030
+ * `dispose()` / `disposeAll()` landing during either await used to leave a
20031
+ * live subscription behind, because nothing stopped the resumed call from
20032
+ * registering the proxy in `proxies` / `activeSubscriptions` afterwards.
20033
+ * `epoch` is bumped by `disposeAll()` (which cannot enumerate in-flight
20034
+ * ids), `generations` per id by `dispose()` and by each new `subscribe()`.
20035
+ */
20036
+ this.epoch = 0;
20037
+ this.generations = new Map();
19760
20038
  this.debounceTimers = new Map();
19761
20039
  /** Per-subscription set of already-processed message addresses (for mention subs)
19762
20040
  * or serialized result hash (for channel-messages subs). */
@@ -19768,6 +20046,18 @@ class WakerSubscriptionManager {
19768
20046
  this.onPersist = options.onPersist;
19769
20047
  this.QuerySubscriptionProxyCtor = options.QuerySubscriptionProxy ?? null;
19770
20048
  this.previousSeenMessages = options.previousSeenMessages ?? {};
20049
+ this.retryPendingMs = options.retryPendingMs ?? 30000;
20050
+ this.subscribeTimeoutMs = options.subscribeTimeoutMs ?? 15000;
20051
+ }
20052
+ /** A token identifying this attempt at subscribing `id`. */
20053
+ beginAttempt(id) {
20054
+ const gen = (this.generations.get(id) ?? 0) + 1;
20055
+ this.generations.set(id, gen);
20056
+ return { epoch: this.epoch, gen };
20057
+ }
20058
+ /** Whether this attempt has been superseded by a dispose or a newer one. */
20059
+ isStale(id, token) {
20060
+ return token.epoch !== this.epoch || this.generations.get(id) !== token.gen;
19771
20061
  }
19772
20062
  /**
19773
20063
  * Create a live SPARQL subscription.
@@ -19776,6 +20066,7 @@ class WakerSubscriptionManager {
19776
20066
  async subscribe(sub) {
19777
20067
  // Dispose existing subscription with same id if any
19778
20068
  this.dispose(sub.id, false);
20069
+ const token = this.beginAttempt(sub.id);
19779
20070
  if (!this.QuerySubscriptionProxyCtor) {
19780
20071
  throw new Error("WakerSubscriptionManager: QuerySubscriptionProxy must be provided via constructor options");
19781
20072
  }
@@ -19790,9 +20081,24 @@ class WakerSubscriptionManager {
19790
20081
  if (proxy.initialized && typeof proxy.initialized.catch === "function") {
19791
20082
  proxy.initialized.catch(() => { });
19792
20083
  }
20084
+ // One deadline for the whole handshake: `proxy.subscribe()` and the
20085
+ // `initialized` promise it resolves share the budget, so a hang in either
20086
+ // surfaces as the same loud-but-recoverable failure a rejection does.
20087
+ const budgetMs = this.subscribeTimeoutMs;
20088
+ const startedAt = Date.now();
20089
+ const bounded = (step, what) => budgetMs > 0
20090
+ ? withTimeout(step, Math.max(0, budgetMs - (Date.now() - startedAt)), `${what} timed out after ${budgetMs}ms`)
20091
+ : step;
19793
20092
  try {
19794
- await proxy.subscribe();
19795
- await proxy.initialized;
20093
+ await bounded(proxy.subscribe(), "subscribe handshake");
20094
+ if (this.isStale(sub.id, token)) {
20095
+ try {
20096
+ proxy.dispose();
20097
+ }
20098
+ catch { }
20099
+ return;
20100
+ }
20101
+ await bounded(proxy.initialized, "subscription initialization");
19796
20102
  }
19797
20103
  catch (err) {
19798
20104
  const msg = err?.message ?? String(err);
@@ -19801,12 +20107,36 @@ class WakerSubscriptionManager {
19801
20107
  proxy.dispose();
19802
20108
  }
19803
20109
  catch { }
19804
- // Remove from active state so it doesn't get persisted/retried
20110
+ // A dispose that landed mid-attempt wins: don't re-queue something the
20111
+ // caller has since asked us to forget.
20112
+ if (this.isStale(sub.id, token))
20113
+ return;
20114
+ // Remove from active state — it is not listening, so it must not be
20115
+ // reported as active or persisted as if it were.
19805
20116
  this.activeSubscriptions.delete(sub.id);
19806
20117
  this.seenMessages.delete(sub.id);
19807
20118
  this.persist();
19808
- return; // Don't throw — caller should not crash
20119
+ // Keep it pending and re-attempt: the usual cause (locked wallet, executor
20120
+ // mid-restart, a handshake the executor never answered) clears on its
20121
+ // own, and the caller asked to be enrolled.
20122
+ this.pendingSubscriptions.set(sub.id, sub);
20123
+ this.scheduleRetry();
20124
+ // Throw so callers can report the real outcome. Background callers
20125
+ // (auto-subscribe, restore-on-start) catch and log; the subscribe tools
20126
+ // turn this into an error result instead of a false "Subscribed" reply.
20127
+ throw new Error(`Waker subscription ${sub.id} failed: ${msg}${hintFor(msg)}` +
20128
+ (this.retryPendingMs > 0
20129
+ ? `. Not listening yet — re-attempting every ${Math.round(this.retryPendingMs / 1000)}s; check ad4m_list_waker_subscriptions.`
20130
+ : ""));
20131
+ }
20132
+ if (this.isStale(sub.id, token)) {
20133
+ try {
20134
+ proxy.dispose();
20135
+ }
20136
+ catch { }
20137
+ return;
19809
20138
  }
20139
+ this.pendingSubscriptions.delete(sub.id);
19810
20140
  this.logger.info(`[waker] ${sub.id}: subscription initialized successfully`);
19811
20141
  // Seed from persisted seen messages so we don't re-wake after restart
19812
20142
  const seen = new Set(this.previousSeenMessages[sub.id] ?? []);
@@ -19887,16 +20217,72 @@ class WakerSubscriptionManager {
19887
20217
  }, this.debounceMs));
19888
20218
  }
19889
20219
  });
20220
+ if (this.isStale(sub.id, token)) {
20221
+ try {
20222
+ proxy.dispose();
20223
+ }
20224
+ catch { }
20225
+ return;
20226
+ }
19890
20227
  this.proxies.set(sub.id, proxy);
19891
20228
  this.activeSubscriptions.set(sub.id, sub);
19892
20229
  this.persist();
19893
20230
  this.logger.info(`[waker] Subscription ${sub.id} active (type=${sub.type}, perspective=${sub.perspective})`);
19894
20231
  }
20232
+ /** Arm the re-attempt timer if pending subscriptions are waiting. */
20233
+ scheduleRetry() {
20234
+ if (this.retryPendingMs <= 0)
20235
+ return;
20236
+ if (this.retryTimer || this.pendingSubscriptions.size === 0)
20237
+ return;
20238
+ this.retryTimer = setTimeout(() => {
20239
+ this.retryTimer = null;
20240
+ void this.retryPending();
20241
+ }, this.retryPendingMs);
20242
+ if (typeof this.retryTimer.unref === "function")
20243
+ this.retryTimer.unref();
20244
+ }
20245
+ /**
20246
+ * Re-attempt every subscription the executor rejected.
20247
+ * Each attempt that fails puts itself back into the pending set and re-arms
20248
+ * the timer, so an agent that asked to be subscribed ends up enrolled once
20249
+ * the executor can accept the query.
20250
+ */
20251
+ async retryPending() {
20252
+ const waiting = Array.from(this.pendingSubscriptions.values());
20253
+ if (waiting.length === 0)
20254
+ return;
20255
+ this.logger.info(`[waker] re-attempting ${waiting.length} pending subscription(s)`);
20256
+ const epoch = this.epoch;
20257
+ for (const sub of waiting) {
20258
+ // A disposeAll() between two awaits must stop the whole sweep, and a
20259
+ // dispose() of this id must skip just it.
20260
+ if (epoch !== this.epoch)
20261
+ return;
20262
+ if (!this.pendingSubscriptions.has(sub.id))
20263
+ continue;
20264
+ this.pendingSubscriptions.delete(sub.id);
20265
+ try {
20266
+ await this.subscribe(sub);
20267
+ this.logger.info(`[waker] ${sub.id}: enrolled on re-attempt`);
20268
+ }
20269
+ catch (err) {
20270
+ // subscribe() already logged, re-queued and re-armed the timer.
20271
+ this.logger.debug(`[waker] ${sub.id}: still pending — ${err?.message ?? err}`);
20272
+ }
20273
+ }
20274
+ }
20275
+ /** Subscriptions that were rejected and are waiting to be re-attempted. */
20276
+ getPending() {
20277
+ return Array.from(this.pendingSubscriptions.values());
20278
+ }
19895
20279
  /**
19896
20280
  * Dispose a single subscription.
19897
20281
  * @param persist — if false, skip calling onPersist (used during batch cleanup).
19898
20282
  */
19899
20283
  dispose(id, persist = true) {
20284
+ // Invalidate any subscribe() for this id that is still awaiting.
20285
+ this.generations.set(id, (this.generations.get(id) ?? 0) + 1);
19900
20286
  const proxy = this.proxies.get(id);
19901
20287
  if (proxy) {
19902
20288
  try {
@@ -19913,15 +20299,24 @@ class WakerSubscriptionManager {
19913
20299
  this.debounceTimers.delete(id);
19914
20300
  }
19915
20301
  this.activeSubscriptions.delete(id);
20302
+ this.pendingSubscriptions.delete(id);
19916
20303
  this.seenMessages.delete(id);
19917
20304
  if (persist)
19918
20305
  this.persist();
19919
20306
  }
19920
- /** Dispose all active subscriptions. */
20307
+ /** Dispose all active subscriptions and drop anything still pending. */
19921
20308
  disposeAll() {
20309
+ // Bump the epoch first: in-flight subscribe() calls have no proxy in the
20310
+ // map yet, so per-id invalidation alone cannot reach them.
20311
+ this.epoch++;
19922
20312
  for (const [id] of this.proxies) {
19923
20313
  this.dispose(id, false);
19924
20314
  }
20315
+ this.pendingSubscriptions.clear();
20316
+ if (this.retryTimer) {
20317
+ clearTimeout(this.retryTimer);
20318
+ this.retryTimer = null;
20319
+ }
19925
20320
  }
19926
20321
  /** Get all active subscriptions. */
19927
20322
  getActive() {
@@ -20019,18 +20414,6 @@ class SmartLiteral {
20019
20414
  }
20020
20415
  _SmartLiteral_perspective = new WeakMap(), _SmartLiteral_base = new WeakMap();
20021
20416
 
20022
- /**
20023
- * Shared type definitions for the Ad4mModel system.
20024
- *
20025
- * Extracted into a standalone module so that utility files
20026
- * (`query-utils.ts`, `decorators.ts`, etc.) can import types without
20027
- * creating circular runtime dependencies on `Ad4mModel.ts`.
20028
- */
20029
- /** Type guard for IncludeProjection objects. */
20030
- function isIncludeProjection(val) {
20031
- return typeof val === 'object' && val !== null && 'from' in val;
20032
- }
20033
-
20034
20417
  /**
20035
20418
  * Shared query compilation utilities.
20036
20419
  *
@@ -20505,6 +20888,7 @@ exports.getPropertiesMetadata = getPropertiesMetadata;
20505
20888
  exports.getPropertyOption = getPropertyOption;
20506
20889
  exports.getRelationsMetadata = getRelationsMetadata;
20507
20890
  exports.hasJsOnlyWhereFilters = hasJsOnlyWhereFilters;
20891
+ exports.hintFor = hintFor;
20508
20892
  exports.ifExpr = ifExpr;
20509
20893
  exports.invalidatePerspectiveCache = invalidatePerspectiveCache;
20510
20894
  exports.isArrayType = isArrayType;
@@ -20515,6 +20899,7 @@ exports.isNodeExpression = isNodeExpression;
20515
20899
  exports.isNumericType = isNumericType;
20516
20900
  exports.isObjectType = isObjectType;
20517
20901
  exports.isSchemaType = isSchemaType;
20902
+ exports.isTraverseScope = isTraverseScope;
20518
20903
  exports.linkEqual = linkEqual;
20519
20904
  exports.literal = literal;
20520
20905
  exports.looksLikeUri = looksLikeUri;
@@ -20528,6 +20913,7 @@ exports.parseLitNumber = parseLitNumber;
20528
20913
  exports.parseSparqlCount = parseSparqlCount;
20529
20914
  exports.path = path;
20530
20915
  exports.queryCacheSize = queryCacheSize;
20916
+ exports.requireSingleParent = requireSingleParent;
20531
20917
  exports.resolveParentPredicate = resolveParentPredicate;
20532
20918
  exports.setCachedResult = setCachedResult;
20533
20919
  exports.setPropertyRegistryEntry = setPropertyRegistryEntry;