@cotal-ai/core 0.133.13 → 0.134.0

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 (51) hide show
  1. package/dist/backup-config.d.ts +48 -5
  2. package/dist/backup-config.d.ts.map +1 -1
  3. package/dist/backup-config.js +72 -10
  4. package/dist/backup-config.js.map +1 -1
  5. package/dist/endpoint-caller.d.ts +4 -1
  6. package/dist/endpoint-caller.d.ts.map +1 -1
  7. package/dist/endpoint-caller.js +3 -1
  8. package/dist/endpoint-caller.js.map +1 -1
  9. package/dist/endpoint-contract-store.d.ts +14 -2
  10. package/dist/endpoint-contract-store.d.ts.map +1 -1
  11. package/dist/endpoint-contract-store.js +16 -3
  12. package/dist/endpoint-contract-store.js.map +1 -1
  13. package/dist/endpoint-coverage.d.ts +55 -0
  14. package/dist/endpoint-coverage.d.ts.map +1 -0
  15. package/dist/endpoint-coverage.js +206 -0
  16. package/dist/endpoint-coverage.js.map +1 -0
  17. package/dist/endpoint.d.ts +67 -20
  18. package/dist/endpoint.d.ts.map +1 -1
  19. package/dist/endpoint.js +111 -75
  20. package/dist/endpoint.js.map +1 -1
  21. package/dist/index.d.ts +3 -0
  22. package/dist/index.d.ts.map +1 -1
  23. package/dist/index.js +3 -0
  24. package/dist/index.js.map +1 -1
  25. package/dist/issued-authority.d.ts +48 -0
  26. package/dist/issued-authority.d.ts.map +1 -1
  27. package/dist/issued-authority.js +78 -0
  28. package/dist/issued-authority.js.map +1 -1
  29. package/dist/provision.d.ts +27 -6
  30. package/dist/provision.d.ts.map +1 -1
  31. package/dist/provision.js +91 -10
  32. package/dist/provision.js.map +1 -1
  33. package/dist/registry-client.d.ts +39 -0
  34. package/dist/registry-client.d.ts.map +1 -0
  35. package/dist/registry-client.js +58 -0
  36. package/dist/registry-client.js.map +1 -0
  37. package/dist/registry-contract.d.ts +79 -0
  38. package/dist/registry-contract.d.ts.map +1 -0
  39. package/dist/registry-contract.js +105 -0
  40. package/dist/registry-contract.js.map +1 -0
  41. package/dist/space-schema-diff.d.ts +2 -2
  42. package/dist/space-schema-diff.d.ts.map +1 -1
  43. package/dist/space-schema-diff.js +29 -2
  44. package/dist/space-schema-diff.js.map +1 -1
  45. package/dist/streams.d.ts +46 -5
  46. package/dist/streams.d.ts.map +1 -1
  47. package/dist/streams.js +120 -8
  48. package/dist/streams.js.map +1 -1
  49. package/dist/types.d.ts +3 -2
  50. package/dist/types.d.ts.map +1 -1
  51. package/package.json +1 -1
package/dist/endpoint.js CHANGED
@@ -18,6 +18,8 @@ import { EpEnvelopeError, respondedButUnbound, replyRefusedBeforeEffect, replyTa
18
18
  import { isRepeatSafeCommand } from "./endpoint-grants.js";
19
19
  import { assertIdToken, assertGeneration } from "./endpoint-subjects.js";
20
20
  import { importNativeSubjectPermissions, issuedPermitsSubject, readAcceptedRow } from "./issued-authority.js";
21
+ import { REGISTRY_ENDPOINT, REGISTRY_ENDPOINTS_COMMAND } from "./registry-contract.js";
22
+ import { listRegistryEndpoints, registryListingCaller } from "./registry-client.js";
21
23
  import { lastKvEntries, liveKvEntries } from "./kv-scan.js";
22
24
  import { isConsumerAlreadyExists, isConsumerNotFound, isJetStreamMissing } from "./jetstream-missing.js";
23
25
  import { isRestoredConsumer } from "./backup.js";
@@ -25,7 +27,7 @@ import { ARTIFACT_PART_KIND, isArtifactPart } from "./artifact.js";
25
27
  import { assertValidKind } from "./agent-file.js";
26
28
  import { assertValidName } from "./resolve.js";
27
29
  import { EVICT_PRINCIPALS_MAX } from "./evict.js";
28
- import { createSpaceStreams, dmDurableConfig, dlvDurableConfig, taskDurableConfig, fanoutDurableConfig, inboxReaderConfig, MAX_MSGS_PER_SUBJECT, MANAGER_LEASE_TTL_MS, MANAGER_LEASE_ATTEMPT_MS, TTL_RECONCILE_CANARY_KEY, PRESENCE_STORAGE } from "./streams.js";
30
+ import { createSpaceStreams, dmDurableConfig, dlvDurableConfig, taskDurableConfig, fanoutDurableConfig, inboxReaderConfig, MANAGER_LEASE_TTL_MS, MANAGER_LEASE_ATTEMPT_MS, TTL_RECONCILE_CANARY_KEY, PRESENCE_STORAGE } from "./streams.js";
29
31
  import { jetstream, jetstreamManager, AckPolicy, DeliverPolicy, JetStreamApiCodes, JetStreamApiError, } from "@nats-io/jetstream";
30
32
  import {} from "@nats-io/jetstream";
31
33
  import { Kvm } from "@nats-io/kv";
@@ -212,6 +214,10 @@ export class CotalEndpoint extends EventEmitter {
212
214
  bearerSource;
213
215
  /** The freshest bearer — what every (re)connect attempt presents. */
214
216
  currentBearer;
217
+ /** The expiry, in seconds, of the credential the latest connect attempt presented. The issuer
218
+ * keys a listing generation on it (SPEC 13.15), so a listing reads the row bound to the
219
+ * credential the broker admitted, never one adopted since. */
220
+ presentedExp;
215
221
  /** Cancels the armed bearer renewal or retry. */
216
222
  cancelBearerRenewal;
217
223
  /** Consecutive failed bearer renewals: the retry's step, and whether this run of failures has
@@ -863,6 +869,18 @@ export class CotalEndpoint extends EventEmitter {
863
869
  : "this endpoint's creds have expired and it holds no creds source to renew them - replace the credential and rebuild the endpoint (pass a creds FUNCTION for standing renewal)");
864
870
  return creds;
865
871
  }
872
+ /** The connect attempt's credential getters: what {@link credsForWire} and {@link bearerForWire}
873
+ * return, with its expiry recorded as {@link presentedExp}. */
874
+ presentCreds() {
875
+ const creds = this.credsForWire();
876
+ this.presentedExp = credsClaims(creds).exp;
877
+ return creds;
878
+ }
879
+ presentBearer() {
880
+ const bearer = this.bearerForWire();
881
+ this.presentedExp = bearerExpiryMs(bearer) / 1000;
882
+ return bearer;
883
+ }
866
884
  /** The cached credential, checked. Handed to nats.js as the authenticator's source on EVERY auth
867
885
  * mode (renewed or static), so each (re)connect attempt — ours or the library's — re-reads a
868
886
  * CHECKED value. A refusal throws out of the authenticator, which nats-core turns into a closed
@@ -1269,7 +1287,7 @@ export class CotalEndpoint extends EventEmitter {
1269
1287
  // and dialed ANONYMOUSLY, so the broker answered `Authorization Violation` and the real fault
1270
1288
  // (an empty credential) was never named. Routing it into the checked getter fails it loud
1271
1289
  // instead. Anonymous access stays reachable the only way it should be: by passing no creds.
1272
- ...authOpts({ token: this.token, user: this.user, pass: this.pass, creds: this.currentCreds !== undefined || this.credsSource ? () => this.credsForWire() : undefined, bearer: this.userMode ? () => this.bearerForWire() : undefined, sentinelCreds: this.sentinelCreds, tls: this.tls,
1290
+ ...authOpts({ token: this.token, user: this.user, pass: this.pass, creds: this.currentCreds !== undefined || this.credsSource ? () => this.presentCreds() : undefined, bearer: this.userMode ? () => this.presentBearer() : undefined, sentinelCreds: this.sentinelCreds, tls: this.tls,
1273
1291
  onCreds: (creds) => {
1274
1292
  watchDeletePermission = undefined;
1275
1293
  try {
@@ -2400,6 +2418,46 @@ export class CotalEndpoint extends EventEmitter {
2400
2418
  this.resolvedServices.set(endpoint, svc);
2401
2419
  return svc;
2402
2420
  }
2421
+ /** The caller a registry listing rides (SPEC 13.15). An issued connection lists as itself. Any
2422
+ * other connection reads the listing generation the issuer bound to the credential it presented,
2423
+ * under the token its connection id and that credential's expiry derive. `undefined`: that
2424
+ * credential carries no listing binding, because it predates listing issuance or has no expiry. */
2425
+ async listingCaller() {
2426
+ if (!this.nc)
2427
+ throw new Error(this.notLiveMsg());
2428
+ return registryListingCaller(this.nc, this.space, this.serviceCaller(), { connId: this.connId, ...(this.presentedExp !== undefined ? { exp: this.presentedExp } : {}) });
2429
+ }
2430
+ /** One page of the registry's `endpoints` answer (SPEC 13.20) over this connection
2431
+ * ({@link listRegistryEndpoints}). The describe rides this connection's own caller; the question
2432
+ * rides the listing caller on an authed mesh. `unbound`: this credential carries no listing
2433
+ * binding. */
2434
+ async listEndpoints(input, opts = {}) {
2435
+ if (!this.nc)
2436
+ throw new Error(this.notLiveMsg());
2437
+ const nc = this.nc;
2438
+ const listing = this.authed ? await this.listingCaller() : undefined;
2439
+ if (this.authed && listing === undefined)
2440
+ return { unbound: true };
2441
+ return this.listEndpointsOver(nc, listing, input, opts);
2442
+ }
2443
+ /** Ask the registry over `nc` under `listing`: this connection, or another of this caller triple
2444
+ * such as a manager-call connection. The describe rides this connection, whose view holds the
2445
+ * registry's describe. Every endpoint the page lists has its cached describe dropped, so the next
2446
+ * describe of it reads the surface afresh. `unbound`: the broker refused the question under
2447
+ * `listing`, whose credential holds no listing row. */
2448
+ async listEndpointsOver(nc, listing, input, opts = {}) {
2449
+ if (!this.nc)
2450
+ throw new Error(this.notLiveMsg());
2451
+ const own = this.nc;
2452
+ const result = await listRegistryEndpoints(this.space, (deadlineMs, signal) => resolveService(own, this.space, REGISTRY_ENDPOINT, this.serviceCaller(), {
2453
+ deadlineMs, signal, commands: [REGISTRY_ENDPOINTS_COMMAND],
2454
+ }), { nc, ...(listing ? { caller: listing } : {}) }, input, opts);
2455
+ if (result.unbound)
2456
+ return result;
2457
+ for (const row of result.page?.rows ?? [])
2458
+ this.clearResolvedService(row.endpoint);
2459
+ return result;
2460
+ }
2403
2461
  /** GENERIC v0.4 service invoke over this endpoint's own connection: resolve
2404
2462
  * the named endpoint's registered surface — describe, §13.7 store fetch, digest-verified
2405
2463
  * recompile ({@link resolveService}; cached per endpoint name) — and invoke one command. The
@@ -2991,7 +3049,7 @@ export class CotalEndpoint extends EventEmitter {
2991
3049
  // As in listChannels: an absent CHAT stream holds nothing yet; any other failure stays loud.
2992
3050
  if (!isJetStreamMissing(e, JetStreamApiCodes.StreamNotFound))
2993
3051
  throw e;
2994
- return { perSender: null, maxAgeMs: null, senders: [], stream: false, lastSeq: 0 };
3052
+ return { perSender: null, maxAgeMs: null, oldestAt: null, senders: [], stream: false, lastSeq: 0 };
2995
3053
  }
2996
3054
  const senders = [];
2997
3055
  for (const [subject, messages] of Object.entries(info.state.subjects ?? {})) {
@@ -3004,6 +3062,8 @@ export class CotalEndpoint extends EventEmitter {
3004
3062
  return {
3005
3063
  perSender: typeof cap === "number" && cap > 0 ? cap : null,
3006
3064
  maxAgeMs: typeof age === "number" && age > 0 ? Math.round(age / 1_000_000) : null,
3065
+ // The stream's oldest post, of any channel; every post sent before it is gone.
3066
+ oldestAt: info.state.messages > 0 ? info.state.first_ts : null,
3007
3067
  senders: senders.sort((a, b) => a.channel.localeCompare(b.channel) || a.sender.localeCompare(b.sender)),
3008
3068
  stream: true,
3009
3069
  lastSeq: info.state.last_seq,
@@ -4906,7 +4966,10 @@ export class CotalEndpoint extends EventEmitter {
4906
4966
  * record (CAS + generation bump), then ACTIVATION CATCH-UP idempotently copies `(joinCursor, fence]`
4907
4967
  * into the owner inbox where `fence = max(frontier, fanoutDelivered)` — fan-out owns `seq > fence`.
4908
4968
  * Idempotent against a timeout-retry (an already-activated membership no-ops). Returns `{durable:false}`
4909
- * (honest degrade) only if the catch-up window was evicted.
4969
+ * only when a concurrent leave or rejoin superseded the activation. Catch-up copies what the stream
4970
+ * still holds and does not judge retention: a post the history limit removed before its copy was
4971
+ * taken is outside the durable guarantee (SPEC §4), and stream state cannot show which channel a
4972
+ * removed sequence belonged to.
4910
4973
  *
4911
4974
  * Runs on the daemon (which hosts the fan-out/reader loops + the members KV), so catch-up + the
4912
4975
  * activation fence read are in-process — no cross-process cursor read.
@@ -4929,7 +4992,7 @@ export class CotalEndpoint extends EventEmitter {
4929
4992
  return { durable: true, generation: existing.record.generation }; // fully activated — idempotent
4930
4993
  // Either a NEW join (no record / a tombstone to supersede) → fresh joinCursor + bumped generation,
4931
4994
  // OR a retry of an INCOMPLETE activation (durable-active but not yet activated, from an earlier
4932
- // eviction/crash) → re-run catch-up over the SAME join window, no bump. The record is committed
4995
+ // crash or failed catch-up) → re-run catch-up over the SAME join window, no bump. The record is committed
4933
4996
  // `activated:false` first and routes IN-INTERVAL immediately (fan-out + reader deliver via the
4934
4997
  // pure-interval durableEligible) so no live message published during catch-up is lost. `activated`
4935
4998
  // gates only the REPORT — durableJoin returns true / channelMembers lists the owner only after the
@@ -4949,24 +5012,7 @@ export class CotalEndpoint extends EventEmitter {
4949
5012
  await this.keepRowIfAclAllows(kv, owner, lifecycleUid, channel, written.revision);
4950
5013
  }
4951
5014
  const fence = Math.max(await this.chatFrontier(), await this.fanoutDeliveredSeq());
4952
- const cu = await this.catchupCopy(owner, lifecycleUid, channel, joinCursor, fence, generation);
4953
- if (cu.evicted) {
4954
- // Catch-up window irreparably evicted (the oldest in-window message aged out) — this join can never
4955
- // be a complete backstop. TOMBSTONE the just-committed record at `fence` so it does NOT route:
4956
- // pure-interval durableEligible would otherwise keep delivering to a record the agent was told is
4957
- // durable:false AND can't discover to leave (critic BLOCKER-1). Pass `generation` as the expected
4958
- // generation (ux stale-write guard) so this cleanup can't tombstone a concurrent NEWER rejoin — if
4959
- // one won, StaleMembershipWrite is the correct no-op (the rejoin is the live record). Then degrade
4960
- // honestly — a retry is a fresh join (no longer `open`, so a current joinCursor is captured).
4961
- try {
4962
- await tombstoneMember(kv, channel, owner, lifecycleUid, fence, this.card.id, generation);
4963
- }
4964
- catch (e) {
4965
- if (!(e instanceof StaleMembershipWrite))
4966
- throw e;
4967
- }
4968
- return { durable: false, reason: "activation catch-up window partially evicted by retention", generation };
4969
- }
5015
+ await this.catchupCopy(owner, lifecycleUid, channel, joinCursor, fence, generation);
4970
5016
  // Flip → reported durable, ATOMICALLY: refuse if a concurrent SAME-generation leave (tombstone) or a
4971
5017
  // rejoin superseded this pending join while catch-up ran. A blind same-gen commit would clobber the
4972
5018
  // tombstone (clear leaveCursor) and resurrect the membership, reopening §7 (review-general-2 BLOCKER).
@@ -5025,18 +5071,12 @@ export class CotalEndpoint extends EventEmitter {
5025
5071
  }
5026
5072
  /** Idempotently copy the eligible chat messages in `(fromSeqExcl, toSeqIncl]` for `channel` into the
5027
5073
  * owner inbox, via a DEDICATED per-(owner,join) ephemeral consumer (NOT the agent-scoped
5028
- * `chathist_<id>`/`histLock` — red-team HIGH-8). `evicted` ⇒ the oldest eligible seq aged out under
5029
- * `discard=Old` (the start seq could not be served), a durable shortfall the caller surfaces. */
5074
+ * `chathist_<id>`/`histLock` — red-team HIGH-8). It copies what the stream still holds in that
5075
+ * window; a post the history limit removed first is not copied and is not reported (SPEC §4). */
5030
5076
  async catchupCopy(owner, lifecycleUid, channel, fromSeqExcl, toSeqIncl, generation) {
5031
5077
  if (!this.js || !this.jsm || toSeqIncl <= fromSeqExcl)
5032
- return { copied: 0, evicted: false };
5078
+ return 0;
5033
5079
  const subject = chatSubject(this.space, "*", "*", channel);
5034
- // Eviction = a message in `(joinCursor, …]` on THIS channel's subject aged out under discard=Old.
5035
- // Judged PER-SUBJECT (reuse channelDropped: oldest-retained-for-subject vs the watermark, only at
5036
- // the per-subject cap), NOT against the stream-global joinCursor+1 — other channels' traffic
5037
- // inflates the global seq, so a naive "first delivered seq > joinCursor+1" false-positives on any
5038
- // busy multi-channel space (impl-review HIGH-2). A true eviction → durableJoin reports durable:false.
5039
- const evicted = await this.channelDropped(subject, fromSeqExcl);
5040
5080
  // Consumer NAME must be JetStream-safe (no `.`) AND collision-free: use the principal DASH-form
5041
5081
  // (`<owner>-<actor>`, `-` reserved as the sole separator), NOT `token(owner)` — `token()` maps the
5042
5082
  // dot-form `.`→`_`, which is NOT collision-free (`_` is legal inside a token, so `a.b_c` and `a_b.c`
@@ -5045,6 +5085,7 @@ export class CotalEndpoint extends EventEmitter {
5045
5085
  // delete/recreate a predecessor's in-flight catch-up consumer — the uid disambiguates.
5046
5086
  const cuP = parsePrincipalKey(owner);
5047
5087
  const name = `cu_${cuP ? lifecycleNameKey(cuP.owner, cuP.actor, lifecycleUid) : `${token(owner)}-${lifecycleUid}`}_${generation}`;
5088
+ // A failed read throws, leaving the pending row to retry over the same window.
5048
5089
  await this.deleteConsumerIfPresent(chatStream(this.space), name);
5049
5090
  await this.jsm.consumers.add(chatStream(this.space), {
5050
5091
  name, filter_subject: subject, ack_policy: AckPolicy.None, mem_storage: true,
@@ -5061,7 +5102,7 @@ export class CotalEndpoint extends EventEmitter {
5061
5102
  for await (const m of iter) {
5062
5103
  got++;
5063
5104
  if (m.seq > toSeqIncl)
5064
- return { copied, evicted };
5105
+ return copied;
5065
5106
  let msg;
5066
5107
  try {
5067
5108
  msg = m.json();
@@ -5083,7 +5124,7 @@ export class CotalEndpoint extends EventEmitter {
5083
5124
  finally {
5084
5125
  await this.deleteConsumerIfPresent(chatStream(this.space), name);
5085
5126
  }
5086
- return { copied, evicted };
5127
+ return copied;
5087
5128
  }
5088
5129
  /** Start the Plane-3 fan-out writer + trusted reader on THIS (privileged, server-side delivery-daemon)
5089
5130
  * endpoint, AND serve the `ctl.delivery` control service (runtime durable join/leave/list). `aclFor`
@@ -6948,10 +6989,11 @@ export class CotalEndpoint extends EventEmitter {
6948
6989
  /**
6949
6990
  * Replay-gated pull of a channel's retained ambient from `sinceSeq` (exclusive) forward — the
6950
6991
  * focus-recall read behind `cotal_inbox`. Returns the messages (NOT emitted — this is a pull,
6951
- * not a push into context) plus `dropped: true` when the window is not complete: either the
6952
- * channel's earliest *retained* message is already newer than the watermark (some ambient aged
6953
- * out of the per-subject window), or replay is off for the channel below. Either way the caller
6954
- * must say so rather than silently reporting an empty, complete window. `seqs[i]` is the chat
6992
+ * not a push into context) plus `dropped: true` when the window may not be complete: the stream's
6993
+ * limits may have removed posts after the watermark ({@link chatMayHaveLost}: a sender at the
6994
+ * per-sender limit, or the stream's oldest post already past the watermark), or replay is off
6995
+ * for the channel below. Either way the caller must say so rather than silently reporting an
6996
+ * empty, complete window. `seqs[i]` is the chat
6955
6997
  * stream sequence of `messages[i]`, the one identity two identical messages do not share.
6956
6998
  * `unanswered` is true when no history read answered (replay is off, or the read failed), so
6957
6999
  * `messages` says nothing about what the channel retains.
@@ -7002,49 +7044,43 @@ export class CotalEndpoint extends EventEmitter {
7002
7044
  collected.push(authenticatedMessage(msg, parsed));
7003
7045
  seqs.push(sm.seq);
7004
7046
  }
7005
- const dropped = await this.channelDropped(subject, sinceSeq);
7006
- return { messages: collected, seqs, dropped, unanswered: false };
7007
- }
7008
- /** Did focus recall on `subject` miss ambient that aged out past the watermark? Ambient is only
7009
- * ever discarded once a sender-subject reaches {@link MAX_MSGS_PER_SUBJECT} (`DiscardPolicy.Old`);
7010
- * below the cap nothing was evicted, so the window is complete — return false without crying
7011
- * wolf. At the cap, the surviving oldest seq decides: if it already postdates the watermark, the
7012
- * eviction reached into the "since you focused" window. (Avoids the false positive of comparing a
7013
- * per-subject oldest against the stream-global frontier, which fires on any other channel's
7014
- * traffic.) */
7015
- async channelDropped(subject, sinceSeq) {
7016
- if (!this.jsm)
7017
- return false;
7018
- let maxPerSubject = 0;
7047
+ let dropped;
7019
7048
  try {
7020
- const info = await this.jsm.streams.info(chatStream(this.space), { subjects_filter: subject });
7021
- for (const count of Object.values(info.state.subjects ?? {}))
7022
- maxPerSubject = Math.max(maxPerSubject, count);
7049
+ dropped = await this.chatMayHaveLost(subject, sinceSeq);
7023
7050
  }
7024
7051
  catch (e) {
7025
- if (e.code !== 404)
7026
- this.emit("error", e);
7027
- return false; // stream/subject missing — nothing retained, nothing dropped
7052
+ // Completeness could not be read, so the read is reported as unanswered: nothing settles on it.
7053
+ this.emit("error", e);
7054
+ if (isPermissionDenied(e))
7055
+ throw e;
7056
+ return { messages: [], seqs: [], dropped: true, unanswered: true };
7028
7057
  }
7029
- if (maxPerSubject < MAX_MSGS_PER_SUBJECT)
7030
- return false; // never hit the cap ⇒ never evicted
7031
- const oldest = await this.channelOldestSeq(subject);
7032
- return oldest !== undefined && oldest > sinceSeq + 1;
7058
+ return { messages: collected, seqs, dropped, unanswered: false };
7033
7059
  }
7034
- /** Sequence of the earliest message still retained on a channel subject (any sender), or
7035
- * undefined if nothing is retained. One message through the contained {@link collectHistory} —
7036
- * used for the recall drop marker. */
7037
- async channelOldestSeq(subject) {
7060
+ /** Whether the chat stream's limits may have removed posts on `subject` after `sinceSeq`, read from
7061
+ * the stream's own config rather than a compiled default. Throws when it cannot read, so no caller
7062
+ * takes an unread stream for a complete one. It reports possible loss, never proof: a removed
7063
+ * sequence does not record its subject, so the stream cannot say which channel lost it.
7064
+ *
7065
+ * Either rule is enough. The stream's oldest retained post is past the watermark, so every post up
7066
+ * to it is gone, from this channel or another. Or a sender on the channel is at the stream's
7067
+ * per-sender limit and the channel's oldest retained post is past the watermark, so that sender's
7068
+ * eviction may have reached into the window; a sender at exactly the limit may have lost nothing.
7069
+ * A hole behind a retained older post, as a channel-filtered purge leaves, sets neither. */
7070
+ async chatMayHaveLost(subject, sinceSeq) {
7038
7071
  if (!this.jsm)
7039
- return undefined;
7040
- try {
7041
- const [first] = await this.collectHistory(subject, { seq: 1 }, { limit: 1 });
7042
- return first?.seq;
7043
- }
7044
- catch (e) {
7045
- this.emit("error", e);
7046
- return undefined;
7047
- }
7072
+ throw new Error(this.notLiveMsg());
7073
+ const info = await this.jsm.streams.info(chatStream(this.space), { subjects_filter: subject });
7074
+ if (info.state.first_seq > sinceSeq + 1)
7075
+ return true;
7076
+ const cap = info.config.max_msgs_per_subject;
7077
+ let maxPerSubject = 0;
7078
+ for (const count of Object.values(info.state.subjects ?? {}))
7079
+ maxPerSubject = Math.max(maxPerSubject, count);
7080
+ if (cap < 1 || maxPerSubject < cap)
7081
+ return false; // no sender at the cap ⇒ none evicted
7082
+ const oldest = (await this.collectHistory(subject, { seq: 1 }, { limit: 1 }))[0]?.seq;
7083
+ return oldest !== undefined && oldest > sinceSeq + 1;
7048
7084
  }
7049
7085
  async publishPresence() {
7050
7086
  if (!this.doRegister || !this.kv)