@maximem/synap-js-sdk 0.4.0 → 0.4.2

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.
@@ -3,7 +3,7 @@
3
3
  * Compatibility shim.
4
4
  *
5
5
  * `npx synap-js-sdk setup` used to build a Python virtualenv and install the
6
- * Python SDK into it. Since 1.0 the SDK is native TypeScript, so there is
6
+ * Python SDK into it. Since 0.4 the SDK is native TypeScript, so there is
7
7
  * nothing to set up.
8
8
  *
9
9
  * The command is kept, and kept exiting 0, because it appears in published
@@ -17,7 +17,7 @@
17
17
  const [, , command] = process.argv;
18
18
 
19
19
  const NOTE = `
20
- @maximem/synap-js-sdk 1.x is a native TypeScript SDK. It does not use Python,
20
+ @maximem/synap-js-sdk 0.4+ is a native TypeScript SDK. It does not use Python,
21
21
  so there is no setup step and this command does nothing.
22
22
 
23
23
  If you are upgrading from 0.3.x:
@@ -37,7 +37,7 @@ switch (command) {
37
37
  break;
38
38
  case '--version':
39
39
  case '-v':
40
- console.log(process.env['npm_package_version'] ?? '1.x');
40
+ console.log(process.env['npm_package_version'] ?? '0.4+');
41
41
  break;
42
42
  default:
43
43
  console.log(`Unknown command: ${command}\n\n${NOTE}`);
@@ -0,0 +1,10 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
+
3
+
4
+ var _chunkRB57I2IQcjs = require('./chunk-RB57I2IQ.cjs');
5
+ require('./chunk-ZKOJDUN4.cjs');
6
+
7
+
8
+
9
+ exports.ANY_SCOPE = _chunkRB57I2IQcjs.ANY_SCOPE; exports.AnticipationCache = _chunkRB57I2IQcjs.AnticipationCache;
10
+ //# sourceMappingURL=anticipation-cache-ARYEEKMU.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/anish/maximemai/maximem_synap/synap/sdk/js/dist/anticipation-cache-JBZHTJ3O.cjs"],"names":[],"mappings":"AAAA;AACE;AACA;AACF,wDAA6B;AAC7B,gCAA6B;AAC7B;AACE;AACA;AACF,iHAAC","file":"/Users/anish/maximemai/maximem_synap/synap/sdk/js/dist/anticipation-cache-JBZHTJ3O.cjs"}
1
+ {"version":3,"sources":["/Users/anish/maximemai/maximem_synap/synap/sdk/js/dist/anticipation-cache-ARYEEKMU.cjs"],"names":[],"mappings":"AAAA;AACE;AACA;AACF,wDAA6B;AAC7B,gCAA6B;AAC7B;AACE;AACA;AACF,iHAAC","file":"/Users/anish/maximemai/maximem_synap/synap/sdk/js/dist/anticipation-cache-ARYEEKMU.cjs"}
@@ -110,6 +110,7 @@ interface AnticipationCacheOptions {
110
110
  onLookup?: (telemetry: LookupTelemetry) => void;
111
111
  }
112
112
  declare class AnticipationCache {
113
+ #private;
113
114
  private readonly ttlSeconds;
114
115
  private readonly maxBundles;
115
116
  private readonly now;
@@ -147,6 +148,15 @@ declare class AnticipationCache {
147
148
  * contract, which caps lookup telemetry rather than this snapshot.
148
149
  */
149
150
  snapshot(): AnticipationCacheSnapshot;
151
+ /**
152
+ * The freshest `user_summary` bundle for this entity, or null.
153
+ *
154
+ * `entityId` is REQUIRED, and a missing one refuses the lookup rather than
155
+ * falling back to the freshest summary across all users. Python hardened this
156
+ * for exactly that reason: the permissive version could splice user A's
157
+ * summary into user B's response on the conversation-scope path.
158
+ */
159
+ lookupUserSummary(entityId: string | null | undefined): Record<string, unknown> | null;
150
160
  /**
151
161
  * Drop every bundle belonging to one conversation.
152
162
  *
@@ -110,6 +110,7 @@ interface AnticipationCacheOptions {
110
110
  onLookup?: (telemetry: LookupTelemetry) => void;
111
111
  }
112
112
  declare class AnticipationCache {
113
+ #private;
113
114
  private readonly ttlSeconds;
114
115
  private readonly maxBundles;
115
116
  private readonly now;
@@ -147,6 +148,15 @@ declare class AnticipationCache {
147
148
  * contract, which caps lookup telemetry rather than this snapshot.
148
149
  */
149
150
  snapshot(): AnticipationCacheSnapshot;
151
+ /**
152
+ * The freshest `user_summary` bundle for this entity, or null.
153
+ *
154
+ * `entityId` is REQUIRED, and a missing one refuses the lookup rather than
155
+ * falling back to the freshest summary across all users. Python hardened this
156
+ * for exactly that reason: the permissive version could splice user A's
157
+ * summary into user B's response on the conversation-scope path.
158
+ */
159
+ lookupUserSummary(entityId: string | null | undefined): Record<string, unknown> | null;
150
160
  /**
151
161
  * Drop every bundle belonging to one conversation.
152
162
  *
@@ -1,10 +1,10 @@
1
1
  import {
2
2
  ANY_SCOPE,
3
3
  AnticipationCache
4
- } from "./chunk-TCEP5OVR.js";
4
+ } from "./chunk-6LDUDKHS.js";
5
5
  import "./chunk-QBCVMPGK.js";
6
6
  export {
7
7
  ANY_SCOPE,
8
8
  AnticipationCache
9
9
  };
10
- //# sourceMappingURL=anticipation-cache-D5YHEPV3.js.map
10
+ //# sourceMappingURL=anticipation-cache-H7HEVWQC.js.map
@@ -675,6 +675,38 @@ var AnticipationCache = class {
675
675
  bundles
676
676
  };
677
677
  }
678
+ /**
679
+ * The freshest `user_summary` bundle for this entity, or null.
680
+ *
681
+ * `entityId` is REQUIRED, and a missing one refuses the lookup rather than
682
+ * falling back to the freshest summary across all users. Python hardened this
683
+ * for exactly that reason: the permissive version could splice user A's
684
+ * summary into user B's response on the conversation-scope path.
685
+ */
686
+ lookupUserSummary(entityId) {
687
+ if (!entityId) return null;
688
+ this.evictExpired();
689
+ let freshest = null;
690
+ for (const entry of this.entries.values()) {
691
+ if (entry.bundleType !== "user_summary") continue;
692
+ if (entry.entityId !== entityId && entry.entityId !== ANY_SCOPE) continue;
693
+ if (freshest === null || entry.storedAt > freshest.storedAt) freshest = entry;
694
+ }
695
+ if (freshest === null) return null;
696
+ if (!getEnvFlag("SYNAP_SDK_CACHE_HONOR_TTL_HINT")) {
697
+ freshest.storedAt = this.now();
698
+ }
699
+ return this.#bundleFor(freshest.bundleId);
700
+ }
701
+ /** Rebuild a bundle's items_by_type from the flat item records. */
702
+ #bundleFor(bundleId) {
703
+ const itemsByType = {};
704
+ for (const record of this.items) {
705
+ if (record.bundleId !== bundleId) continue;
706
+ (itemsByType[record.itemType] ??= []).push(record.itemDict);
707
+ }
708
+ return { bundle_id: bundleId, items_by_type: itemsByType };
709
+ }
678
710
  /**
679
711
  * Drop every bundle belonging to one conversation.
680
712
  *
@@ -797,4 +829,4 @@ export {
797
829
  ANY_SCOPE,
798
830
  AnticipationCache
799
831
  };
800
- //# sourceMappingURL=chunk-TCEP5OVR.js.map
832
+ //# sourceMappingURL=chunk-6LDUDKHS.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/behavior/anticipation.json","../src/behavior/contract.ts","../src/cache/bm25.ts","../src/context/anticipation-cache.ts"],"sourcesContent":["{\n \"$comment\": \"SOURCE OF TRUTH for anticipation-cache behavior, shared by the Python and JS/TS SDKs. Do not duplicate these values into either SDK's source. See ../README.md. Regexes are restricted to the intersection of Python 're' and ECMAScript; both SDKs have a parity test.\",\n \"version\": 1,\n \"recall_bypass\": {\n \"note\": \"WS4 of the playground query-hygiene plan. A recall-shaped question never serves from the anticipation cache. Asymmetric cost is why: a stale false-hit makes the agent answer 'I don't see that' while the store holds the fact (the BZQR6J cross-session failure), whereas bypassing costs only cold-fetch latency on a turn where the user already expects a lookup. Stem coverage cannot gate this \\u2014 false hits were measured at coverage=1.00. Ties break toward INCLUDING a pattern.\",\n \"env_flag\": \"SYNAP_SDK_CACHE_RECALL_BYPASS\",\n \"default\": false,\n \"patterns\": [\n {\n \"pattern\": \"\\\\bremind me\\\\b\",\n \"flags\": \"i\",\n \"note\": \"Original set (WS4, playground query-hygiene plan).\"\n },\n {\n \"pattern\": \"\\\\bon file\\\\b\",\n \"flags\": \"i\",\n \"note\": \"Original set (WS4).\"\n },\n {\n \"pattern\": \"\\\\b(your|my|the) records\\\\b\",\n \"flags\": \"i\",\n \"note\": \"Original set (WS4).\"\n },\n {\n \"pattern\": \"\\\\bdo you (have|know|remember|recall|see)\\\\b\",\n \"flags\": \"i\",\n \"note\": \"Original set (WS4).\"\n },\n {\n \"pattern\": \"\\\\bwhat (do|did) (i|you) (say|tell|mention|have)\\\\b\",\n \"flags\": \"i\",\n \"note\": \"Original set (WS4).\"\n },\n {\n \"pattern\": \"\\\\bwhat('s| is) my\\\\b\",\n \"flags\": \"i\",\n \"note\": \"Original set (WS4).\"\n },\n {\n \"pattern\": \"\\\\bwhere (am i|do i live)\\\\b\",\n \"flags\": \"i\",\n \"note\": \"Original set (WS4).\"\n },\n {\n \"pattern\": \"\\\\bhow long have i\\\\b\",\n \"flags\": \"i\",\n \"note\": \"Original set (WS4).\"\n },\n {\n \"pattern\": \"\\\\bwhich of my\\\\b\",\n \"flags\": \"i\",\n \"note\": \"Original set (WS4).\"\n },\n {\n \"pattern\": \"\\\\bwhat .{0,40}\\\\b(again|earlier|last time|previously|yesterday)\\\\b\",\n \"flags\": \"i\",\n \"note\": \"Original set (WS4). 'again' alone is deliberately NOT a marker: 'book me a ride again' is a task query, not a recall query.\"\n },\n {\n \"pattern\": \"\\\\bwill you use to (contact|reach|notify)\\\\b\",\n \"flags\": \"i\",\n \"note\": \"Original set (WS4).\"\n },\n {\n \"pattern\": \"\\\\b(confirm|verify|double.?check)\\\\b.{0,40}\\\\bmy\\\\b\",\n \"flags\": \"i\",\n \"note\": \"2026-07-16 eval register issue #11: 'can you confirm my email address?' served a stale bundle. Also catches 'confirm my booking' \\u2014 an intentional over-match, costing one cloud fetch.\"\n },\n {\n \"pattern\": \"\\\\b(linked to|associated with|registered (to|on|with)) my\\\\b\",\n \"flags\": \"i\",\n \"note\": \"2026-07-16 eval register issue #11: 'what name is linked to my Uber account?' served a stale bundle.\"\n },\n {\n \"pattern\": \"\\\\b(best|preferred) way to (reach|contact|update|notify) me\\\\b\",\n \"flags\": \"i\",\n \"note\": \"2026-07-16 eval register issue #11: 'best way to contact me with updates' served a stale bundle.\"\n },\n {\n \"pattern\": \"\\\\bhow (do|will|can|should) you (reach|contact|notify) me\\\\b\",\n \"flags\": \"i\",\n \"note\": \"2026-07-16 eval register issue #11, sibling phrasing of the above.\"\n },\n {\n \"pattern\": \"\\\\bwhich .{0,40}\\\\b(are|will) you (going to )?(use|using)\\\\b\",\n \"flags\": \"i\",\n \"note\": \"2026-07-16 eval register issue #11: 'which email are you going to use?' served a stale bundle.\"\n },\n {\n \"pattern\": \"\\\\bon (my|the) account\\\\b\",\n \"flags\": \"i\",\n \"note\": \"2026-07-16 eval register issue #11.\"\n }\n ]\n },\n \"thresholds\": {\n \"bm25\": {\n \"value\": 1.5,\n \"note\": \"Nominal threshold. The value actually applied is derived per query: max(effective_floor, min(bm25, query_token_scale * len(query_tokens))). Short queries cannot reach the nominal score, so holding them to it would miss every time.\"\n },\n \"novel_term\": {\n \"value\": 0.45,\n \"note\": \"Fraction of query stems absent from the cached corpus that forces a miss.\"\n },\n \"min_corpus_for_novel_gate\": {\n \"value\": 200,\n \"note\": \"The novel-term gate is meaningless on a small corpus, where the ratio is dominated by ordinary English word forms. Measured: a fresh playground conversation reaches ~60 stems after the first push and would trip the 0.45 gate on essentially every second-turn query. 200 means the gate engages once a customer has ~3-4 typical bundles cached.\"\n },\n \"effective_floor\": {\n \"value\": 0.6,\n \"note\": \"Lower bound on the derived per-query threshold. Below this, BM25 stops discriminating.\"\n },\n \"query_token_scale\": {\n \"value\": 0.3,\n \"note\": \"Scales the threshold down for short queries: 0.3 points of score per query token.\"\n }\n },\n \"bm25\": {\n \"k1\": 1.5,\n \"b\": 0.75,\n \"idf_floor\": 0.5,\n \"min_token_len\": 2,\n \"min_stem_len\": 4,\n \"suffixes\": [\n \"ences\",\n \"ances\",\n \"ation\",\n \"tion\",\n \"sion\",\n \"ence\",\n \"ance\",\n \"ness\",\n \"ment\",\n \"able\",\n \"ible\",\n \"ical\",\n \"ally\",\n \"ies\",\n \"ive\",\n \"ful\",\n \"ous\",\n \"ing\",\n \"ary\",\n \"ly\",\n \"ed\",\n \"es\",\n \"s\"\n ],\n \"stop_words\": [\n \"a\",\n \"about\",\n \"after\",\n \"an\",\n \"and\",\n \"are\",\n \"at\",\n \"be\",\n \"been\",\n \"before\",\n \"being\",\n \"but\",\n \"by\",\n \"can\",\n \"could\",\n \"did\",\n \"do\",\n \"does\",\n \"for\",\n \"from\",\n \"had\",\n \"has\",\n \"have\",\n \"how\",\n \"if\",\n \"in\",\n \"into\",\n \"is\",\n \"it\",\n \"its\",\n \"may\",\n \"might\",\n \"no\",\n \"nor\",\n \"not\",\n \"of\",\n \"on\",\n \"or\",\n \"over\",\n \"should\",\n \"so\",\n \"than\",\n \"that\",\n \"the\",\n \"then\",\n \"these\",\n \"this\",\n \"those\",\n \"to\",\n \"was\",\n \"were\",\n \"what\",\n \"when\",\n \"where\",\n \"which\",\n \"who\",\n \"whom\",\n \"why\",\n \"will\",\n \"with\",\n \"would\"\n ],\n \"alias_token\": {\n \"pattern\": \"\\\\[\\\\[([A-Za-z][A-Za-z0-9_]*_[a-z0-9]{12})\\\\]\\\\]\",\n \"note\": \"An alias label as it appears in text: [[PERSON_PHONE_h2n7v5cx8m0d]]. Kept whole rather than split, because 'person' and 'phone' are boilerplate shared by every label of that field type and would make two different people's memories score alike. Mirrors synap/cloud/shared/tokenizer.py \\u2014 keep the two in step.\"\n },\n \"suffix_note\": \"Order matters: longest-first, because _stem returns on first match. Reordering this list silently changes every stem and therefore every BM25 score.\"\n },\n \"env_flags\": {\n \"$comment\": \"Read at CALL time, never at module load. Python does os.environ.get inside the function bodies; JS must do the same or late process.env mutation stops working and the flag looks broken. See gotcha G-S.\",\n \"SYNAP_SDK_CACHE_RECALL_BYPASS\": {\n \"default\": false,\n \"truthy\": [\n \"true\",\n \"1\",\n \"yes\"\n ]\n },\n \"SYNAP_SDK_CACHE_HONOR_TTL_HINT\": {\n \"default\": false,\n \"truthy\": [\n \"true\",\n \"1\",\n \"yes\"\n ],\n \"note\": \"A bundle's server ttl_hint_seconds may only SHORTEN the global TTL, never extend it.\"\n },\n \"SYNAP_SDK_CACHE_INVALIDATE_ON_WRITE\": {\n \"default\": false,\n \"truthy\": [\n \"true\",\n \"1\",\n \"yes\"\n ],\n \"note\": \"2026-07-16 eval register issue #8: the cloud invalidates its own Redis caches on ingest, but that stops at the process boundary.\"\n },\n \"SYNAP_SDK_CACHE_MAX_ENTRY_AGE\": {\n \"default\": null,\n \"note\": \"2026-07-16 eval register issue #6: stored_at is a sliding lease renewed on hit, so under steady traffic a pre-update snapshot never expired. Defaults to 2x the sliding TTL; 0 disables.\"\n },\n \"SYNAP_SDK_CACHE_COVERAGE_MIN\": {\n \"default\": null\n }\n },\n \"coverage_gate\": {\n \"note\": \"Fraction of the query's stems present in the picked items. A bundle can clear the BM25 threshold on one shared token ('account') while lacking the asked-for fact entirely: the false HIT behind the eval's 'forgot the name' failure. ALWAYS computed and reported; ENFORCED only when SYNAP_SDK_CACHE_COVERAGE_MIN is explicitly set, so default behavior is unchanged. When it does fire it must gate BEFORE any side effect, so a rejected lookup leaves cache state untouched.\",\n \"env_flag\": \"SYNAP_SDK_CACHE_COVERAGE_MIN\",\n \"default\": null,\n \"empty_query_coverage\": 1.0\n },\n \"telemetry\": {\n \"rejected_items_cap\": {\n \"value\": 20,\n \"note\": \"Rejected items reported per lookup, highest score first, so a large cache cannot bloat the payload.\"\n },\n \"content_preview_chars\": 120\n }\n}\n","/**\n * Loader for the shared SDK behavior contract.\n *\n * The values here are tuned against measured eval failures and are shared,\n * byte-identical, with the Python SDK. They live in data rather than code\n * specifically so the two SDKs cannot drift. See\n * `synap/sdk/CONTRACT/README.md`.\n *\n * `anticipation.json` is vendored into `src/` by\n * `synap/sdk/scripts/sync-behavior.sh` and imported (not read from disk) so\n * that the bundler inlines it. Reading it with `node:fs` at runtime would work\n * in Node and break in every bundled target: Edge, Workers, and anything under\n * webpack/turbopack, where `dist/` is rewritten and relative paths do not\n * survive. It is the same failure mode as `@grpc/proto-loader` reading a\n * `.proto` off disk (gotcha G-P).\n */\n\nimport contractJson from './anticipation.json' with { type: 'json' };\n\nexport interface RecallPattern {\n pattern: string;\n flags: string;\n note: string;\n}\n\nexport interface BehaviorContract {\n version: number;\n recall_bypass: {\n note: string;\n env_flag: string;\n default: boolean;\n patterns: RecallPattern[];\n };\n thresholds: {\n bm25: { value: number; note: string };\n novel_term: { value: number; note: string };\n min_corpus_for_novel_gate: { value: number; note: string };\n effective_floor: { value: number; note: string };\n query_token_scale: { value: number; note: string };\n };\n coverage_gate: {\n note: string;\n env_flag: string;\n default: number | null;\n empty_query_coverage: number;\n };\n telemetry: {\n rejected_items_cap: { value: number; note: string };\n content_preview_chars: number;\n };\n bm25: {\n k1: number;\n b: number;\n idf_floor: number;\n min_token_len: number;\n min_stem_len: number;\n suffixes: string[];\n stop_words: string[];\n alias_token: { pattern: string; note: string };\n };\n}\n\nexport const CONTRACT = contractJson as unknown as BehaviorContract;\n\n/** ECMAScript flags we accept. Anything else is invalid in Python too. */\nconst ALLOWED_FLAGS = new Set(['i', 'm', 's']);\n\nfunction compile(pattern: string, flags: string): RegExp {\n for (const ch of flags) {\n if (!ALLOWED_FLAGS.has(ch)) {\n throw new Error(\n `Unsupported regex flag '${ch}' in behavior contract. Flags must be ` +\n `valid in both Python and ECMAScript.`,\n );\n }\n }\n return new RegExp(pattern, flags);\n}\n\n/**\n * Compiled recall-bypass patterns, in contract order.\n *\n * Deliberately NOT using the `g` flag: a global RegExp carries `lastIndex`\n * between calls, so a shared instance would match on one query and then miss\n * on the next. That failure is intermittent and traffic-dependent, which is\n * the worst kind to debug.\n */\nexport const RECALL_PATTERNS: readonly RegExp[] = CONTRACT.recall_bypass.patterns.map((p) =>\n compile(p.pattern, p.flags ?? ''),\n);\n\nexport const THRESHOLDS = {\n bm25: CONTRACT.thresholds.bm25.value,\n novelTerm: CONTRACT.thresholds.novel_term.value,\n minCorpusForNovelGate: CONTRACT.thresholds.min_corpus_for_novel_gate.value,\n /** Lower bound on the derived per-query threshold. */\n effectiveFloor: CONTRACT.thresholds.effective_floor.value,\n /** Points of score allowed per query token when deriving the threshold. */\n queryTokenScale: CONTRACT.thresholds.query_token_scale.value,\n} as const;\n\nexport const BM25_PARAMS = CONTRACT.bm25;\nexport const STOP_WORDS: ReadonlySet<string> = new Set(CONTRACT.bm25.stop_words);\n// Order is load-bearing: stem() returns on first match, so this must stay\n// longest-first exactly as the contract lists it.\nexport const SUFFIXES: readonly string[] = CONTRACT.bm25.suffixes;\nexport const ALIAS_TOKEN_SOURCE = CONTRACT.bm25.alias_token.pattern;\n\n/** True when any query string looks like an explicit memory-recall ask. */\nexport function isRecallQuery(searchQuery: readonly (string | null | undefined)[] | null | undefined): boolean {\n for (const q of searchQuery ?? []) {\n if (!q) continue;\n for (const pattern of RECALL_PATTERNS) {\n if (pattern.test(q)) return true;\n }\n }\n return false;\n}\n","/**\n * BM25 scorer for the anticipation cache.\n *\n * A faithful port of `maximem_synap/cache/bm25.py`. Every tuned value comes\n * from the shared behavior contract, so the two implementations cannot drift\n * on parameters. What they *can* still drift on is arithmetic, which is what\n * the shared conformance corpus is for.\n */\n\nimport { BM25_PARAMS, STOP_WORDS, SUFFIXES, ALIAS_TOKEN_SOURCE } from '../behavior/contract.js';\n\nconst MIN_STEM_LEN = BM25_PARAMS.min_stem_len;\nconst MIN_TOKEN_LEN = BM25_PARAMS.min_token_len;\n\nexport function stem(word: string): string {\n // Order is load-bearing: longest suffix first, return on first match.\n for (const suffix of SUFFIXES) {\n if (word.endsWith(suffix) && word.length - suffix.length >= MIN_STEM_LEN) {\n return word.slice(0, word.length - suffix.length);\n }\n }\n return word;\n}\n\n/**\n * An alias label, as it appears in text: `[[PERSON_PHONE_h2n7v5cx8m0d]]`.\n *\n * Kept whole rather than split into `person`, `phone` and the suffix, because\n * the first two are boilerplate shared by every label of that field type and\n * would make two different people's memories score alike.\n *\n * Mirrors `synap/cloud/shared/tokenizer.py`. Keep the two in step.\n */\nfunction aliasTokenRe(): RegExp {\n // Constructed per call because `g` regexes carry `lastIndex`, and this one\n // is used with replace(). A module-level shared instance would produce\n // different results on alternating calls.\n return new RegExp(ALIAS_TOKEN_SOURCE, 'g');\n}\n\nconst WORD_RE = /[a-z0-9]+/g;\n\n/** Tokenize, lowercase, remove stop words, and stem. Alias labels survive whole. */\nexport function tokenize(text: string | null | undefined): string[] {\n if (!text) return [];\n\n const labels: string[] = [];\n const remainder = text.replace(aliasTokenRe(), (_match, captured: string) => {\n labels.push(captured.toLowerCase());\n return ' ';\n });\n\n const words = remainder.toLowerCase().match(WORD_RE) ?? [];\n const out = labels.slice();\n for (const w of words) {\n if (w.length >= MIN_TOKEN_LEN && !STOP_WORDS.has(w)) out.push(stem(w));\n }\n return out;\n}\n\n/** Okapi BM25 scorer over a small in-memory corpus. */\nexport class BM25 {\n static readonly IDF_FLOOR = BM25_PARAMS.idf_floor;\n\n readonly k1: number;\n readonly b: number;\n readonly corpus: readonly (readonly string[])[];\n readonly docCount: number;\n readonly avgdl: number;\n readonly docLens: readonly number[];\n readonly idf: ReadonlyMap<string, number>;\n\n constructor(\n corpus: readonly (readonly string[])[],\n k1: number = BM25_PARAMS.k1,\n b: number = BM25_PARAMS.b,\n ) {\n this.k1 = k1;\n this.b = b;\n this.corpus = corpus;\n this.docCount = corpus.length;\n this.docLens = corpus.map((doc) => doc.length);\n // Python falls back to 1.0 rather than dividing by zero on an empty corpus.\n this.avgdl = this.docCount\n ? this.docLens.reduce((a, n) => a + n, 0) / this.docCount\n : 1.0;\n\n const idf = new Map<string, number>();\n const allTerms = new Set<string>();\n for (const doc of corpus) for (const t of doc) allTerms.add(t);\n for (const term of allTerms) {\n let df = 0;\n for (const doc of corpus) if (doc.includes(term)) df++;\n const raw = Math.log((this.docCount - df + 0.5) / (df + 0.5) + 1.0);\n idf.set(term, Math.max(raw, BM25.IDF_FLOOR));\n }\n this.idf = idf;\n }\n\n score(queryTokens: readonly string[], docIdx: number): number {\n const doc = this.corpus[docIdx];\n if (doc === undefined) return 0;\n const dl = this.docLens[docIdx] ?? 0;\n\n const tfMap = new Map<string, number>();\n for (const t of doc) tfMap.set(t, (tfMap.get(t) ?? 0) + 1);\n\n let s = 0;\n for (const term of queryTokens) {\n const tf = tfMap.get(term);\n if (tf === undefined) continue;\n const idf = this.idf.get(term) ?? BM25.IDF_FLOOR;\n const numerator = tf * (this.k1 + 1);\n const denominator = tf + this.k1 * (1 - this.b + (this.b * dl) / this.avgdl);\n s += (idf * numerator) / denominator;\n }\n return s;\n }\n\n scores(queryTokens: readonly string[]): number[] {\n return this.corpus.map((_, i) => this.score(queryTokens, i));\n }\n}\n","/**\n * In-memory TTL cache for context bundles pushed over gRPC.\n *\n * Port of `maximem_synap/cache/anticipation_cache.py`.\n *\n * ## Why this is a faithful port and not a simplification\n *\n * `@maximem/synap-vercel-adk` already contains a native TS anticipation cache,\n * and it is a simplification: a hardcoded 30-minute TTL, a plain BM25 threshold\n * with no per-query derivation, and none of the gates below. Shipping that as\n * the SDK's cache would mean two retrieval behaviors under one brand, which is\n * gotcha G-C. Every gate here exists because a specific eval failed without it:\n *\n * - **Recall bypass** runs BEFORE scoring. The measured false hit scored 2.86\n * at coverage 1.00, so no score-side gate could ever have caught it.\n * - **The novel-term gate** is suppressed below a 200-stem corpus, because at\n * cold start ordinary English trips it on nearly every query.\n * - **The per-query threshold** scales down for short queries, which otherwise\n * cannot reach the nominal score at all.\n * - **The coverage gate** catches a bundle that clears BM25 on one shared\n * token (\"account\") while lacking the asked-for fact.\n *\n * All thresholds come from the shared behavior contract.\n */\n\nimport { BM25, tokenize } from '../cache/bm25.js';\nimport { CONTRACT, THRESHOLDS, isRecallQuery } from '../behavior/contract.js';\nimport { getEnvFlag, getEnvFloat } from '../util/env.js';\n\nconst EFFECTIVE_FLOOR = CONTRACT.thresholds.effective_floor.value;\nconst QUERY_TOKEN_SCALE = CONTRACT.thresholds.query_token_scale.value;\nconst REJECTED_CAP = CONTRACT.telemetry.rejected_items_cap.value;\nconst PREVIEW_CHARS = CONTRACT.telemetry.content_preview_chars;\n\n/** Sentinel scope that matches any requester. */\nexport const ANY_SCOPE = '_any';\n\nexport interface BundleItem {\n item_id?: string;\n content?: string;\n [key: string]: unknown;\n}\n\nexport interface ContextBundle {\n bundleId: string;\n entityId?: string | null;\n conversationId?: string | null;\n itemsByType: Record<string, BundleItem[]>;\n /** Server hint; may only SHORTEN the global TTL, never extend it. */\n ttlHintSeconds?: number | null;\n /** Which anticipation pattern produced this bundle. Diagnostics only. */\n bundleType?: string | null;\n /** The queries the server anticipated. Diagnostics only. */\n searchQueries?: readonly string[] | null;\n}\n\ninterface ItemRecord {\n bundleId: string;\n itemType: string;\n content: string;\n tokens: string[];\n itemDict: BundleItem;\n}\n\ninterface EntryRecord {\n bundleId: string;\n entityId: string;\n conversationId: string | null;\n bundleType: string | null;\n searchQueries: string[];\n /** Sliding lease, refreshed on hit unless TTL hints are honoured. */\n storedAt: number;\n /** Absolute creation time; the max-entry-age cap uses this, not the lease. */\n createdAt: number;\n ttlHintSeconds: number | null;\n}\n\nexport interface LookupResult {\n itemsByType: Record<string, BundleItem[]>;\n bundleIds: string[];\n score: number;\n coverage: number;\n}\n\nexport interface LookupParams {\n searchQuery?: readonly string[] | null;\n entityId?: string | null;\n customerId?: string | null;\n clientId?: string | null;\n conversationId?: string | null;\n maxItems?: number;\n}\n\nexport type ExitReason =\n | 'empty'\n | 'recall_bypass'\n | 'no_query_tokens'\n | 'novel_term_gate'\n | 'empty_corpus'\n | 'no_items_above_threshold'\n | 'coverage_gate'\n | 'hit';\n\nexport interface LookupTelemetry {\n searchQuery: string[];\n entityId: string | null;\n customerId: string | null;\n clientId: string | null;\n conversationId: string | null;\n scopeFilterAccepted: string[];\n novelTermRatio: number | null;\n bm25Threshold: number | null;\n bm25QueryTokens: string[];\n itemsPicked: unknown[];\n itemsRejected: unknown[];\n coverage: number | null;\n hit: boolean;\n exitReason: ExitReason;\n}\n\nexport interface SnapshotItemPreview {\n type: string;\n scope: string | null;\n content: string;\n}\n\nexport interface SnapshotItemRecord {\n bundle_id: string;\n item_type: string;\n tokens: string[];\n content: string;\n}\n\nexport interface SnapshotBundle {\n bundle_id: string;\n entity_id: string;\n conversation_id: string | null;\n bundle_type: string | null;\n search_queries: string[];\n scope_counts: Record<string, number>;\n total_items: number;\n items: SnapshotItemPreview[];\n}\n\nexport interface AnticipationCacheSnapshot {\n total_entries: number;\n total_item_records: number;\n scope_breakdown_overall: Record<string, number>;\n corpus_vocab_size: number;\n corpus_vocab_sample: string[];\n item_records: SnapshotItemRecord[];\n bundles: SnapshotBundle[];\n}\n\nexport interface AnticipationCacheOptions {\n ttlSeconds?: number;\n maxBundles?: number;\n /** Injected in tests. Defaults to a monotonic clock. */\n now?: () => number;\n onLookup?: (telemetry: LookupTelemetry) => void;\n}\n\nconst DEFAULT_TTL_SECONDS = 1800;\nconst DEFAULT_MAX_BUNDLES = 50;\n\nexport class AnticipationCache {\n private readonly ttlSeconds: number;\n private readonly maxBundles: number;\n private readonly now: () => number;\n private readonly onLookup: ((t: LookupTelemetry) => void) | undefined;\n\n private entries = new Map<string, EntryRecord>();\n private items: ItemRecord[] = [];\n private corpusVocab = new Set<string>();\n private bm25: BM25 | null = null;\n private bm25Dirty = true;\n\n constructor(options: AnticipationCacheOptions = {}) {\n this.ttlSeconds = options.ttlSeconds ?? DEFAULT_TTL_SECONDS;\n this.maxBundles = options.maxBundles ?? DEFAULT_MAX_BUNDLES;\n this.now = options.now ?? monotonicNow;\n this.onLookup = options.onLookup;\n }\n\n get size(): number {\n return this.entries.size;\n }\n\n get itemCount(): number {\n return this.items.length;\n }\n\n store(bundle: ContextBundle): void {\n if (!bundle.bundleId) return;\n this.evictExpired();\n\n // Client-scope knowledge (FAQs, policies) arrives with no entity, and the\n // sentinel makes it visible to every requester.\n const entityId = bundle.entityId || ANY_SCOPE;\n\n if (this.entries.has(bundle.bundleId)) this.dropBundle(bundle.bundleId);\n\n const now = this.now();\n this.entries.set(bundle.bundleId, {\n bundleId: bundle.bundleId,\n entityId,\n conversationId: bundle.conversationId ?? null,\n bundleType: bundle.bundleType ?? null,\n searchQueries: [...(bundle.searchQueries ?? [])],\n storedAt: now,\n createdAt: now,\n ttlHintSeconds: bundle.ttlHintSeconds ?? null,\n });\n\n for (const [itemType, list] of Object.entries(bundle.itemsByType ?? {})) {\n for (const item of list ?? []) {\n const content = String(item.content ?? '');\n const tokens = tokenize(content);\n this.items.push({ bundleId: bundle.bundleId, itemType, content, tokens, itemDict: item });\n for (const t of tokens) this.corpusVocab.add(t);\n }\n }\n this.bm25Dirty = true;\n\n // LRU by lease age.\n while (this.entries.size > this.maxBundles) {\n let oldest: EntryRecord | null = null;\n for (const e of this.entries.values()) {\n if (oldest === null || e.storedAt < oldest.storedAt) oldest = e;\n }\n if (oldest === null) break;\n this.dropBundle(oldest.bundleId);\n }\n }\n\n lookup(params: LookupParams): LookupResult | null {\n const {\n searchQuery = null, entityId = null, customerId = null,\n clientId = null, conversationId = null, maxItems = 10,\n } = params;\n\n this.evictExpired();\n\n const accepted = this.buildAcceptedScope(entityId, customerId, clientId);\n const telemetry: LookupTelemetry = {\n searchQuery: (searchQuery ?? []).filter((q): q is string => Boolean(q)),\n entityId, customerId, clientId, conversationId,\n scopeFilterAccepted: [...accepted].sort(),\n novelTermRatio: null, bm25Threshold: null, bm25QueryTokens: [],\n itemsPicked: [], itemsRejected: [], coverage: null,\n hit: false, exitReason: 'empty',\n };\n\n if (this.entries.size === 0 || this.items.length === 0) {\n return this.miss(telemetry, 'empty');\n }\n\n const hasQuery = (searchQuery ?? []).some((q) => q && q.trim() !== '');\n if (!hasQuery) {\n return this.freshnessLookup(entityId, maxItems, telemetry);\n }\n\n // Recall bypass fires BEFORE scoring: a stale false-hit on a recall-shaped\n // question makes the agent deny a fact the store holds, and the measured\n // failure cleared every score-side gate.\n if (getEnvFlag(CONTRACT.recall_bypass.env_flag) && isRecallQuery(searchQuery)) {\n return this.miss(telemetry, 'recall_bypass');\n }\n\n const queryTokens = (searchQuery ?? []).flatMap((q) => tokenize(q));\n telemetry.bm25QueryTokens = queryTokens;\n if (queryTokens.length === 0) {\n return this.miss(telemetry, 'no_query_tokens');\n }\n\n const uniqueStems = new Set(queryTokens);\n let novel = 0;\n for (const s of uniqueStems) if (!this.corpusVocab.has(s)) novel++;\n const novelRatio = uniqueStems.size ? novel / uniqueStems.size : 0;\n telemetry.novelTermRatio = round4(novelRatio);\n\n // Only meaningful once the corpus has real vocabulary. Below the floor the\n // ratio is dominated by ordinary English and would miss on nearly anything.\n if (\n this.corpusVocab.size >= THRESHOLDS.minCorpusForNovelGate &&\n novelRatio >= THRESHOLDS.novelTerm\n ) {\n return this.miss(telemetry, 'novel_term_gate');\n }\n\n if (this.bm25Dirty || this.bm25 === null) {\n if (this.items.length === 0) return this.miss(telemetry, 'empty_corpus');\n this.bm25 = new BM25(this.items.map((i) => i.tokens));\n this.bm25Dirty = false;\n }\n\n const scores = this.bm25.scores(queryTokens);\n const validBundles = this.getValidBundleIds(accepted, conversationId);\n\n const effectiveThreshold = Math.max(\n EFFECTIVE_FLOOR,\n Math.min(THRESHOLDS.bm25, QUERY_TOKEN_SCALE * queryTokens.length),\n );\n telemetry.bm25Threshold = round4(effectiveThreshold);\n\n const picked: { score: number; item: ItemRecord }[] = [];\n const rejected: { score: number; payload: Record<string, unknown> }[] = [];\n\n for (let idx = 0; idx < scores.length; idx++) {\n const item = this.items[idx]!;\n const score = scores[idx]!;\n const reject = (reason: string) =>\n rejected.push({\n score,\n payload: {\n item_index: idx, bundle_id: item.bundleId, item_type: item.itemType,\n content_first_120: item.content.slice(0, PREVIEW_CHARS),\n bm25_score: round4(score), reason,\n },\n });\n if (score < effectiveThreshold) { reject('below_threshold'); continue; }\n if (!validBundles.has(item.bundleId)) { reject('scope_filter_excluded'); continue; }\n picked.push({ score, item });\n }\n\n rejected.sort((a, b) => b.score - a.score);\n telemetry.itemsRejected = rejected.slice(0, REJECTED_CAP).map((r) => r.payload);\n\n if (picked.length === 0) {\n return this.miss(telemetry, 'no_items_above_threshold');\n }\n\n picked.sort((a, b) => b.score - a.score);\n const top = picked.slice(0, maxItems);\n\n const pickedStems = new Set<string>();\n for (const { item } of top) for (const t of item.tokens) pickedStems.add(t);\n let overlap = 0;\n for (const s of uniqueStems) if (pickedStems.has(s)) overlap++;\n const coverage = uniqueStems.size ? overlap / uniqueStems.size : 1.0;\n telemetry.coverage = round4(coverage);\n\n // Observe-only unless explicitly configured. A malformed setting stays\n // observe-only rather than failing closed on every lookup.\n const coverageMin = getEnvFloat('SYNAP_SDK_CACHE_COVERAGE_MIN');\n if (coverageMin !== null && coverage < coverageMin) {\n // Gate BEFORE any side effect, so a rejected lookup leaves cache state\n // untouched and does not refresh a lease.\n return this.miss(telemetry, 'coverage_gate');\n }\n\n const itemsByType: Record<string, BundleItem[]> = {};\n const bundleIds = new Set<string>();\n for (const { item } of top) {\n (itemsByType[item.itemType] ??= []).push(item.itemDict);\n bundleIds.add(item.bundleId);\n }\n\n // Honouring a TTL hint also means a hit stops renewing the lease, otherwise\n // a hinted bundle under steady traffic would outlive its hint.\n const refreshOnHit = !getEnvFlag('SYNAP_SDK_CACHE_HONOR_TTL_HINT');\n if (refreshOnHit) {\n const now = this.now();\n for (const id of bundleIds) {\n const entry = this.entries.get(id);\n if (entry) entry.storedAt = now;\n }\n }\n\n telemetry.hit = true;\n telemetry.exitReason = 'hit';\n telemetry.itemsPicked = top.map(({ score, item }) => ({\n bundle_id: item.bundleId, item_type: item.itemType,\n content_first_120: item.content.slice(0, PREVIEW_CHARS), bm25_score: round4(score),\n }));\n this.fire(telemetry);\n\n return {\n itemsByType,\n bundleIds: [...bundleIds],\n score: top[0]!.score,\n coverage,\n };\n }\n\n /**\n * Drop this entity's bundles after a write, so the cache stops serving a\n * pre-write view. Gated on the flag: this is the write-path hook.\n */\n invalidateEntity(entityId: string): number {\n if (!getEnvFlag('SYNAP_SDK_CACHE_INVALIDATE_ON_WRITE')) return 0;\n return this.dropEntity(entityId);\n }\n\n /**\n * Unconditionally drop this entity's bundles. Backs `cache.clear_user` and\n * `cache.clear_customer`, which are explicit user requests and so are not\n * gated on the invalidate-on-write flag.\n */\n dropEntity(entityId: string): number {\n let dropped = 0;\n for (const entry of [...this.entries.values()]) {\n // Never drop shared client-scope knowledge on one entity's behalf.\n if (entry.entityId === ANY_SCOPE) continue;\n if (entry.entityId === entityId) { this.dropBundle(entry.bundleId); dropped++; }\n }\n return dropped;\n }\n\n /**\n * A read-only diagnostic projection of the cache.\n *\n * Backs `client.anticipation_cache_snapshot()` and mirrors Python's shape\n * key for key, including snake_case keys: this output gets logged, diffed\n * and pasted into issues across both SDKs, so it is a wire format.\n *\n * Note the 140-character content previews. That is Python's literal, and it\n * is deliberately NOT the 120 of `telemetry.content_preview_chars` from the\n * contract, which caps lookup telemetry rather than this snapshot.\n */\n snapshot(): AnticipationCacheSnapshot {\n const SNAPSHOT_PREVIEW_CHARS = 140;\n const overallScope = new Map<string, number>();\n const itemsByBundle = new Map<string, ItemRecord[]>();\n for (const record of this.items) {\n const list = itemsByBundle.get(record.bundleId);\n if (list === undefined) itemsByBundle.set(record.bundleId, [record]);\n else list.push(record);\n }\n\n const bundles: SnapshotBundle[] = [];\n for (const [bundleId, entry] of this.entries) {\n const perBundle = new Map<string, number>();\n const itemPreviews: SnapshotItemPreview[] = [];\n for (const record of itemsByBundle.get(bundleId) ?? []) {\n // `scope` is absent on plenty of items; Python's Counter happily keys\n // on None, which JSON-serialises to null, so preserve the distinction\n // rather than coercing to a string.\n const scope = (record.itemDict['scope'] ?? null) as string | null;\n const key = scope === null ? '' : scope;\n overallScope.set(key, (overallScope.get(key) ?? 0) + 1);\n perBundle.set(key, (perBundle.get(key) ?? 0) + 1);\n itemPreviews.push({\n type: record.itemType,\n scope,\n content: record.content.slice(0, SNAPSHOT_PREVIEW_CHARS),\n });\n }\n let totalItems = 0;\n for (const n of perBundle.values()) totalItems += n;\n bundles.push({\n bundle_id: bundleId,\n entity_id: entry.entityId,\n conversation_id: entry.conversationId,\n bundle_type: entry.bundleType,\n search_queries: [...entry.searchQueries],\n scope_counts: Object.fromEntries(perBundle),\n total_items: totalItems,\n items: itemPreviews,\n });\n }\n\n return {\n total_entries: this.entries.size,\n total_item_records: this.items.length,\n scope_breakdown_overall: Object.fromEntries(overallScope),\n corpus_vocab_size: this.corpusVocab.size,\n corpus_vocab_sample: [...this.corpusVocab].sort().slice(0, 80),\n item_records: this.items.slice(0, 20).map((rec) => ({\n bundle_id: rec.bundleId,\n item_type: rec.itemType,\n tokens: rec.tokens.slice(0, 25),\n content: rec.content.slice(0, SNAPSHOT_PREVIEW_CHARS),\n })),\n bundles,\n };\n }\n\n /**\n * Drop every bundle belonging to one conversation.\n *\n * Backs the `compaction_update` signal on the Listen stream: a compaction\n * rewrites the conversation's summary, so any bundle built from the previous\n * state is stale and must not keep serving for the rest of its TTL.\n *\n * Unlike `dropEntity`, client-scope bundles are NOT spared: a bundle is only\n * dropped here if it is bound to this specific conversation, and a shared\n * client-scope bundle has no conversation id to match.\n */\n dropConversation(conversationId: string): number {\n if (!conversationId) return 0;\n let dropped = 0;\n for (const entry of [...this.entries.values()]) {\n if (entry.conversationId === conversationId) { this.dropBundle(entry.bundleId); dropped++; }\n }\n return dropped;\n }\n\n clear(): void {\n this.entries.clear();\n this.items = [];\n this.corpusVocab.clear();\n this.bm25 = null;\n this.bm25Dirty = true;\n }\n\n // ── internals ───────────────────────────────────────────────────────────────\n\n private miss(telemetry: LookupTelemetry, reason: ExitReason): null {\n telemetry.exitReason = reason;\n telemetry.hit = false;\n this.fire(telemetry);\n return null;\n }\n\n private fire(telemetry: LookupTelemetry): void {\n // Exception-safe by contract: a buggy hook must never break the SDK.\n try {\n this.onLookup?.(telemetry);\n } catch {\n /* ignored on purpose */\n }\n }\n\n private freshnessLookup(\n entityId: string | null,\n maxItems: number,\n telemetry: LookupTelemetry,\n ): LookupResult | null {\n const candidates = [...this.entries.values()]\n .filter((e) => entityId === null || e.entityId === entityId || e.entityId === ANY_SCOPE)\n .sort((a, b) => b.storedAt - a.storedAt);\n if (candidates.length === 0) return this.miss(telemetry, 'empty');\n\n const newest = candidates[0]!;\n const itemsByType: Record<string, BundleItem[]> = {};\n let n = 0;\n for (const item of this.items) {\n if (item.bundleId !== newest.bundleId) continue;\n if (n >= maxItems) break;\n (itemsByType[item.itemType] ??= []).push(item.itemDict);\n n++;\n }\n if (n === 0) return this.miss(telemetry, 'empty');\n\n telemetry.hit = true;\n telemetry.exitReason = 'hit';\n this.fire(telemetry);\n return { itemsByType, bundleIds: [newest.bundleId], score: 0, coverage: 1.0 };\n }\n\n /**\n * The widened scope-match set for a request.\n *\n * A narrower-scope request also matches broader-scope bundles for the same\n * customer or client. Falsy ids are dropped so an empty customer_id cannot\n * accidentally match bundles keyed at \"\".\n */\n private buildAcceptedScope(\n entityId: string | null, customerId: string | null, clientId: string | null,\n ): Set<string> {\n const accepted = new Set<string>([ANY_SCOPE]);\n if (entityId) accepted.add(entityId);\n if (customerId) accepted.add(customerId);\n if (clientId) accepted.add(clientId);\n return accepted;\n }\n\n private getValidBundleIds(accepted: Set<string>, conversationId: string | null): Set<string> {\n const valid = new Set<string>();\n for (const entry of this.entries.values()) {\n if (!accepted.has(entry.entityId)) continue;\n // A conversation-scoped bundle is only valid inside its conversation.\n if (entry.conversationId && conversationId && entry.conversationId !== conversationId) continue;\n valid.add(entry.bundleId);\n }\n return valid;\n }\n\n private effectiveTtl(entry: EntryRecord): number {\n if (!getEnvFlag('SYNAP_SDK_CACHE_HONOR_TTL_HINT')) return this.ttlSeconds;\n if (entry.ttlHintSeconds == null || entry.ttlHintSeconds <= 0) return this.ttlSeconds;\n // A hint may only shorten.\n return Math.min(this.ttlSeconds, entry.ttlHintSeconds);\n }\n\n private evictExpired(): void {\n const now = this.now();\n // Default cap is twice the sliding TTL; 0 disables. Without it a bundle\n // under steady traffic renews forever and can serve a retired value\n // indefinitely.\n const configuredMaxAge = getEnvFloat('SYNAP_SDK_CACHE_MAX_ENTRY_AGE');\n const maxAge = configuredMaxAge ?? this.ttlSeconds * 2;\n\n for (const entry of [...this.entries.values()]) {\n const idleExpired = now - entry.storedAt > this.effectiveTtl(entry);\n const ageExpired = maxAge > 0 && now - entry.createdAt > maxAge;\n if (idleExpired || ageExpired) this.dropBundle(entry.bundleId);\n }\n }\n\n private dropBundle(bundleId: string): void {\n if (!this.entries.delete(bundleId)) return;\n this.items = this.items.filter((i) => i.bundleId !== bundleId);\n // Vocabulary is rebuilt rather than decremented: a stem can be shared by\n // several bundles, so per-bundle subtraction would drop stems still in use.\n this.corpusVocab = new Set(this.items.flatMap((i) => i.tokens));\n this.bm25Dirty = true;\n }\n}\n\nfunction monotonicNow(): number {\n // performance.now() is monotonic and unaffected by wall-clock adjustments,\n // matching Python's time.monotonic(). Date.now() would let an NTP step\n // expire or resurrect every entry at once.\n return typeof performance !== 'undefined' && typeof performance.now === 'function'\n ? performance.now() / 1000\n : Date.now() / 1000;\n}\n\nfunction round4(n: number): number {\n return Number(n.toFixed(4));\n}\n"],"mappings":";;;;;;AAAA;AAAA,EACE,UAAY;AAAA,EACZ,SAAW;AAAA,EACX,eAAiB;AAAA,IACf,MAAQ;AAAA,IACR,UAAY;AAAA,IACZ,SAAW;AAAA,IACX,UAAY;AAAA,MACV;AAAA,QACE,SAAW;AAAA,QACX,OAAS;AAAA,QACT,MAAQ;AAAA,MACV;AAAA,MACA;AAAA,QACE,SAAW;AAAA,QACX,OAAS;AAAA,QACT,MAAQ;AAAA,MACV;AAAA,MACA;AAAA,QACE,SAAW;AAAA,QACX,OAAS;AAAA,QACT,MAAQ;AAAA,MACV;AAAA,MACA;AAAA,QACE,SAAW;AAAA,QACX,OAAS;AAAA,QACT,MAAQ;AAAA,MACV;AAAA,MACA;AAAA,QACE,SAAW;AAAA,QACX,OAAS;AAAA,QACT,MAAQ;AAAA,MACV;AAAA,MACA;AAAA,QACE,SAAW;AAAA,QACX,OAAS;AAAA,QACT,MAAQ;AAAA,MACV;AAAA,MACA;AAAA,QACE,SAAW;AAAA,QACX,OAAS;AAAA,QACT,MAAQ;AAAA,MACV;AAAA,MACA;AAAA,QACE,SAAW;AAAA,QACX,OAAS;AAAA,QACT,MAAQ;AAAA,MACV;AAAA,MACA;AAAA,QACE,SAAW;AAAA,QACX,OAAS;AAAA,QACT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nB;AAEA,SAAS,OAAO,GAAmB;AACjC,SAAO,OAAO,EAAE,QAAQ,CAAC,CAAC;AAC5B;","names":[]}
1
+ {"version":3,"sources":["../src/behavior/anticipation.json","../src/behavior/contract.ts","../src/cache/bm25.ts","../src/context/anticipation-cache.ts"],"sourcesContent":["{\n \"$comment\": \"SOURCE OF TRUTH for anticipation-cache behavior, shared by the Python and JS/TS SDKs. Do not duplicate these values into either SDK's source. See ../README.md. Regexes are restricted to the intersection of Python 're' and ECMAScript; both SDKs have a parity test.\",\n \"version\": 1,\n \"recall_bypass\": {\n \"note\": \"WS4 of the playground query-hygiene plan. A recall-shaped question never serves from the anticipation cache. Asymmetric cost is why: a stale false-hit makes the agent answer 'I don't see that' while the store holds the fact (the BZQR6J cross-session failure), whereas bypassing costs only cold-fetch latency on a turn where the user already expects a lookup. Stem coverage cannot gate this \\u2014 false hits were measured at coverage=1.00. Ties break toward INCLUDING a pattern.\",\n \"env_flag\": \"SYNAP_SDK_CACHE_RECALL_BYPASS\",\n \"default\": false,\n \"patterns\": [\n {\n \"pattern\": \"\\\\bremind me\\\\b\",\n \"flags\": \"i\",\n \"note\": \"Original set (WS4, playground query-hygiene plan).\"\n },\n {\n \"pattern\": \"\\\\bon file\\\\b\",\n \"flags\": \"i\",\n \"note\": \"Original set (WS4).\"\n },\n {\n \"pattern\": \"\\\\b(your|my|the) records\\\\b\",\n \"flags\": \"i\",\n \"note\": \"Original set (WS4).\"\n },\n {\n \"pattern\": \"\\\\bdo you (have|know|remember|recall|see)\\\\b\",\n \"flags\": \"i\",\n \"note\": \"Original set (WS4).\"\n },\n {\n \"pattern\": \"\\\\bwhat (do|did) (i|you) (say|tell|mention|have)\\\\b\",\n \"flags\": \"i\",\n \"note\": \"Original set (WS4).\"\n },\n {\n \"pattern\": \"\\\\bwhat('s| is) my\\\\b\",\n \"flags\": \"i\",\n \"note\": \"Original set (WS4).\"\n },\n {\n \"pattern\": \"\\\\bwhere (am i|do i live)\\\\b\",\n \"flags\": \"i\",\n \"note\": \"Original set (WS4).\"\n },\n {\n \"pattern\": \"\\\\bhow long have i\\\\b\",\n \"flags\": \"i\",\n \"note\": \"Original set (WS4).\"\n },\n {\n \"pattern\": \"\\\\bwhich of my\\\\b\",\n \"flags\": \"i\",\n \"note\": \"Original set (WS4).\"\n },\n {\n \"pattern\": \"\\\\bwhat .{0,40}\\\\b(again|earlier|last time|previously|yesterday)\\\\b\",\n \"flags\": \"i\",\n \"note\": \"Original set (WS4). 'again' alone is deliberately NOT a marker: 'book me a ride again' is a task query, not a recall query.\"\n },\n {\n \"pattern\": \"\\\\bwill you use to (contact|reach|notify)\\\\b\",\n \"flags\": \"i\",\n \"note\": \"Original set (WS4).\"\n },\n {\n \"pattern\": \"\\\\b(confirm|verify|double.?check)\\\\b.{0,40}\\\\bmy\\\\b\",\n \"flags\": \"i\",\n \"note\": \"2026-07-16 eval register issue #11: 'can you confirm my email address?' served a stale bundle. Also catches 'confirm my booking' \\u2014 an intentional over-match, costing one cloud fetch.\"\n },\n {\n \"pattern\": \"\\\\b(linked to|associated with|registered (to|on|with)) my\\\\b\",\n \"flags\": \"i\",\n \"note\": \"2026-07-16 eval register issue #11: 'what name is linked to my Uber account?' served a stale bundle.\"\n },\n {\n \"pattern\": \"\\\\b(best|preferred) way to (reach|contact|update|notify) me\\\\b\",\n \"flags\": \"i\",\n \"note\": \"2026-07-16 eval register issue #11: 'best way to contact me with updates' served a stale bundle.\"\n },\n {\n \"pattern\": \"\\\\bhow (do|will|can|should) you (reach|contact|notify) me\\\\b\",\n \"flags\": \"i\",\n \"note\": \"2026-07-16 eval register issue #11, sibling phrasing of the above.\"\n },\n {\n \"pattern\": \"\\\\bwhich .{0,40}\\\\b(are|will) you (going to )?(use|using)\\\\b\",\n \"flags\": \"i\",\n \"note\": \"2026-07-16 eval register issue #11: 'which email are you going to use?' served a stale bundle.\"\n },\n {\n \"pattern\": \"\\\\bon (my|the) account\\\\b\",\n \"flags\": \"i\",\n \"note\": \"2026-07-16 eval register issue #11.\"\n }\n ]\n },\n \"thresholds\": {\n \"bm25\": {\n \"value\": 1.5,\n \"note\": \"Nominal threshold. The value actually applied is derived per query: max(effective_floor, min(bm25, query_token_scale * len(query_tokens))). Short queries cannot reach the nominal score, so holding them to it would miss every time.\"\n },\n \"novel_term\": {\n \"value\": 0.45,\n \"note\": \"Fraction of query stems absent from the cached corpus that forces a miss.\"\n },\n \"min_corpus_for_novel_gate\": {\n \"value\": 200,\n \"note\": \"The novel-term gate is meaningless on a small corpus, where the ratio is dominated by ordinary English word forms. Measured: a fresh playground conversation reaches ~60 stems after the first push and would trip the 0.45 gate on essentially every second-turn query. 200 means the gate engages once a customer has ~3-4 typical bundles cached.\"\n },\n \"effective_floor\": {\n \"value\": 0.6,\n \"note\": \"Lower bound on the derived per-query threshold. Below this, BM25 stops discriminating.\"\n },\n \"query_token_scale\": {\n \"value\": 0.3,\n \"note\": \"Scales the threshold down for short queries: 0.3 points of score per query token.\"\n }\n },\n \"bm25\": {\n \"k1\": 1.5,\n \"b\": 0.75,\n \"idf_floor\": 0.5,\n \"min_token_len\": 2,\n \"min_stem_len\": 4,\n \"suffixes\": [\n \"ences\",\n \"ances\",\n \"ation\",\n \"tion\",\n \"sion\",\n \"ence\",\n \"ance\",\n \"ness\",\n \"ment\",\n \"able\",\n \"ible\",\n \"ical\",\n \"ally\",\n \"ies\",\n \"ive\",\n \"ful\",\n \"ous\",\n \"ing\",\n \"ary\",\n \"ly\",\n \"ed\",\n \"es\",\n \"s\"\n ],\n \"stop_words\": [\n \"a\",\n \"about\",\n \"after\",\n \"an\",\n \"and\",\n \"are\",\n \"at\",\n \"be\",\n \"been\",\n \"before\",\n \"being\",\n \"but\",\n \"by\",\n \"can\",\n \"could\",\n \"did\",\n \"do\",\n \"does\",\n \"for\",\n \"from\",\n \"had\",\n \"has\",\n \"have\",\n \"how\",\n \"if\",\n \"in\",\n \"into\",\n \"is\",\n \"it\",\n \"its\",\n \"may\",\n \"might\",\n \"no\",\n \"nor\",\n \"not\",\n \"of\",\n \"on\",\n \"or\",\n \"over\",\n \"should\",\n \"so\",\n \"than\",\n \"that\",\n \"the\",\n \"then\",\n \"these\",\n \"this\",\n \"those\",\n \"to\",\n \"was\",\n \"were\",\n \"what\",\n \"when\",\n \"where\",\n \"which\",\n \"who\",\n \"whom\",\n \"why\",\n \"will\",\n \"with\",\n \"would\"\n ],\n \"alias_token\": {\n \"pattern\": \"\\\\[\\\\[([A-Za-z][A-Za-z0-9_]*_[a-z0-9]{12})\\\\]\\\\]\",\n \"note\": \"An alias label as it appears in text: [[PERSON_PHONE_h2n7v5cx8m0d]]. Kept whole rather than split, because 'person' and 'phone' are boilerplate shared by every label of that field type and would make two different people's memories score alike. Mirrors synap/cloud/shared/tokenizer.py \\u2014 keep the two in step.\"\n },\n \"suffix_note\": \"Order matters: longest-first, because _stem returns on first match. Reordering this list silently changes every stem and therefore every BM25 score.\"\n },\n \"env_flags\": {\n \"$comment\": \"Read at CALL time, never at module load. Python does os.environ.get inside the function bodies; JS must do the same or late process.env mutation stops working and the flag looks broken. See gotcha G-S.\",\n \"SYNAP_SDK_CACHE_RECALL_BYPASS\": {\n \"default\": false,\n \"truthy\": [\n \"true\",\n \"1\",\n \"yes\"\n ]\n },\n \"SYNAP_SDK_CACHE_HONOR_TTL_HINT\": {\n \"default\": false,\n \"truthy\": [\n \"true\",\n \"1\",\n \"yes\"\n ],\n \"note\": \"A bundle's server ttl_hint_seconds may only SHORTEN the global TTL, never extend it.\"\n },\n \"SYNAP_SDK_CACHE_INVALIDATE_ON_WRITE\": {\n \"default\": false,\n \"truthy\": [\n \"true\",\n \"1\",\n \"yes\"\n ],\n \"note\": \"2026-07-16 eval register issue #8: the cloud invalidates its own Redis caches on ingest, but that stops at the process boundary.\"\n },\n \"SYNAP_SDK_CACHE_MAX_ENTRY_AGE\": {\n \"default\": null,\n \"note\": \"2026-07-16 eval register issue #6: stored_at is a sliding lease renewed on hit, so under steady traffic a pre-update snapshot never expired. Defaults to 2x the sliding TTL; 0 disables.\"\n },\n \"SYNAP_SDK_CACHE_COVERAGE_MIN\": {\n \"default\": null\n }\n },\n \"coverage_gate\": {\n \"note\": \"Fraction of the query's stems present in the picked items. A bundle can clear the BM25 threshold on one shared token ('account') while lacking the asked-for fact entirely: the false HIT behind the eval's 'forgot the name' failure. ALWAYS computed and reported; ENFORCED only when SYNAP_SDK_CACHE_COVERAGE_MIN is explicitly set, so default behavior is unchanged. When it does fire it must gate BEFORE any side effect, so a rejected lookup leaves cache state untouched.\",\n \"env_flag\": \"SYNAP_SDK_CACHE_COVERAGE_MIN\",\n \"default\": null,\n \"empty_query_coverage\": 1.0\n },\n \"telemetry\": {\n \"rejected_items_cap\": {\n \"value\": 20,\n \"note\": \"Rejected items reported per lookup, highest score first, so a large cache cannot bloat the payload.\"\n },\n \"content_preview_chars\": 120\n }\n}\n","/**\n * Loader for the shared SDK behavior contract.\n *\n * The values here are tuned against measured eval failures and are shared,\n * byte-identical, with the Python SDK. They live in data rather than code\n * specifically so the two SDKs cannot drift. See\n * `synap/sdk/CONTRACT/README.md`.\n *\n * `anticipation.json` is vendored into `src/` by\n * `synap/sdk/scripts/sync-behavior.sh` and imported (not read from disk) so\n * that the bundler inlines it. Reading it with `node:fs` at runtime would work\n * in Node and break in every bundled target: Edge, Workers, and anything under\n * webpack/turbopack, where `dist/` is rewritten and relative paths do not\n * survive. It is the same failure mode as `@grpc/proto-loader` reading a\n * `.proto` off disk (gotcha G-P).\n */\n\nimport contractJson from './anticipation.json' with { type: 'json' };\n\nexport interface RecallPattern {\n pattern: string;\n flags: string;\n note: string;\n}\n\nexport interface BehaviorContract {\n version: number;\n recall_bypass: {\n note: string;\n env_flag: string;\n default: boolean;\n patterns: RecallPattern[];\n };\n thresholds: {\n bm25: { value: number; note: string };\n novel_term: { value: number; note: string };\n min_corpus_for_novel_gate: { value: number; note: string };\n effective_floor: { value: number; note: string };\n query_token_scale: { value: number; note: string };\n };\n coverage_gate: {\n note: string;\n env_flag: string;\n default: number | null;\n empty_query_coverage: number;\n };\n telemetry: {\n rejected_items_cap: { value: number; note: string };\n content_preview_chars: number;\n };\n bm25: {\n k1: number;\n b: number;\n idf_floor: number;\n min_token_len: number;\n min_stem_len: number;\n suffixes: string[];\n stop_words: string[];\n alias_token: { pattern: string; note: string };\n };\n}\n\nexport const CONTRACT = contractJson as unknown as BehaviorContract;\n\n/** ECMAScript flags we accept. Anything else is invalid in Python too. */\nconst ALLOWED_FLAGS = new Set(['i', 'm', 's']);\n\nfunction compile(pattern: string, flags: string): RegExp {\n for (const ch of flags) {\n if (!ALLOWED_FLAGS.has(ch)) {\n throw new Error(\n `Unsupported regex flag '${ch}' in behavior contract. Flags must be ` +\n `valid in both Python and ECMAScript.`,\n );\n }\n }\n return new RegExp(pattern, flags);\n}\n\n/**\n * Compiled recall-bypass patterns, in contract order.\n *\n * Deliberately NOT using the `g` flag: a global RegExp carries `lastIndex`\n * between calls, so a shared instance would match on one query and then miss\n * on the next. That failure is intermittent and traffic-dependent, which is\n * the worst kind to debug.\n */\nexport const RECALL_PATTERNS: readonly RegExp[] = CONTRACT.recall_bypass.patterns.map((p) =>\n compile(p.pattern, p.flags ?? ''),\n);\n\nexport const THRESHOLDS = {\n bm25: CONTRACT.thresholds.bm25.value,\n novelTerm: CONTRACT.thresholds.novel_term.value,\n minCorpusForNovelGate: CONTRACT.thresholds.min_corpus_for_novel_gate.value,\n /** Lower bound on the derived per-query threshold. */\n effectiveFloor: CONTRACT.thresholds.effective_floor.value,\n /** Points of score allowed per query token when deriving the threshold. */\n queryTokenScale: CONTRACT.thresholds.query_token_scale.value,\n} as const;\n\nexport const BM25_PARAMS = CONTRACT.bm25;\nexport const STOP_WORDS: ReadonlySet<string> = new Set(CONTRACT.bm25.stop_words);\n// Order is load-bearing: stem() returns on first match, so this must stay\n// longest-first exactly as the contract lists it.\nexport const SUFFIXES: readonly string[] = CONTRACT.bm25.suffixes;\nexport const ALIAS_TOKEN_SOURCE = CONTRACT.bm25.alias_token.pattern;\n\n/** True when any query string looks like an explicit memory-recall ask. */\nexport function isRecallQuery(searchQuery: readonly (string | null | undefined)[] | null | undefined): boolean {\n for (const q of searchQuery ?? []) {\n if (!q) continue;\n for (const pattern of RECALL_PATTERNS) {\n if (pattern.test(q)) return true;\n }\n }\n return false;\n}\n","/**\n * BM25 scorer for the anticipation cache.\n *\n * A faithful port of `maximem_synap/cache/bm25.py`. Every tuned value comes\n * from the shared behavior contract, so the two implementations cannot drift\n * on parameters. What they *can* still drift on is arithmetic, which is what\n * the shared conformance corpus is for.\n */\n\nimport { BM25_PARAMS, STOP_WORDS, SUFFIXES, ALIAS_TOKEN_SOURCE } from '../behavior/contract.js';\n\nconst MIN_STEM_LEN = BM25_PARAMS.min_stem_len;\nconst MIN_TOKEN_LEN = BM25_PARAMS.min_token_len;\n\nexport function stem(word: string): string {\n // Order is load-bearing: longest suffix first, return on first match.\n for (const suffix of SUFFIXES) {\n if (word.endsWith(suffix) && word.length - suffix.length >= MIN_STEM_LEN) {\n return word.slice(0, word.length - suffix.length);\n }\n }\n return word;\n}\n\n/**\n * An alias label, as it appears in text: `[[PERSON_PHONE_h2n7v5cx8m0d]]`.\n *\n * Kept whole rather than split into `person`, `phone` and the suffix, because\n * the first two are boilerplate shared by every label of that field type and\n * would make two different people's memories score alike.\n *\n * Mirrors `synap/cloud/shared/tokenizer.py`. Keep the two in step.\n */\nfunction aliasTokenRe(): RegExp {\n // Constructed per call because `g` regexes carry `lastIndex`, and this one\n // is used with replace(). A module-level shared instance would produce\n // different results on alternating calls.\n return new RegExp(ALIAS_TOKEN_SOURCE, 'g');\n}\n\nconst WORD_RE = /[a-z0-9]+/g;\n\n/** Tokenize, lowercase, remove stop words, and stem. Alias labels survive whole. */\nexport function tokenize(text: string | null | undefined): string[] {\n if (!text) return [];\n\n const labels: string[] = [];\n const remainder = text.replace(aliasTokenRe(), (_match, captured: string) => {\n labels.push(captured.toLowerCase());\n return ' ';\n });\n\n const words = remainder.toLowerCase().match(WORD_RE) ?? [];\n const out = labels.slice();\n for (const w of words) {\n if (w.length >= MIN_TOKEN_LEN && !STOP_WORDS.has(w)) out.push(stem(w));\n }\n return out;\n}\n\n/** Okapi BM25 scorer over a small in-memory corpus. */\nexport class BM25 {\n static readonly IDF_FLOOR = BM25_PARAMS.idf_floor;\n\n readonly k1: number;\n readonly b: number;\n readonly corpus: readonly (readonly string[])[];\n readonly docCount: number;\n readonly avgdl: number;\n readonly docLens: readonly number[];\n readonly idf: ReadonlyMap<string, number>;\n\n constructor(\n corpus: readonly (readonly string[])[],\n k1: number = BM25_PARAMS.k1,\n b: number = BM25_PARAMS.b,\n ) {\n this.k1 = k1;\n this.b = b;\n this.corpus = corpus;\n this.docCount = corpus.length;\n this.docLens = corpus.map((doc) => doc.length);\n // Python falls back to 1.0 rather than dividing by zero on an empty corpus.\n this.avgdl = this.docCount\n ? this.docLens.reduce((a, n) => a + n, 0) / this.docCount\n : 1.0;\n\n const idf = new Map<string, number>();\n const allTerms = new Set<string>();\n for (const doc of corpus) for (const t of doc) allTerms.add(t);\n for (const term of allTerms) {\n let df = 0;\n for (const doc of corpus) if (doc.includes(term)) df++;\n const raw = Math.log((this.docCount - df + 0.5) / (df + 0.5) + 1.0);\n idf.set(term, Math.max(raw, BM25.IDF_FLOOR));\n }\n this.idf = idf;\n }\n\n score(queryTokens: readonly string[], docIdx: number): number {\n const doc = this.corpus[docIdx];\n if (doc === undefined) return 0;\n const dl = this.docLens[docIdx] ?? 0;\n\n const tfMap = new Map<string, number>();\n for (const t of doc) tfMap.set(t, (tfMap.get(t) ?? 0) + 1);\n\n let s = 0;\n for (const term of queryTokens) {\n const tf = tfMap.get(term);\n if (tf === undefined) continue;\n const idf = this.idf.get(term) ?? BM25.IDF_FLOOR;\n const numerator = tf * (this.k1 + 1);\n const denominator = tf + this.k1 * (1 - this.b + (this.b * dl) / this.avgdl);\n s += (idf * numerator) / denominator;\n }\n return s;\n }\n\n scores(queryTokens: readonly string[]): number[] {\n return this.corpus.map((_, i) => this.score(queryTokens, i));\n }\n}\n","/**\n * In-memory TTL cache for context bundles pushed over gRPC.\n *\n * Port of `maximem_synap/cache/anticipation_cache.py`.\n *\n * ## Why this is a faithful port and not a simplification\n *\n * `@maximem/synap-vercel-adk` already contains a native TS anticipation cache,\n * and it is a simplification: a hardcoded 30-minute TTL, a plain BM25 threshold\n * with no per-query derivation, and none of the gates below. Shipping that as\n * the SDK's cache would mean two retrieval behaviors under one brand, which is\n * gotcha G-C. Every gate here exists because a specific eval failed without it:\n *\n * - **Recall bypass** runs BEFORE scoring. The measured false hit scored 2.86\n * at coverage 1.00, so no score-side gate could ever have caught it.\n * - **The novel-term gate** is suppressed below a 200-stem corpus, because at\n * cold start ordinary English trips it on nearly every query.\n * - **The per-query threshold** scales down for short queries, which otherwise\n * cannot reach the nominal score at all.\n * - **The coverage gate** catches a bundle that clears BM25 on one shared\n * token (\"account\") while lacking the asked-for fact.\n *\n * All thresholds come from the shared behavior contract.\n */\n\nimport { BM25, tokenize } from '../cache/bm25.js';\nimport { CONTRACT, THRESHOLDS, isRecallQuery } from '../behavior/contract.js';\nimport { getEnvFlag, getEnvFloat } from '../util/env.js';\n\nconst EFFECTIVE_FLOOR = CONTRACT.thresholds.effective_floor.value;\nconst QUERY_TOKEN_SCALE = CONTRACT.thresholds.query_token_scale.value;\nconst REJECTED_CAP = CONTRACT.telemetry.rejected_items_cap.value;\nconst PREVIEW_CHARS = CONTRACT.telemetry.content_preview_chars;\n\n/** Sentinel scope that matches any requester. */\nexport const ANY_SCOPE = '_any';\n\nexport interface BundleItem {\n item_id?: string;\n content?: string;\n [key: string]: unknown;\n}\n\nexport interface ContextBundle {\n bundleId: string;\n entityId?: string | null;\n conversationId?: string | null;\n itemsByType: Record<string, BundleItem[]>;\n /** Server hint; may only SHORTEN the global TTL, never extend it. */\n ttlHintSeconds?: number | null;\n /** Which anticipation pattern produced this bundle. Diagnostics only. */\n bundleType?: string | null;\n /** The queries the server anticipated. Diagnostics only. */\n searchQueries?: readonly string[] | null;\n}\n\ninterface ItemRecord {\n bundleId: string;\n itemType: string;\n content: string;\n tokens: string[];\n itemDict: BundleItem;\n}\n\ninterface EntryRecord {\n bundleId: string;\n entityId: string;\n conversationId: string | null;\n bundleType: string | null;\n searchQueries: string[];\n /** Sliding lease, refreshed on hit unless TTL hints are honoured. */\n storedAt: number;\n /** Absolute creation time; the max-entry-age cap uses this, not the lease. */\n createdAt: number;\n ttlHintSeconds: number | null;\n}\n\nexport interface LookupResult {\n itemsByType: Record<string, BundleItem[]>;\n bundleIds: string[];\n score: number;\n coverage: number;\n}\n\nexport interface LookupParams {\n searchQuery?: readonly string[] | null;\n entityId?: string | null;\n customerId?: string | null;\n clientId?: string | null;\n conversationId?: string | null;\n maxItems?: number;\n}\n\nexport type ExitReason =\n | 'empty'\n | 'recall_bypass'\n | 'no_query_tokens'\n | 'novel_term_gate'\n | 'empty_corpus'\n | 'no_items_above_threshold'\n | 'coverage_gate'\n | 'hit';\n\nexport interface LookupTelemetry {\n searchQuery: string[];\n entityId: string | null;\n customerId: string | null;\n clientId: string | null;\n conversationId: string | null;\n scopeFilterAccepted: string[];\n novelTermRatio: number | null;\n bm25Threshold: number | null;\n bm25QueryTokens: string[];\n itemsPicked: unknown[];\n itemsRejected: unknown[];\n coverage: number | null;\n hit: boolean;\n exitReason: ExitReason;\n}\n\nexport interface SnapshotItemPreview {\n type: string;\n scope: string | null;\n content: string;\n}\n\nexport interface SnapshotItemRecord {\n bundle_id: string;\n item_type: string;\n tokens: string[];\n content: string;\n}\n\nexport interface SnapshotBundle {\n bundle_id: string;\n entity_id: string;\n conversation_id: string | null;\n bundle_type: string | null;\n search_queries: string[];\n scope_counts: Record<string, number>;\n total_items: number;\n items: SnapshotItemPreview[];\n}\n\nexport interface AnticipationCacheSnapshot {\n total_entries: number;\n total_item_records: number;\n scope_breakdown_overall: Record<string, number>;\n corpus_vocab_size: number;\n corpus_vocab_sample: string[];\n item_records: SnapshotItemRecord[];\n bundles: SnapshotBundle[];\n}\n\nexport interface AnticipationCacheOptions {\n ttlSeconds?: number;\n maxBundles?: number;\n /** Injected in tests. Defaults to a monotonic clock. */\n now?: () => number;\n onLookup?: (telemetry: LookupTelemetry) => void;\n}\n\nconst DEFAULT_TTL_SECONDS = 1800;\nconst DEFAULT_MAX_BUNDLES = 50;\n\nexport class AnticipationCache {\n private readonly ttlSeconds: number;\n private readonly maxBundles: number;\n private readonly now: () => number;\n private readonly onLookup: ((t: LookupTelemetry) => void) | undefined;\n\n private entries = new Map<string, EntryRecord>();\n private items: ItemRecord[] = [];\n private corpusVocab = new Set<string>();\n private bm25: BM25 | null = null;\n private bm25Dirty = true;\n\n constructor(options: AnticipationCacheOptions = {}) {\n this.ttlSeconds = options.ttlSeconds ?? DEFAULT_TTL_SECONDS;\n this.maxBundles = options.maxBundles ?? DEFAULT_MAX_BUNDLES;\n this.now = options.now ?? monotonicNow;\n this.onLookup = options.onLookup;\n }\n\n get size(): number {\n return this.entries.size;\n }\n\n get itemCount(): number {\n return this.items.length;\n }\n\n store(bundle: ContextBundle): void {\n if (!bundle.bundleId) return;\n this.evictExpired();\n\n // Client-scope knowledge (FAQs, policies) arrives with no entity, and the\n // sentinel makes it visible to every requester.\n const entityId = bundle.entityId || ANY_SCOPE;\n\n if (this.entries.has(bundle.bundleId)) this.dropBundle(bundle.bundleId);\n\n const now = this.now();\n this.entries.set(bundle.bundleId, {\n bundleId: bundle.bundleId,\n entityId,\n conversationId: bundle.conversationId ?? null,\n bundleType: bundle.bundleType ?? null,\n searchQueries: [...(bundle.searchQueries ?? [])],\n storedAt: now,\n createdAt: now,\n ttlHintSeconds: bundle.ttlHintSeconds ?? null,\n });\n\n for (const [itemType, list] of Object.entries(bundle.itemsByType ?? {})) {\n for (const item of list ?? []) {\n const content = String(item.content ?? '');\n const tokens = tokenize(content);\n this.items.push({ bundleId: bundle.bundleId, itemType, content, tokens, itemDict: item });\n for (const t of tokens) this.corpusVocab.add(t);\n }\n }\n this.bm25Dirty = true;\n\n // LRU by lease age.\n while (this.entries.size > this.maxBundles) {\n let oldest: EntryRecord | null = null;\n for (const e of this.entries.values()) {\n if (oldest === null || e.storedAt < oldest.storedAt) oldest = e;\n }\n if (oldest === null) break;\n this.dropBundle(oldest.bundleId);\n }\n }\n\n lookup(params: LookupParams): LookupResult | null {\n const {\n searchQuery = null, entityId = null, customerId = null,\n clientId = null, conversationId = null, maxItems = 10,\n } = params;\n\n this.evictExpired();\n\n const accepted = this.buildAcceptedScope(entityId, customerId, clientId);\n const telemetry: LookupTelemetry = {\n searchQuery: (searchQuery ?? []).filter((q): q is string => Boolean(q)),\n entityId, customerId, clientId, conversationId,\n scopeFilterAccepted: [...accepted].sort(),\n novelTermRatio: null, bm25Threshold: null, bm25QueryTokens: [],\n itemsPicked: [], itemsRejected: [], coverage: null,\n hit: false, exitReason: 'empty',\n };\n\n if (this.entries.size === 0 || this.items.length === 0) {\n return this.miss(telemetry, 'empty');\n }\n\n const hasQuery = (searchQuery ?? []).some((q) => q && q.trim() !== '');\n if (!hasQuery) {\n return this.freshnessLookup(entityId, maxItems, telemetry);\n }\n\n // Recall bypass fires BEFORE scoring: a stale false-hit on a recall-shaped\n // question makes the agent deny a fact the store holds, and the measured\n // failure cleared every score-side gate.\n if (getEnvFlag(CONTRACT.recall_bypass.env_flag) && isRecallQuery(searchQuery)) {\n return this.miss(telemetry, 'recall_bypass');\n }\n\n const queryTokens = (searchQuery ?? []).flatMap((q) => tokenize(q));\n telemetry.bm25QueryTokens = queryTokens;\n if (queryTokens.length === 0) {\n return this.miss(telemetry, 'no_query_tokens');\n }\n\n const uniqueStems = new Set(queryTokens);\n let novel = 0;\n for (const s of uniqueStems) if (!this.corpusVocab.has(s)) novel++;\n const novelRatio = uniqueStems.size ? novel / uniqueStems.size : 0;\n telemetry.novelTermRatio = round4(novelRatio);\n\n // Only meaningful once the corpus has real vocabulary. Below the floor the\n // ratio is dominated by ordinary English and would miss on nearly anything.\n if (\n this.corpusVocab.size >= THRESHOLDS.minCorpusForNovelGate &&\n novelRatio >= THRESHOLDS.novelTerm\n ) {\n return this.miss(telemetry, 'novel_term_gate');\n }\n\n if (this.bm25Dirty || this.bm25 === null) {\n if (this.items.length === 0) return this.miss(telemetry, 'empty_corpus');\n this.bm25 = new BM25(this.items.map((i) => i.tokens));\n this.bm25Dirty = false;\n }\n\n const scores = this.bm25.scores(queryTokens);\n const validBundles = this.getValidBundleIds(accepted, conversationId);\n\n const effectiveThreshold = Math.max(\n EFFECTIVE_FLOOR,\n Math.min(THRESHOLDS.bm25, QUERY_TOKEN_SCALE * queryTokens.length),\n );\n telemetry.bm25Threshold = round4(effectiveThreshold);\n\n const picked: { score: number; item: ItemRecord }[] = [];\n const rejected: { score: number; payload: Record<string, unknown> }[] = [];\n\n for (let idx = 0; idx < scores.length; idx++) {\n const item = this.items[idx]!;\n const score = scores[idx]!;\n const reject = (reason: string) =>\n rejected.push({\n score,\n payload: {\n item_index: idx, bundle_id: item.bundleId, item_type: item.itemType,\n content_first_120: item.content.slice(0, PREVIEW_CHARS),\n bm25_score: round4(score), reason,\n },\n });\n if (score < effectiveThreshold) { reject('below_threshold'); continue; }\n if (!validBundles.has(item.bundleId)) { reject('scope_filter_excluded'); continue; }\n picked.push({ score, item });\n }\n\n rejected.sort((a, b) => b.score - a.score);\n telemetry.itemsRejected = rejected.slice(0, REJECTED_CAP).map((r) => r.payload);\n\n if (picked.length === 0) {\n return this.miss(telemetry, 'no_items_above_threshold');\n }\n\n picked.sort((a, b) => b.score - a.score);\n const top = picked.slice(0, maxItems);\n\n const pickedStems = new Set<string>();\n for (const { item } of top) for (const t of item.tokens) pickedStems.add(t);\n let overlap = 0;\n for (const s of uniqueStems) if (pickedStems.has(s)) overlap++;\n const coverage = uniqueStems.size ? overlap / uniqueStems.size : 1.0;\n telemetry.coverage = round4(coverage);\n\n // Observe-only unless explicitly configured. A malformed setting stays\n // observe-only rather than failing closed on every lookup.\n const coverageMin = getEnvFloat('SYNAP_SDK_CACHE_COVERAGE_MIN');\n if (coverageMin !== null && coverage < coverageMin) {\n // Gate BEFORE any side effect, so a rejected lookup leaves cache state\n // untouched and does not refresh a lease.\n return this.miss(telemetry, 'coverage_gate');\n }\n\n const itemsByType: Record<string, BundleItem[]> = {};\n const bundleIds = new Set<string>();\n for (const { item } of top) {\n (itemsByType[item.itemType] ??= []).push(item.itemDict);\n bundleIds.add(item.bundleId);\n }\n\n // Honouring a TTL hint also means a hit stops renewing the lease, otherwise\n // a hinted bundle under steady traffic would outlive its hint.\n const refreshOnHit = !getEnvFlag('SYNAP_SDK_CACHE_HONOR_TTL_HINT');\n if (refreshOnHit) {\n const now = this.now();\n for (const id of bundleIds) {\n const entry = this.entries.get(id);\n if (entry) entry.storedAt = now;\n }\n }\n\n telemetry.hit = true;\n telemetry.exitReason = 'hit';\n telemetry.itemsPicked = top.map(({ score, item }) => ({\n bundle_id: item.bundleId, item_type: item.itemType,\n content_first_120: item.content.slice(0, PREVIEW_CHARS), bm25_score: round4(score),\n }));\n this.fire(telemetry);\n\n return {\n itemsByType,\n bundleIds: [...bundleIds],\n score: top[0]!.score,\n coverage,\n };\n }\n\n /**\n * Drop this entity's bundles after a write, so the cache stops serving a\n * pre-write view. Gated on the flag: this is the write-path hook.\n */\n invalidateEntity(entityId: string): number {\n if (!getEnvFlag('SYNAP_SDK_CACHE_INVALIDATE_ON_WRITE')) return 0;\n return this.dropEntity(entityId);\n }\n\n /**\n * Unconditionally drop this entity's bundles. Backs `cache.clear_user` and\n * `cache.clear_customer`, which are explicit user requests and so are not\n * gated on the invalidate-on-write flag.\n */\n dropEntity(entityId: string): number {\n let dropped = 0;\n for (const entry of [...this.entries.values()]) {\n // Never drop shared client-scope knowledge on one entity's behalf.\n if (entry.entityId === ANY_SCOPE) continue;\n if (entry.entityId === entityId) { this.dropBundle(entry.bundleId); dropped++; }\n }\n return dropped;\n }\n\n /**\n * A read-only diagnostic projection of the cache.\n *\n * Backs `client.anticipation_cache_snapshot()` and mirrors Python's shape\n * key for key, including snake_case keys: this output gets logged, diffed\n * and pasted into issues across both SDKs, so it is a wire format.\n *\n * Note the 140-character content previews. That is Python's literal, and it\n * is deliberately NOT the 120 of `telemetry.content_preview_chars` from the\n * contract, which caps lookup telemetry rather than this snapshot.\n */\n snapshot(): AnticipationCacheSnapshot {\n const SNAPSHOT_PREVIEW_CHARS = 140;\n const overallScope = new Map<string, number>();\n const itemsByBundle = new Map<string, ItemRecord[]>();\n for (const record of this.items) {\n const list = itemsByBundle.get(record.bundleId);\n if (list === undefined) itemsByBundle.set(record.bundleId, [record]);\n else list.push(record);\n }\n\n const bundles: SnapshotBundle[] = [];\n for (const [bundleId, entry] of this.entries) {\n const perBundle = new Map<string, number>();\n const itemPreviews: SnapshotItemPreview[] = [];\n for (const record of itemsByBundle.get(bundleId) ?? []) {\n // `scope` is absent on plenty of items; Python's Counter happily keys\n // on None, which JSON-serialises to null, so preserve the distinction\n // rather than coercing to a string.\n const scope = (record.itemDict['scope'] ?? null) as string | null;\n const key = scope === null ? '' : scope;\n overallScope.set(key, (overallScope.get(key) ?? 0) + 1);\n perBundle.set(key, (perBundle.get(key) ?? 0) + 1);\n itemPreviews.push({\n type: record.itemType,\n scope,\n content: record.content.slice(0, SNAPSHOT_PREVIEW_CHARS),\n });\n }\n let totalItems = 0;\n for (const n of perBundle.values()) totalItems += n;\n bundles.push({\n bundle_id: bundleId,\n entity_id: entry.entityId,\n conversation_id: entry.conversationId,\n bundle_type: entry.bundleType,\n search_queries: [...entry.searchQueries],\n scope_counts: Object.fromEntries(perBundle),\n total_items: totalItems,\n items: itemPreviews,\n });\n }\n\n return {\n total_entries: this.entries.size,\n total_item_records: this.items.length,\n scope_breakdown_overall: Object.fromEntries(overallScope),\n corpus_vocab_size: this.corpusVocab.size,\n corpus_vocab_sample: [...this.corpusVocab].sort().slice(0, 80),\n item_records: this.items.slice(0, 20).map((rec) => ({\n bundle_id: rec.bundleId,\n item_type: rec.itemType,\n tokens: rec.tokens.slice(0, 25),\n content: rec.content.slice(0, SNAPSHOT_PREVIEW_CHARS),\n })),\n bundles,\n };\n }\n\n /**\n * The freshest `user_summary` bundle for this entity, or null.\n *\n * `entityId` is REQUIRED, and a missing one refuses the lookup rather than\n * falling back to the freshest summary across all users. Python hardened this\n * for exactly that reason: the permissive version could splice user A's\n * summary into user B's response on the conversation-scope path.\n */\n lookupUserSummary(entityId: string | null | undefined): Record<string, unknown> | null {\n if (!entityId) return null;\n this.evictExpired();\n\n let freshest: EntryRecord | null = null;\n for (const entry of this.entries.values()) {\n if (entry.bundleType !== 'user_summary') continue;\n // ANY_SCOPE covers client-shared summaries, which are safe for everyone.\n if (entry.entityId !== entityId && entry.entityId !== ANY_SCOPE) continue;\n if (freshest === null || entry.storedAt > freshest.storedAt) freshest = entry;\n }\n if (freshest === null) return null;\n\n // Serving refreshes the sliding lease, unless the server's TTL hint is\n // being honoured, in which case the hint owns expiry.\n if (!getEnvFlag('SYNAP_SDK_CACHE_HONOR_TTL_HINT')) {\n freshest.storedAt = this.now();\n }\n return this.#bundleFor(freshest.bundleId);\n }\n\n /** Rebuild a bundle's items_by_type from the flat item records. */\n #bundleFor(bundleId: string): Record<string, unknown> {\n const itemsByType: Record<string, BundleItem[]> = {};\n for (const record of this.items) {\n if (record.bundleId !== bundleId) continue;\n (itemsByType[record.itemType] ??= []).push(record.itemDict);\n }\n return { bundle_id: bundleId, items_by_type: itemsByType };\n }\n\n /**\n * Drop every bundle belonging to one conversation.\n *\n * Backs the `compaction_update` signal on the Listen stream: a compaction\n * rewrites the conversation's summary, so any bundle built from the previous\n * state is stale and must not keep serving for the rest of its TTL.\n *\n * Unlike `dropEntity`, client-scope bundles are NOT spared: a bundle is only\n * dropped here if it is bound to this specific conversation, and a shared\n * client-scope bundle has no conversation id to match.\n */\n dropConversation(conversationId: string): number {\n if (!conversationId) return 0;\n let dropped = 0;\n for (const entry of [...this.entries.values()]) {\n if (entry.conversationId === conversationId) { this.dropBundle(entry.bundleId); dropped++; }\n }\n return dropped;\n }\n\n clear(): void {\n this.entries.clear();\n this.items = [];\n this.corpusVocab.clear();\n this.bm25 = null;\n this.bm25Dirty = true;\n }\n\n // ── internals ───────────────────────────────────────────────────────────────\n\n private miss(telemetry: LookupTelemetry, reason: ExitReason): null {\n telemetry.exitReason = reason;\n telemetry.hit = false;\n this.fire(telemetry);\n return null;\n }\n\n private fire(telemetry: LookupTelemetry): void {\n // Exception-safe by contract: a buggy hook must never break the SDK.\n try {\n this.onLookup?.(telemetry);\n } catch {\n /* ignored on purpose */\n }\n }\n\n private freshnessLookup(\n entityId: string | null,\n maxItems: number,\n telemetry: LookupTelemetry,\n ): LookupResult | null {\n const candidates = [...this.entries.values()]\n .filter((e) => entityId === null || e.entityId === entityId || e.entityId === ANY_SCOPE)\n .sort((a, b) => b.storedAt - a.storedAt);\n if (candidates.length === 0) return this.miss(telemetry, 'empty');\n\n const newest = candidates[0]!;\n const itemsByType: Record<string, BundleItem[]> = {};\n let n = 0;\n for (const item of this.items) {\n if (item.bundleId !== newest.bundleId) continue;\n if (n >= maxItems) break;\n (itemsByType[item.itemType] ??= []).push(item.itemDict);\n n++;\n }\n if (n === 0) return this.miss(telemetry, 'empty');\n\n telemetry.hit = true;\n telemetry.exitReason = 'hit';\n this.fire(telemetry);\n return { itemsByType, bundleIds: [newest.bundleId], score: 0, coverage: 1.0 };\n }\n\n /**\n * The widened scope-match set for a request.\n *\n * A narrower-scope request also matches broader-scope bundles for the same\n * customer or client. Falsy ids are dropped so an empty customer_id cannot\n * accidentally match bundles keyed at \"\".\n */\n private buildAcceptedScope(\n entityId: string | null, customerId: string | null, clientId: string | null,\n ): Set<string> {\n const accepted = new Set<string>([ANY_SCOPE]);\n if (entityId) accepted.add(entityId);\n if (customerId) accepted.add(customerId);\n if (clientId) accepted.add(clientId);\n return accepted;\n }\n\n private getValidBundleIds(accepted: Set<string>, conversationId: string | null): Set<string> {\n const valid = new Set<string>();\n for (const entry of this.entries.values()) {\n if (!accepted.has(entry.entityId)) continue;\n // A conversation-scoped bundle is only valid inside its conversation.\n if (entry.conversationId && conversationId && entry.conversationId !== conversationId) continue;\n valid.add(entry.bundleId);\n }\n return valid;\n }\n\n private effectiveTtl(entry: EntryRecord): number {\n if (!getEnvFlag('SYNAP_SDK_CACHE_HONOR_TTL_HINT')) return this.ttlSeconds;\n if (entry.ttlHintSeconds == null || entry.ttlHintSeconds <= 0) return this.ttlSeconds;\n // A hint may only shorten.\n return Math.min(this.ttlSeconds, entry.ttlHintSeconds);\n }\n\n private evictExpired(): void {\n const now = this.now();\n // Default cap is twice the sliding TTL; 0 disables. Without it a bundle\n // under steady traffic renews forever and can serve a retired value\n // indefinitely.\n const configuredMaxAge = getEnvFloat('SYNAP_SDK_CACHE_MAX_ENTRY_AGE');\n const maxAge = configuredMaxAge ?? this.ttlSeconds * 2;\n\n for (const entry of [...this.entries.values()]) {\n const idleExpired = now - entry.storedAt > this.effectiveTtl(entry);\n const ageExpired = maxAge > 0 && now - entry.createdAt > maxAge;\n if (idleExpired || ageExpired) this.dropBundle(entry.bundleId);\n }\n }\n\n private dropBundle(bundleId: string): void {\n if (!this.entries.delete(bundleId)) return;\n this.items = this.items.filter((i) => i.bundleId !== bundleId);\n // Vocabulary is rebuilt rather than decremented: a stem can be shared by\n // several bundles, so per-bundle subtraction would drop stems still in use.\n this.corpusVocab = new Set(this.items.flatMap((i) => i.tokens));\n this.bm25Dirty = true;\n }\n}\n\nfunction monotonicNow(): number {\n // performance.now() is monotonic and unaffected by wall-clock adjustments,\n // matching Python's time.monotonic(). Date.now() would let an NTP step\n // expire or resurrect every entry at once.\n return typeof performance !== 'undefined' && typeof performance.now === 'function'\n ? performance.now() / 1000\n : Date.now() / 1000;\n}\n\nfunction round4(n: number): number {\n return Number(n.toFixed(4));\n}\n"],"mappings":";;;;;;AAAA;AAAA,EACE,UAAY;AAAA,EACZ,SAAW;AAAA,EACX,eAAiB;AAAA,IACf,MAAQ;AAAA,IACR,UAAY;AAAA,IACZ,SAAW;AAAA,IACX,UAAY;AAAA,MACV;A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K,YAAY;AAAA,EACnB;AACF;AAEA,SAAS,eAAuB;AAI9B,SAAO,OAAO,gBAAgB,eAAe,OAAO,YAAY,QAAQ,aACpE,YAAY,IAAI,IAAI,MACpB,KAAK,IAAI,IAAI;AACnB;AAEA,SAAS,OAAO,GAAmB;AACjC,SAAO,OAAO,EAAE,QAAQ,CAAC,CAAC;AAC5B;","names":[]}
@@ -675,6 +675,38 @@ var AnticipationCache = (_class2 = class {
675
675
  bundles
676
676
  };
677
677
  }
678
+ /**
679
+ * The freshest `user_summary` bundle for this entity, or null.
680
+ *
681
+ * `entityId` is REQUIRED, and a missing one refuses the lookup rather than
682
+ * falling back to the freshest summary across all users. Python hardened this
683
+ * for exactly that reason: the permissive version could splice user A's
684
+ * summary into user B's response on the conversation-scope path.
685
+ */
686
+ lookupUserSummary(entityId) {
687
+ if (!entityId) return null;
688
+ this.evictExpired();
689
+ let freshest = null;
690
+ for (const entry of this.entries.values()) {
691
+ if (entry.bundleType !== "user_summary") continue;
692
+ if (entry.entityId !== entityId && entry.entityId !== ANY_SCOPE) continue;
693
+ if (freshest === null || entry.storedAt > freshest.storedAt) freshest = entry;
694
+ }
695
+ if (freshest === null) return null;
696
+ if (!_chunkZKOJDUN4cjs.getEnvFlag.call(void 0, "SYNAP_SDK_CACHE_HONOR_TTL_HINT")) {
697
+ freshest.storedAt = this.now();
698
+ }
699
+ return this.#bundleFor(freshest.bundleId);
700
+ }
701
+ /** Rebuild a bundle's items_by_type from the flat item records. */
702
+ #bundleFor(bundleId) {
703
+ const itemsByType = {};
704
+ for (const record of this.items) {
705
+ if (record.bundleId !== bundleId) continue;
706
+ (itemsByType[record.itemType] ??= []).push(record.itemDict);
707
+ }
708
+ return { bundle_id: bundleId, items_by_type: itemsByType };
709
+ }
678
710
  /**
679
711
  * Drop every bundle belonging to one conversation.
680
712
  *
@@ -797,4 +829,4 @@ function round4(n) {
797
829
 
798
830
 
799
831
  exports.CONTRACT = CONTRACT; exports.THRESHOLDS = THRESHOLDS; exports.isRecallQuery = isRecallQuery; exports.stem = stem; exports.tokenize = tokenize; exports.BM25 = BM25; exports.ANY_SCOPE = ANY_SCOPE; exports.AnticipationCache = AnticipationCache;
800
- //# sourceMappingURL=chunk-NIDPTBNC.cjs.map
832
+ //# sourceMappingURL=chunk-RB57I2IQ.cjs.map