@atlaskit/editor-plugin-autocomplete 8.0.0 → 9.0.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.
- package/CHANGELOG.md +80 -0
- package/dist/cjs/analytics/ufo.js +2 -1
- package/dist/cjs/pm-plugins/artifact-loader.js +135 -0
- package/dist/cjs/pm-plugins/artifacts-manifest.js +3 -0
- package/dist/cjs/pm-plugins/autocomplete-plugin.js +416 -129
- package/dist/cjs/pm-plugins/canonical-lm-scoring.js +371 -0
- package/dist/cjs/pm-plugins/debug-mode.js +90 -7
- package/dist/cjs/pm-plugins/ghost-text-decoration.js +12 -3
- package/dist/cjs/pm-plugins/local-slow-lane-client.js +1202 -453
- package/dist/cjs/pm-plugins/scoring-pipeline.js +164 -19
- package/dist/cjs/pm-plugins/slow-lane-client.js +100 -37
- package/dist/cjs/pm-plugins/text-predictor.js +1951 -273
- package/dist/es2019/analytics/ufo.js +2 -0
- package/dist/es2019/pm-plugins/artifact-loader.js +70 -0
- package/dist/es2019/pm-plugins/artifacts-manifest.js +3 -0
- package/dist/es2019/pm-plugins/autocomplete-plugin.js +425 -130
- package/dist/es2019/pm-plugins/canonical-lm-scoring.js +270 -0
- package/dist/es2019/pm-plugins/debug-mode.js +87 -7
- package/dist/es2019/pm-plugins/ghost-text-decoration.js +12 -3
- package/dist/es2019/pm-plugins/local-slow-lane-client.js +940 -326
- package/dist/es2019/pm-plugins/scoring-pipeline.js +137 -13
- package/dist/es2019/pm-plugins/slow-lane-client.js +94 -37
- package/dist/es2019/pm-plugins/text-predictor.js +1603 -199
- package/dist/esm/analytics/ufo.js +2 -1
- package/dist/esm/pm-plugins/artifact-loader.js +128 -0
- package/dist/esm/pm-plugins/artifacts-manifest.js +3 -0
- package/dist/esm/pm-plugins/autocomplete-plugin.js +419 -132
- package/dist/esm/pm-plugins/canonical-lm-scoring.js +364 -0
- package/dist/esm/pm-plugins/debug-mode.js +89 -6
- package/dist/esm/pm-plugins/ghost-text-decoration.js +12 -3
- package/dist/esm/pm-plugins/local-slow-lane-client.js +1200 -451
- package/dist/esm/pm-plugins/scoring-pipeline.js +163 -18
- package/dist/esm/pm-plugins/slow-lane-client.js +100 -37
- package/dist/esm/pm-plugins/text-predictor.js +1953 -277
- package/dist/types/analytics/ufo.d.ts +1 -0
- package/dist/types/pm-plugins/artifact-loader.d.ts +44 -0
- package/dist/types/pm-plugins/artifacts-manifest.d.ts +3 -0
- package/dist/types/pm-plugins/autocomplete-plugin.d.ts +39 -0
- package/dist/types/pm-plugins/canonical-lm-scoring.d.ts +158 -0
- package/dist/types/pm-plugins/debug-mode.d.ts +36 -1
- package/dist/types/pm-plugins/ghost-text-decoration.d.ts +5 -2
- package/dist/types/pm-plugins/local-slow-lane-client.d.ts +87 -54
- package/dist/types/pm-plugins/scoring-pipeline.d.ts +33 -1
- package/dist/types/pm-plugins/slow-lane-client.d.ts +51 -3
- package/dist/types/pm-plugins/text-predictor.d.ts +120 -2
- package/package.json +2 -2
- package/src/analytics/ufo.ts +5 -0
- package/src/pm-plugins/artifact-loader.ts +92 -0
- package/src/pm-plugins/artifacts-manifest.ts +3 -0
- package/src/pm-plugins/autocomplete-plugin.ts +517 -133
- package/src/pm-plugins/canonical-lm-scoring.ts +412 -0
- package/src/pm-plugins/debug-mode.ts +109 -7
- package/src/pm-plugins/ghost-text-decoration.ts +13 -4
- package/src/pm-plugins/local-slow-lane-client.ts +1302 -386
- package/src/pm-plugins/scoring-pipeline.ts +167 -17
- package/src/pm-plugins/slow-lane-client.ts +147 -62
- package/src/pm-plugins/text-predictor.ts +2006 -255
- package/CANONICAL_FIX__DO_NOT_USE_ME_A/package.json +0 -8
- package/CANONICAL_FIX__DO_NOT_USE_ME_B/package.json +0 -8
- package/CANONICAL_FIX__DO_NOT_USE_ME_C/package.json +0 -8
- package/dist/cjs/entry-points/src-pm-plugins-autocomplete-plugin.js +0 -18
- package/dist/cjs/entry-points/src-pm-plugins-slow-lane-client.js +0 -36
- package/dist/cjs/entry-points/src-pm-plugins-text-predictor.js +0 -66
- package/dist/es2019/entry-points/src-pm-plugins-autocomplete-plugin.js +0 -2
- package/dist/es2019/entry-points/src-pm-plugins-slow-lane-client.js +0 -2
- package/dist/es2019/entry-points/src-pm-plugins-text-predictor.js +0 -2
- package/dist/esm/entry-points/src-pm-plugins-autocomplete-plugin.js +0 -2
- package/dist/esm/entry-points/src-pm-plugins-slow-lane-client.js +0 -2
- package/dist/esm/entry-points/src-pm-plugins-text-predictor.js +0 -2
- package/dist/types/entry-points/src-pm-plugins-autocomplete-plugin.d.ts +0 -2
- package/dist/types/entry-points/src-pm-plugins-slow-lane-client.d.ts +0 -2
- package/dist/types/entry-points/src-pm-plugins-text-predictor.d.ts +0 -2
- package/scripts/gen_first_token_to_words.py +0 -170
- package/src/entry-points/src-pm-plugins-autocomplete-plugin.ts +0 -7
- package/src/entry-points/src-pm-plugins-slow-lane-client.ts +0 -13
- package/src/entry-points/src-pm-plugins-text-predictor.ts +0 -14
- package/src/pm-plugins/autocomplete-plugin/package.json +0 -8
- package/src/pm-plugins/slow-lane-client/package.json +0 -8
- package/src/pm-plugins/text-predictor/package.json +0 -8
|
@@ -4,7 +4,7 @@ import _defineProperty from "@babel/runtime/helpers/defineProperty";
|
|
|
4
4
|
*
|
|
5
5
|
* Two prediction modes:
|
|
6
6
|
* 1. Word boundary → bigram-based next-word suggestion (grammar-filtered)
|
|
7
|
-
* 2. Mid-word (≥
|
|
7
|
+
* 2. Mid-word (≥1 char) → grouped prefetch; ≥3 chars + exact evidence → ghost result
|
|
8
8
|
*
|
|
9
9
|
* Scoring is delegated to scoring-pipeline.ts which handles:
|
|
10
10
|
* Stage 1 (semantic + frequency), grammar filter, Stage 2 (optional LM re-ranking).
|
|
@@ -17,14 +17,12 @@ import _defineProperty from "@babel/runtime/helpers/defineProperty";
|
|
|
17
17
|
*/
|
|
18
18
|
|
|
19
19
|
import { EXPERIENCE_NAME, failExp, startExp, succeedExp } from '../analytics/ufo';
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
import {
|
|
25
|
-
import {
|
|
26
|
-
import { rankCandidates, STAGE1_WEIGHT, STAGE2_WEIGHT, MIN_STAGE1_SCORE } from './scoring-pipeline';
|
|
27
|
-
import { getStoredContextVector, getStoredLmLogits } from './slow-lane-client';
|
|
20
|
+
import { fetchAutocompleteArtifactBinary, fetchAutocompleteArtifactJson } from './artifact-loader';
|
|
21
|
+
import { ARTIFACT_NAME } from './artifacts-manifest';
|
|
22
|
+
import { createCanonicalContextPositionCache, deriveCanonicalCandidateContext, deriveWhitespaceBoundaryContext, logSoftmaxAt, logSumExp, selectBoundaryPrimeRequests } from './canonical-lm-scoring';
|
|
23
|
+
import { CTC_STYLES, ctcSection, ctcTag, isAutocompleteDebugEnabled, isAutocompleteDebugVerbose } from './debug-mode';
|
|
24
|
+
import { loadGrammarDataAsync, rankCandidates, STAGE1_WEIGHT, STAGE2_WEIGHT, MIN_STAGE1_SCORE, MIN_WINNER_MARGIN } from './scoring-pipeline';
|
|
25
|
+
import { getBoundaryLmState, getCanonicalSurfaceCount, getCanonicalSurfaceTokenIds, getDefaultSlowLaneClientStatus, getProgressiveSurfaceEvidence, getStoredContextInput, getStoredContextVector, getStoredLmLogits, getSurfaceScore, isCanonicalSurfaceScoringSupported, primeBoundaryLm, requestProgressiveSurfaceScores } from './slow-lane-client';
|
|
28
26
|
|
|
29
27
|
// ─── Constants ───────────────────────────────────────────────────────────────
|
|
30
28
|
|
|
@@ -36,14 +34,153 @@ const WHITESPACE_SPLIT_REGEX = /\s+/;
|
|
|
36
34
|
const SENTENCE_BOUNDARY_REGEX = /[\n.?!]+/;
|
|
37
35
|
// eslint-disable-next-line require-unicode-regexp
|
|
38
36
|
const TRAILING_WHITESPACE_REGEX = /\s$/;
|
|
39
|
-
const
|
|
37
|
+
const TRAILING_SURFACE_TOKEN_REGEX = /[\p{L}\p{N}_'-]+$/u;
|
|
38
|
+
const SURFACE_TOKEN_REGEX = /[\p{L}\p{N}_'-]+/gu;
|
|
39
|
+
const ONLY_WHITESPACE_REGEX = /^\s+$/u;
|
|
40
|
+
const UNIGRAM_PREFETCH_MIN_PREFIX_LENGTH = 1;
|
|
41
|
+
const MULTIWORD_PREFETCH_MIN_PREFIX_LENGTH = 1;
|
|
42
|
+
const DISPLAY_MIN_PREFIX_LENGTH = 3;
|
|
40
43
|
const MAX_CANDIDATES = 200;
|
|
41
44
|
const CONTEXT_WORDS = 10;
|
|
42
|
-
const MIN_SCORE_THRESHOLD = 0.35;
|
|
43
45
|
const L3_BASELINE_FREQ = 0.001;
|
|
46
|
+
// Max tokens in a completion term (bigram=2, phrase=3). Mirrors the producer's
|
|
47
|
+
// `phrase_max_words` default so the FE window never exceeds what was mined.
|
|
48
|
+
const PHRASE_MAX_WORDS = 3;
|
|
49
|
+
// Per-window cap on phrase-trie subtree collection (keeps the hot path bounded).
|
|
50
|
+
const MAX_PHRASE_CANDIDATES = 50;
|
|
51
|
+
/**
|
|
52
|
+
* Share of its context shortlist's probability mass the model must put on a
|
|
53
|
+
* surface before that surface may be shown.
|
|
54
|
+
*
|
|
55
|
+
* Candidates competing at the same boundary are normalised into a posterior
|
|
56
|
+
* over that shortlist, so this reads directly as "the model is at least this
|
|
57
|
+
* sure". Measuring distance from the best candidate instead cannot express
|
|
58
|
+
* being unsure: the leader scores full marks whether it won by a nose or a
|
|
59
|
+
* mile, which pushes the entire question of how contested a context is onto
|
|
60
|
+
* `MIN_WINNER_MARGIN` — and there the blended score's only remaining spread is
|
|
61
|
+
* the corpus prior, the weakest ranking signal we have.
|
|
62
|
+
*
|
|
63
|
+
* Each extra token raises the bar. A wrong multi-word ghost costs the reader
|
|
64
|
+
* more to notice and undo than a wrong single word, and it is offered from the
|
|
65
|
+
* same keystroke, so precision has to be bought per token of commitment.
|
|
66
|
+
*/
|
|
67
|
+
const MIN_LM_POSTERIOR = {
|
|
68
|
+
word: 0.5,
|
|
69
|
+
bigram: 0.6,
|
|
70
|
+
phrase: 0.7
|
|
71
|
+
};
|
|
72
|
+
/**
|
|
73
|
+
* How many scored candidates a context must hold before its leader may show.
|
|
74
|
+
*
|
|
75
|
+
* A posterior is a share of a shortlist, so a shortlist of one hands its only
|
|
76
|
+
* member 1.0 whatever the model thinks of it — `logSumExp` of a single value
|
|
77
|
+
* returns that value. Such a ghost sits in the top bucket without having beaten
|
|
78
|
+
* anything, and it is the gate's blind spot rather than a case the gate ruled
|
|
79
|
+
* on: 1 in 14 of them were accepted against 34% for word ghosts overall, and
|
|
80
|
+
* every phrase shown through this hole was rejected.
|
|
81
|
+
*
|
|
82
|
+
* Counted over pool membership rather than over the normaliser, because those
|
|
83
|
+
* two deliberately differ. Where a pool holds a surface and its own extension
|
|
84
|
+
* the chain rule leaves one term in the denominator, and the resulting 1.0 is
|
|
85
|
+
* earned — whichever the user meant, the shorter form is a correct ghost.
|
|
86
|
+
*
|
|
87
|
+
* Waived where the context never held a second candidate at all. The 1-in-14
|
|
88
|
+
* acceptance above was measured over a population dominated by pools that read
|
|
89
|
+
* as one because rivals had not come back, and it is that absence of evidence
|
|
90
|
+
* the floor is for. A vocabulary offering a single continuation of a long
|
|
91
|
+
* distinctive prefix is the opposite situation, and it is also where a ghost
|
|
92
|
+
* saves the most keystrokes, so refusing it spends the most to learn the least.
|
|
93
|
+
*/
|
|
94
|
+
const MIN_SCORED_POOL_SIZE = 2;
|
|
95
|
+
/**
|
|
96
|
+
* Mean per-token log-probability a surface must hold, in nats, independently of
|
|
97
|
+
* anything it was competing against.
|
|
98
|
+
*
|
|
99
|
+
* Every other display test is relative: a posterior is a share of a shortlist,
|
|
100
|
+
* and a winner margin is a distance from a rival. So a surface reaches the
|
|
101
|
+
* screen by being the best of what happened to be in its pool, and nothing ever
|
|
102
|
+
* asks whether the model finds it plausible at all. That gap was tolerable while
|
|
103
|
+
* little was being read, and stopped being tolerable once the scheduler started
|
|
104
|
+
* reading roughly twice as much per decision: shown-per-decision went from 3.2%
|
|
105
|
+
* to 7.4% with no threshold moved, and acceptance of what showed fell from 32%
|
|
106
|
+
* to 24.5%. More reading does not weaken a relative test — it hands it far more
|
|
107
|
+
* pools to be the winner of, and the marginal winner is worse than the average.
|
|
108
|
+
*
|
|
109
|
+
* Set at the point where a uniform distribution over the model's vocabulary
|
|
110
|
+
* sits: 49,152 tokens, so `ln(1/49152)` is about -10.8 nats. Below it the model
|
|
111
|
+
* assigns the surface less mass than a token drawn at random, which is the only
|
|
112
|
+
* statement about a surface that needs no reference to what it competed with.
|
|
113
|
+
*
|
|
114
|
+
* It was first tried at -8, chosen from the bucket where acceptance was measured
|
|
115
|
+
* to fall away, and that reasoning does not survive more data. Acceptance against
|
|
116
|
+
* this quantity turned out to be a smooth slope — about 19% below -8, 26% from -8
|
|
117
|
+
* to -6, then flat near 35% above - with no discontinuity to place a threshold
|
|
118
|
+
* at. A floor on a smooth slope is a coverage dial rather than a test: -8 removed
|
|
119
|
+
* a band converting at 26% and cost 3.7 points of show rate, for an acceptance
|
|
120
|
+
* movement no sample of this size can resolve. Anchoring to uniform instead makes
|
|
121
|
+
* the value an argument about what is indefensible rather than a point picked off
|
|
122
|
+
* a histogram, which is what stops it from being retuned every batch.
|
|
123
|
+
*
|
|
124
|
+
* Applied to the mean over the verified prefix, the same quantity
|
|
125
|
+
* `ghostsByMeanLogProb` buckets, and deliberately not to
|
|
126
|
+
* `meanTokenLogProbabilityUpperBound`. The bound is the right instrument for
|
|
127
|
+
* keeping a candidate in the race, where dropping something that could still
|
|
128
|
+
* clear the bar would be an error, but it is systematically higher than the
|
|
129
|
+
* quantity acceptance is measured against. Judging a surface on the prefix that
|
|
130
|
+
* was actually read is also what every other test here does.
|
|
131
|
+
*
|
|
132
|
+
* One value across all three shapes. Splitting it per shape needs an acceptance
|
|
133
|
+
* curve per shape, and 19 bigrams and 1 phrase across five sessions cannot
|
|
134
|
+
* support one.
|
|
135
|
+
*/
|
|
136
|
+
const MIN_MEAN_TOKEN_LOG_PROBABILITY = -10.8;
|
|
137
|
+
// Tab replaces the whole remaining suffix, so an N-character completion saves
|
|
138
|
+
// N-1 keystrokes: at one character it saves nothing at all and at two it saves
|
|
139
|
+
// one, which does not repay noticing the ghost and reaching for Tab. Offering
|
|
140
|
+
// them anyway spends the acceptance-rate denominator on completions nobody
|
|
141
|
+
// wants and teaches the user to stop reading ghosts. `DISPLAY_MIN_PREFIX_LENGTH`
|
|
142
|
+
// is the same guard on the side the user has already typed.
|
|
143
|
+
const MIN_SUGGESTION_LENGTH = 3;
|
|
144
|
+
/**
|
|
145
|
+
* How many leading tokens of a surface must be scored before it may be shown.
|
|
146
|
+
*
|
|
147
|
+
* Scoring a token costs one model round trip, and a round trip costs about the
|
|
148
|
+
* same no matter how much is in it, so the price of a candidate is its token
|
|
149
|
+
* count. Demanding every token therefore caps what can ever reach the screen at
|
|
150
|
+
* roughly two tokens inside the decision budget — which is why no phrase has
|
|
151
|
+
* ever been displayed. Verifying a fixed prefix makes the cost of a candidate
|
|
152
|
+
* independent of its length.
|
|
153
|
+
*/
|
|
154
|
+
const REQUIRED_VERIFIED_TOKENS = 2;
|
|
155
|
+
/**
|
|
156
|
+
* Extra winner margin demanded of a surface judged on a verified prefix rather
|
|
157
|
+
* than on every one of its tokens, to buy back the precision given up by
|
|
158
|
+
* leaving the tail unread.
|
|
159
|
+
*/
|
|
160
|
+
const PARTIAL_EVIDENCE_MARGIN_PREMIUM = 0.08;
|
|
161
|
+
const ARBITRATION_MODE = 'confidence-v2';
|
|
162
|
+
const DEBUG_TEXT_TAIL_CHARS = 120;
|
|
44
163
|
|
|
45
164
|
// ─── Types ───────────────────────────────────────────────────────────────────
|
|
46
165
|
|
|
166
|
+
/**
|
|
167
|
+
* Which constraint stopped an evaluation from putting a ghost on screen.
|
|
168
|
+
*
|
|
169
|
+
* Each one implies different work: `below-posterior-gate` is a threshold to
|
|
170
|
+
* calibrate, `winner-margin` is two candidates the model cannot separate,
|
|
171
|
+
* `cold-competitor` and `unresolved-rival` are scheduling, and `no-candidate`
|
|
172
|
+
* is vocabulary coverage.
|
|
173
|
+
*/
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* A candidate paired with the length of the already-typed prefix it completes.
|
|
177
|
+
* For a single word this is the current partial token length; for a phrase it
|
|
178
|
+
* is the length of the matched multi-word window (previous words + partial),
|
|
179
|
+
* so the ghost tail is `word.slice(matchedPrefixLen)`.
|
|
180
|
+
*/
|
|
181
|
+
|
|
182
|
+
/** Optional per-term metadata carried by bigram/phrase completion terms. */
|
|
183
|
+
|
|
47
184
|
class TrieNode {
|
|
48
185
|
constructor() {
|
|
49
186
|
_defineProperty(this, "children", new Map());
|
|
@@ -52,6 +189,12 @@ class TrieNode {
|
|
|
52
189
|
_defineProperty(this, "docFreq", 0);
|
|
53
190
|
_defineProperty(this, "authorFreq", 0);
|
|
54
191
|
_defineProperty(this, "sessionFreq", 0);
|
|
192
|
+
// Term-type + phrase metadata. Plain words keep `termType='word'` and null
|
|
193
|
+
// metadata; bigram/phrase nodes carry the producer-shipped POS + association.
|
|
194
|
+
_defineProperty(this, "termType", 'word');
|
|
195
|
+
_defineProperty(this, "posSeq", null);
|
|
196
|
+
_defineProperty(this, "headPos", null);
|
|
197
|
+
_defineProperty(this, "association", null);
|
|
55
198
|
}
|
|
56
199
|
}
|
|
57
200
|
class WeightedWordTrie {
|
|
@@ -60,7 +203,8 @@ class WeightedWordTrie {
|
|
|
60
203
|
/** Highest tenantFreq seen — used to normalize freq scores at query time */
|
|
61
204
|
_defineProperty(this, "maxTenantFreq", 1);
|
|
62
205
|
}
|
|
63
|
-
insert(word, tenantFreq, docFreq, authorFreq) {
|
|
206
|
+
insert(word, tenantFreq, docFreq, authorFreq, meta) {
|
|
207
|
+
var _meta$termType, _meta$posSeq, _meta$headPos, _meta$association;
|
|
64
208
|
let node = this.root;
|
|
65
209
|
for (const char of word.toLowerCase()) {
|
|
66
210
|
let next = node.children.get(char);
|
|
@@ -74,6 +218,10 @@ class WeightedWordTrie {
|
|
|
74
218
|
node.tenantFreq = tenantFreq;
|
|
75
219
|
node.docFreq = docFreq;
|
|
76
220
|
node.authorFreq = authorFreq;
|
|
221
|
+
node.termType = (_meta$termType = meta === null || meta === void 0 ? void 0 : meta.termType) !== null && _meta$termType !== void 0 ? _meta$termType : 'word';
|
|
222
|
+
node.posSeq = (_meta$posSeq = meta === null || meta === void 0 ? void 0 : meta.posSeq) !== null && _meta$posSeq !== void 0 ? _meta$posSeq : null;
|
|
223
|
+
node.headPos = (_meta$headPos = meta === null || meta === void 0 ? void 0 : meta.headPos) !== null && _meta$headPos !== void 0 ? _meta$headPos : null;
|
|
224
|
+
node.association = (_meta$association = meta === null || meta === void 0 ? void 0 : meta.association) !== null && _meta$association !== void 0 ? _meta$association : null;
|
|
77
225
|
if (tenantFreq > this.maxTenantFreq) {
|
|
78
226
|
this.maxTenantFreq = tenantFreq;
|
|
79
227
|
}
|
|
@@ -158,6 +306,15 @@ const wordTrie = new WeightedWordTrie();
|
|
|
158
306
|
// L3 Trie (General English Fallback)
|
|
159
307
|
const l3Trie = new WeightedWordTrie();
|
|
160
308
|
|
|
309
|
+
/**
|
|
310
|
+
* L2 phrase/bigram trie. Kept SEPARATE from `wordTrie` so single-word
|
|
311
|
+
* completion + L3 gap-fill stay untouched; multi-word units are only surfaced
|
|
312
|
+
* by the (12b) multiword prefix-window matcher. Keys are the full normalized
|
|
313
|
+
* surface string (spaces included), e.g. `"return on investment"`, so a lookup
|
|
314
|
+
* is a plain char-trie walk over the whole phrase.
|
|
315
|
+
*/
|
|
316
|
+
const phraseTrie = new WeightedWordTrie();
|
|
317
|
+
|
|
161
318
|
/**
|
|
162
319
|
* Loads the General English vocabulary.
|
|
163
320
|
* expects a simple array of strings: ["about", "above", "actually", ...]
|
|
@@ -168,10 +325,8 @@ export const initL3Vocabulary = l3Words => {
|
|
|
168
325
|
// loses to any domain word in Stage 1, but still scores above 0.
|
|
169
326
|
l3Trie.insert(word, L3_BASELINE_FREQ, 0, 0);
|
|
170
327
|
}
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
console.log(`[text-predictor] L3 General English loaded: ${l3Words.length} words`);
|
|
174
|
-
}
|
|
328
|
+
recallGeneration++;
|
|
329
|
+
ctcTag('init', `L3 general English loaded: ${l3Words.length} words`);
|
|
175
330
|
};
|
|
176
331
|
|
|
177
332
|
// const bigramMap: Map<string, Record<string, number>> = new Map(
|
|
@@ -181,8 +336,50 @@ export const initL3Vocabulary = l3Words => {
|
|
|
181
336
|
let isInitialized = false;
|
|
182
337
|
let vectorStore = null;
|
|
183
338
|
let vectorsLoadStarted = false;
|
|
339
|
+
|
|
340
|
+
// Phrase/bigram artifacts load independently of the word vocabulary so a
|
|
341
|
+
// missing/late `bigrams.json`/`phrases.json` never breaks word completion.
|
|
342
|
+
let phrasesLoadStarted = false;
|
|
343
|
+
let phrasesLoaded = false;
|
|
344
|
+
let phraseTermCount = 0;
|
|
345
|
+
// Per-type frequency maxima, tracked separately because bigrams and phrases
|
|
346
|
+
// share one trie but have very different absolute frequency ranges (bigrams are
|
|
347
|
+
// far more frequent than 3-word phrases). Normalizing each type by its OWN max
|
|
348
|
+
// stops phrase freq scores from being crushed against the top bigram's count.
|
|
349
|
+
let maxBigramFreq = 1;
|
|
350
|
+
let maxPhraseFreq = 1;
|
|
184
351
|
let lastPredictionDebug = null;
|
|
185
352
|
|
|
353
|
+
// ── Stabilization (QI-2): post-accept cooldown + whole-surface repetition ────
|
|
354
|
+
// Two guards that stop the accept→echo (`end to end` → `end to end to end`) and
|
|
355
|
+
// generally keep a just-accepted unit from being re-offered:
|
|
356
|
+
// • repetition: never surface a candidate whose full surface already equals the
|
|
357
|
+
// run of tokens immediately before the cursor (handled inline in predict()).
|
|
358
|
+
// • cooldown: after an accept, briefly suppress re-offering that same unit. The
|
|
359
|
+
// cooldown lifts only once BOTH the keystroke budget and the time window have
|
|
360
|
+
// elapsed (either one still counting keeps it active).
|
|
361
|
+
const COOLDOWN_KEYSTROKES = 5;
|
|
362
|
+
const COOLDOWN_MS = 2000;
|
|
363
|
+
|
|
364
|
+
// Active post-accept cooldown, or null when none.
|
|
365
|
+
let acceptCooldown = null;
|
|
366
|
+
|
|
367
|
+
/**
|
|
368
|
+
* Start a short cooldown for the exact surface the editor inserted. The caller
|
|
369
|
+
* passes the committed snapshot's surface so background re-ranking can never
|
|
370
|
+
* move cooldown bookkeeping away from what the user actually accepted.
|
|
371
|
+
*/
|
|
372
|
+
export const noteSuggestionAccepted = surface => {
|
|
373
|
+
const normalizedSurface = surface.trim().toLowerCase();
|
|
374
|
+
if (normalizedSurface) {
|
|
375
|
+
acceptCooldown = {
|
|
376
|
+
predictionsSince: 0,
|
|
377
|
+
surface: normalizedSurface,
|
|
378
|
+
ts: performance.now()
|
|
379
|
+
};
|
|
380
|
+
}
|
|
381
|
+
};
|
|
382
|
+
|
|
186
383
|
/** Get vector for a word from the store. */
|
|
187
384
|
const getWordVector = word => {
|
|
188
385
|
if (!vectorStore) {
|
|
@@ -260,6 +457,111 @@ const extractPreviousWord = text => {
|
|
|
260
457
|
return words.length >= 2 ? words[words.length - 2] : '';
|
|
261
458
|
};
|
|
262
459
|
|
|
460
|
+
/**
|
|
461
|
+
* Collect phrase/bigram completion candidates for the multi-word window ending
|
|
462
|
+
* at the current partial token.
|
|
463
|
+
*
|
|
464
|
+
* Builds windows of the last `2..PHRASE_MAX_WORDS` tokens of the current
|
|
465
|
+
* sentence (widest first) and prefix-searches the phrase trie for each, so
|
|
466
|
+
* `quarterly pla` matches `quarterly planning meeting`. Windows never cross a
|
|
467
|
+
* sentence boundary (mirrors `extractPreviousWord`). Each result records the
|
|
468
|
+
* matched window length so the caller can compute the ghost tail.
|
|
469
|
+
*
|
|
470
|
+
* :params:
|
|
471
|
+
* trimmed: Text before the cursor, trailing whitespace already removed
|
|
472
|
+
* :returns:
|
|
473
|
+
* Matched phrase candidates (deduped, widest-window match wins per term)
|
|
474
|
+
*/
|
|
475
|
+
const getPhraseCandidates = trimmed => {
|
|
476
|
+
// Records every prefix window we probe and its match count so the (verbose)
|
|
477
|
+
// debug line makes it obvious whether the phrase path found nothing because the
|
|
478
|
+
// trie is empty, or because no phrase begins with the typed window.
|
|
479
|
+
const windowsTried = [];
|
|
480
|
+
const logPhrasePath = skipReason => {
|
|
481
|
+
if (!isAutocompleteDebugVerbose()) {
|
|
482
|
+
return;
|
|
483
|
+
}
|
|
484
|
+
const detail = skipReason ? skipReason : `windows: ${windowsTried.map(w => `"${w.window}"→${w.matches}`).join(', ') || '(none)'}`;
|
|
485
|
+
ctcTag('phrase', `loaded=${phraseTermCount} (${phrasesLoaded ? 'ready' : 'not loaded'}) · ${detail}`, CTC_STYLES.section);
|
|
486
|
+
};
|
|
487
|
+
if (phraseTermCount === 0) {
|
|
488
|
+
logPhrasePath('phrase trie empty — bigrams.json/phrases.json not loaded (or 0 terms)');
|
|
489
|
+
return [];
|
|
490
|
+
}
|
|
491
|
+
const tokenMatches = Array.from(trimmed.matchAll(SURFACE_TOKEN_REGEX));
|
|
492
|
+
const lastMatch = tokenMatches[tokenMatches.length - 1];
|
|
493
|
+
const lastStart = lastMatch === null || lastMatch === void 0 ? void 0 : lastMatch.index;
|
|
494
|
+
if (!lastMatch || lastStart === undefined || lastStart + lastMatch[0].length !== trimmed.length) {
|
|
495
|
+
logPhrasePath('no tokens in current sentence');
|
|
496
|
+
return [];
|
|
497
|
+
}
|
|
498
|
+
const trailingTokens = [{
|
|
499
|
+
start: lastStart,
|
|
500
|
+
value: lastMatch[0]
|
|
501
|
+
}];
|
|
502
|
+
for (let i = tokenMatches.length - 2; i >= 0; i--) {
|
|
503
|
+
const current = trailingTokens[0];
|
|
504
|
+
const match = tokenMatches[i];
|
|
505
|
+
const start = match.index;
|
|
506
|
+
if (start === undefined) {
|
|
507
|
+
break;
|
|
508
|
+
}
|
|
509
|
+
const end = start + match[0].length;
|
|
510
|
+
const gap = trimmed.slice(end, current.start);
|
|
511
|
+
if (!ONLY_WHITESPACE_REGEX.test(gap)) {
|
|
512
|
+
break;
|
|
513
|
+
}
|
|
514
|
+
trailingTokens.unshift({
|
|
515
|
+
start,
|
|
516
|
+
value: match[0]
|
|
517
|
+
});
|
|
518
|
+
if (trailingTokens.length >= PHRASE_MAX_WORDS) {
|
|
519
|
+
break;
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
const partial = trailingTokens[trailingTokens.length - 1].value;
|
|
523
|
+
const results = [];
|
|
524
|
+
const seen = new Set();
|
|
525
|
+
const maxPrev = trailingTokens.length - 1;
|
|
526
|
+
|
|
527
|
+
// Widest window first so the most specific (longest-context) match wins the
|
|
528
|
+
// dedup for a given phrase term. `prev` is the number of *preceding* complete
|
|
529
|
+
// words included ahead of the current partial:
|
|
530
|
+
// prev ≥ 1 → "continue a phrase I've started" (e.g. "root c" → root cause).
|
|
531
|
+
// Preceding-word context is strong, so a short partial is fine.
|
|
532
|
+
// prev = 0 → "the partial is a phrase's FIRST word" (e.g. "root" → root
|
|
533
|
+
// cause). No preceding context, so require the partial to be a
|
|
534
|
+
// one character so grouped LM work can begin early. UI remains
|
|
535
|
+
// gated at DISPLAY_MIN_PREFIX_LENGTH.
|
|
536
|
+
for (let prev = maxPrev; prev >= 0; prev--) {
|
|
537
|
+
if (prev === 0 && partial.length < MULTIWORD_PREFETCH_MIN_PREFIX_LENGTH) {
|
|
538
|
+
continue;
|
|
539
|
+
}
|
|
540
|
+
const windowTokens = trailingTokens.slice(-(prev + 1));
|
|
541
|
+
const windowPrefix = windowTokens.map(token => token.value).join(' ').toLowerCase();
|
|
542
|
+
const windowLen = windowPrefix.length;
|
|
543
|
+
const matches = phraseTrie.getCandidates(windowPrefix, MAX_PHRASE_CANDIDATES);
|
|
544
|
+
windowsTried.push({
|
|
545
|
+
window: windowPrefix,
|
|
546
|
+
matches: matches.length
|
|
547
|
+
});
|
|
548
|
+
for (const match of matches) {
|
|
549
|
+
if (seen.has(match.word)) {
|
|
550
|
+
continue;
|
|
551
|
+
}
|
|
552
|
+
seen.add(match.word);
|
|
553
|
+
results.push({
|
|
554
|
+
node: match.node,
|
|
555
|
+
word: match.word,
|
|
556
|
+
matchedPrefixLen: windowLen,
|
|
557
|
+
surfaceStart: windowTokens[0].start
|
|
558
|
+
});
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
logPhrasePath();
|
|
562
|
+
return results;
|
|
563
|
+
};
|
|
564
|
+
|
|
263
565
|
// ─── Debug Helpers ───────────────────────────────────────────────────────────
|
|
264
566
|
|
|
265
567
|
/**
|
|
@@ -268,11 +570,25 @@ const extractPreviousWord = text => {
|
|
|
268
570
|
* wordCount: number of words in vector store (0 if not loaded)
|
|
269
571
|
*/
|
|
270
572
|
export const getPredictorStatus = () => {
|
|
573
|
+
const slowLaneStatus = getDefaultSlowLaneClientStatus();
|
|
271
574
|
return {
|
|
575
|
+
canonicalScoringSupported: slowLaneStatus.canonicalScoringSupported,
|
|
576
|
+
canonicalSurfaceCount: slowLaneStatus.canonicalSurfaceCount,
|
|
577
|
+
clientId: slowLaneStatus.clientId,
|
|
578
|
+
clientKind: slowLaneStatus.clientKind,
|
|
579
|
+
localModelReady: slowLaneStatus.localModelReady,
|
|
580
|
+
slowLaneRegistered: slowLaneStatus.registered,
|
|
272
581
|
vectorsLoaded: vectorStore !== null,
|
|
273
582
|
wordCount: vectorStore ? Object.keys(vectorStore.wordIndex).length : 0,
|
|
274
583
|
vectorsLoadStarted,
|
|
275
|
-
isInitialized
|
|
584
|
+
isInitialized,
|
|
585
|
+
phrasesLoaded,
|
|
586
|
+
phraseCount: phraseTermCount,
|
|
587
|
+
maxFreqByType: {
|
|
588
|
+
word: wordTrie.maxTenantFreq,
|
|
589
|
+
bigram: maxBigramFreq,
|
|
590
|
+
phrase: maxPhraseFreq
|
|
591
|
+
}
|
|
276
592
|
};
|
|
277
593
|
};
|
|
278
594
|
|
|
@@ -288,6 +604,41 @@ export const initVocabulary = vocabulary => {
|
|
|
288
604
|
wordTrie.insert(term.word, term.freq, term.docFreq, term.authorFreq);
|
|
289
605
|
}
|
|
290
606
|
isInitialized = true;
|
|
607
|
+
recallGeneration++;
|
|
608
|
+
};
|
|
609
|
+
|
|
610
|
+
/**
|
|
611
|
+
* Insert a producer-shipped bigram/phrase artifact into the phrase trie.
|
|
612
|
+
*
|
|
613
|
+
* :params:
|
|
614
|
+
* artifact: Normalized `{term: {freq, doc_freq, author_freq, pos_seq, head_pos, association}}` map
|
|
615
|
+
* termType: Whether these terms are `bigram` (2 tokens) or `phrase` (3 tokens)
|
|
616
|
+
* :returns:
|
|
617
|
+
* The number of terms inserted
|
|
618
|
+
*/
|
|
619
|
+
export const initPhrases = (artifact, termType) => {
|
|
620
|
+
let count = 0;
|
|
621
|
+
for (const [term, stats] of Object.entries(artifact)) {
|
|
622
|
+
var _stats$pos_seq, _stats$head_pos, _stats$association;
|
|
623
|
+
phraseTrie.insert(term, stats.freq, stats.doc_freq, stats.author_freq, {
|
|
624
|
+
termType,
|
|
625
|
+
posSeq: (_stats$pos_seq = stats.pos_seq) !== null && _stats$pos_seq !== void 0 ? _stats$pos_seq : null,
|
|
626
|
+
headPos: (_stats$head_pos = stats.head_pos) !== null && _stats$head_pos !== void 0 ? _stats$head_pos : null,
|
|
627
|
+
association: (_stats$association = stats.association) !== null && _stats$association !== void 0 ? _stats$association : null
|
|
628
|
+
});
|
|
629
|
+
// Track each type's own frequency ceiling for per-type normalization.
|
|
630
|
+
if (termType === 'bigram') {
|
|
631
|
+
if (stats.freq > maxBigramFreq) {
|
|
632
|
+
maxBigramFreq = stats.freq;
|
|
633
|
+
}
|
|
634
|
+
} else if (stats.freq > maxPhraseFreq) {
|
|
635
|
+
maxPhraseFreq = stats.freq;
|
|
636
|
+
}
|
|
637
|
+
count++;
|
|
638
|
+
}
|
|
639
|
+
phraseTermCount += count;
|
|
640
|
+
recallGeneration++;
|
|
641
|
+
return count;
|
|
291
642
|
};
|
|
292
643
|
|
|
293
644
|
/**
|
|
@@ -321,107 +672,175 @@ export const ingestDocumentPage = pageContent => {
|
|
|
321
672
|
}
|
|
322
673
|
}
|
|
323
674
|
if (isAutocompleteDebugEnabled() && validBoostedWords.size > 0) {
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
console.groupEnd();
|
|
675
|
+
ctcTag('init', `L1 session primed ${validBoostedWords.size} words from page`, CTC_STYLES.brand);
|
|
676
|
+
if (isAutocompleteDebugVerbose()) {
|
|
677
|
+
// eslint-disable-next-line no-console
|
|
678
|
+
console.dir(Array.from(validBoostedWords).sort());
|
|
679
|
+
}
|
|
330
680
|
}
|
|
331
681
|
};
|
|
682
|
+
|
|
683
|
+
/**
|
|
684
|
+
* Result of a prediction: the ghost tail to insert plus an immutable record of
|
|
685
|
+
* the evidence that authorized the UI commitment.
|
|
686
|
+
*/
|
|
687
|
+
|
|
688
|
+
// ─── Recall memo ─────────────────────────────────────────────────────────────
|
|
689
|
+
|
|
690
|
+
/** Trie recall plus the canonical context derived for each matched term. */
|
|
691
|
+
|
|
692
|
+
/**
|
|
693
|
+
* Bumped whenever an artifact load changes what the tries can return, which is
|
|
694
|
+
* the only way the candidate *set* for a given prefix can change.
|
|
695
|
+
*
|
|
696
|
+
* Session-frequency boosts are deliberately not counted: they mutate trie nodes
|
|
697
|
+
* in place, and the memo holds those nodes by reference, so a boost is already
|
|
698
|
+
* visible through a cached entry.
|
|
699
|
+
*/
|
|
700
|
+
let recallGeneration = 0;
|
|
701
|
+
let recallMemo = null;
|
|
702
|
+
const computeCanonicalRecall = (trimmed, currentWord, currentWordStart) => {
|
|
703
|
+
// Start recall at one character so grouped causal work can overlap later
|
|
704
|
+
// keystrokes. Nothing is displayed until three characters.
|
|
705
|
+
const wordCandidates = currentWord.length >= UNIGRAM_PREFETCH_MIN_PREFIX_LENGTH ? wordTrie.getCandidates(currentWord, MAX_CANDIDATES) : [];
|
|
706
|
+
|
|
707
|
+
// Gap-fill from the L3 general-English trie, requesting a full buffer so
|
|
708
|
+
// enough survive de-duplication against the L2 results.
|
|
709
|
+
if (currentWord.length >= UNIGRAM_PREFETCH_MIN_PREFIX_LENGTH && wordCandidates.length < MAX_CANDIDATES) {
|
|
710
|
+
const l3Candidates = l3Trie.getCandidates(currentWord, MAX_CANDIDATES);
|
|
711
|
+
const existingWords = new Set(wordCandidates.map(c => c.word));
|
|
712
|
+
for (const l3c of l3Candidates) {
|
|
713
|
+
if (wordCandidates.length >= MAX_CANDIDATES) break;
|
|
714
|
+
if (!existingWords.has(l3c.word)) {
|
|
715
|
+
wordCandidates.push(l3c);
|
|
716
|
+
}
|
|
717
|
+
}
|
|
718
|
+
}
|
|
719
|
+
|
|
720
|
+
// Multi-word completion terms (bigrams/phrases) matched on the trailing
|
|
721
|
+
// window ending at the current partial token. Runs even when the unigram path
|
|
722
|
+
// was skipped for a short partial, so first-word/early phrase matches surface.
|
|
723
|
+
const phraseCandidates = getPhraseCandidates(trimmed);
|
|
724
|
+
|
|
725
|
+
// Unify: a word completes the current partial token; a phrase completes its
|
|
726
|
+
// matched multi-word window. Track the prefix length per term so the ghost
|
|
727
|
+
// tail is sliced correctly regardless of term type.
|
|
728
|
+
const matched = [...wordCandidates.map(({
|
|
729
|
+
word,
|
|
730
|
+
node
|
|
731
|
+
}) => ({
|
|
732
|
+
word,
|
|
733
|
+
node,
|
|
734
|
+
matchedPrefixLen: currentWord.length,
|
|
735
|
+
surfaceStart: currentWordStart
|
|
736
|
+
})), ...phraseCandidates];
|
|
737
|
+
const positionCache = createCanonicalContextPositionCache();
|
|
738
|
+
const canonicalMatched = matched.map(candidate => ({
|
|
739
|
+
...candidate,
|
|
740
|
+
...deriveCanonicalCandidateContext(trimmed, candidate.matchedPrefixLen, candidate.word, getCanonicalSurfaceTokenIds, candidate.surfaceStart, positionCache)
|
|
741
|
+
}));
|
|
742
|
+
const prefixLenByWord = new Map();
|
|
743
|
+
for (const m of canonicalMatched) {
|
|
744
|
+
if (!prefixLenByWord.has(m.word)) {
|
|
745
|
+
prefixLenByWord.set(m.word, m.matchedPrefixLen);
|
|
746
|
+
}
|
|
747
|
+
}
|
|
748
|
+
return {
|
|
749
|
+
canonicalMatched,
|
|
750
|
+
prefixLenByWord
|
|
751
|
+
};
|
|
752
|
+
};
|
|
753
|
+
|
|
754
|
+
/**
|
|
755
|
+
* Recall and canonical derivation for `trimmed`, reusing the previous result
|
|
756
|
+
* when nothing they depend on has changed.
|
|
757
|
+
*
|
|
758
|
+
* `predict()` runs several times for one keystroke — once when the decision
|
|
759
|
+
* opens and again for each async evidence signal that lands inside the budget —
|
|
760
|
+
* and only the evidence differs between those runs. Without this, every run
|
|
761
|
+
* re-walks the tries and re-derives a canonical context per candidate.
|
|
762
|
+
*/
|
|
763
|
+
const getCanonicalRecall = (trimmed, currentWord, currentWordStart) => {
|
|
764
|
+
const surfaceCount = getCanonicalSurfaceCount();
|
|
765
|
+
if (recallMemo !== null && recallMemo.trimmed === trimmed && recallMemo.generation === recallGeneration && recallMemo.surfaceCount === surfaceCount) {
|
|
766
|
+
return recallMemo;
|
|
767
|
+
}
|
|
768
|
+
const recall = computeCanonicalRecall(trimmed, currentWord, currentWordStart);
|
|
769
|
+
recallMemo = {
|
|
770
|
+
...recall,
|
|
771
|
+
generation: recallGeneration,
|
|
772
|
+
surfaceCount,
|
|
773
|
+
trimmed
|
|
774
|
+
};
|
|
775
|
+
return recall;
|
|
776
|
+
};
|
|
332
777
|
export const predict = textBefore => {
|
|
778
|
+
var _trimmed$match$, _trimmed$match, _canonicalMatched$fin, _eligible$, _eligible$0$score, _eligible$2, _judgedEvidenceFor3, _prefixLenByWord$get2, _runtimeBySurface$get1, _judgedEvidenceFor$me3, _judgedEvidenceFor6, _contextTotals$get$le4, _contextTotals$get4, _selectedEvidence$ver, _selectedEvidence$tot, _selectedEvidence$ver2;
|
|
333
779
|
if (!isInitialized) {
|
|
334
|
-
// Vocabulary
|
|
335
|
-
// and skip this keystroke; the plugin also primes it on
|
|
336
|
-
// are usually ready before the user types.
|
|
337
|
-
void loadDefaultVocabulary(
|
|
780
|
+
// Vocabulary artifacts load asynchronously over the autocomplete gateway.
|
|
781
|
+
// Kick off the load and skip this keystroke; the plugin also primes it on
|
|
782
|
+
// focus, so the tries are usually ready before the user types.
|
|
783
|
+
void loadDefaultVocabulary({
|
|
784
|
+
source: 'predict'
|
|
785
|
+
}).catch(() => {});
|
|
338
786
|
return null;
|
|
339
787
|
}
|
|
340
788
|
const t0 = performance.now();
|
|
341
789
|
|
|
342
|
-
//
|
|
343
|
-
//
|
|
344
|
-
//
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
//
|
|
358
|
-
// if (debugMode) {
|
|
359
|
-
// const latencyMs = performance.now() - t0;
|
|
360
|
-
// console.log(
|
|
361
|
-
// '%c[autocomplete] BIGRAM',
|
|
362
|
-
// 'color:cyan',
|
|
363
|
-
// '| "' + prevWord + '" -> "' + bestWord + '" | ' + latencyMs.toFixed(1) + 'ms',
|
|
364
|
-
// );
|
|
365
|
-
// }
|
|
366
|
-
// return bestWord;
|
|
367
|
-
// }
|
|
368
|
-
// }
|
|
369
|
-
// if (debugMode) {
|
|
370
|
-
// console.log(
|
|
371
|
-
// '%c[autocomplete] BIGRAM-MISS',
|
|
372
|
-
// 'color:gray',
|
|
373
|
-
// '| no bigram for "' + words[words.length - 1] + '", skipping prefix completion',
|
|
374
|
-
// );
|
|
375
|
-
// }
|
|
376
|
-
// return null;
|
|
377
|
-
// }
|
|
378
|
-
|
|
379
|
-
// ── Step 2: Prefix completion (≥3 chars typed) ──────────────────────────
|
|
790
|
+
// Advance the post-accept cooldown once per prediction. It stays active until
|
|
791
|
+
// BOTH the keystroke budget and the time window have elapsed; while active it
|
|
792
|
+
// suppresses re-offering the just-accepted surface (see arbitration below).
|
|
793
|
+
let cooledSurface = null;
|
|
794
|
+
if (acceptCooldown) {
|
|
795
|
+
acceptCooldown.predictionsSince += 1;
|
|
796
|
+
const stillByKeys = acceptCooldown.predictionsSince <= COOLDOWN_KEYSTROKES;
|
|
797
|
+
const stillByTime = performance.now() - acceptCooldown.ts < COOLDOWN_MS;
|
|
798
|
+
if (stillByKeys || stillByTime) {
|
|
799
|
+
cooledSurface = acceptCooldown.surface;
|
|
800
|
+
} else {
|
|
801
|
+
acceptCooldown = null;
|
|
802
|
+
}
|
|
803
|
+
}
|
|
804
|
+
|
|
805
|
+
// ── Boundary/early-prefix prefetch; display remains gated at ≥3 ─────────
|
|
380
806
|
if (textBefore.length > 0 && TRAILING_WHITESPACE_REGEX.test(textBefore)) {
|
|
807
|
+
const boundaryContext = deriveWhitespaceBoundaryContext(textBefore);
|
|
808
|
+
if (boundaryContext) {
|
|
809
|
+
primeBoundaryLm({
|
|
810
|
+
...boundaryContext,
|
|
811
|
+
familyKey: boundaryContext.contextKey,
|
|
812
|
+
priority: 0
|
|
813
|
+
});
|
|
814
|
+
}
|
|
381
815
|
return null;
|
|
382
816
|
}
|
|
383
817
|
const trimmed = textBefore.trimEnd();
|
|
384
|
-
const
|
|
385
|
-
|
|
386
|
-
if (currentWord.length < MIN_PREFIX_LENGTH) {
|
|
818
|
+
const trailingSurfaceToken = (_trimmed$match$ = (_trimmed$match = trimmed.match(TRAILING_SURFACE_TOKEN_REGEX)) === null || _trimmed$match === void 0 ? void 0 : _trimmed$match[0]) !== null && _trimmed$match$ !== void 0 ? _trimmed$match$ : '';
|
|
819
|
+
if (trailingSurfaceToken.length === 0) {
|
|
387
820
|
return null;
|
|
388
821
|
}
|
|
389
|
-
const
|
|
822
|
+
const currentWord = trailingSurfaceToken;
|
|
823
|
+
const currentWordStart = trimmed.length - currentWord.length;
|
|
824
|
+
const {
|
|
825
|
+
canonicalMatched,
|
|
826
|
+
prefixLenByWord
|
|
827
|
+
} = getCanonicalRecall(trimmed, currentWord, currentWordStart);
|
|
390
828
|
|
|
391
|
-
//
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
for (const l3c of l3Candidates) {
|
|
397
|
-
if (candidates.length >= MAX_CANDIDATES) break;
|
|
398
|
-
if (!existingWords.has(l3c.word)) {
|
|
399
|
-
candidates.push(l3c);
|
|
400
|
-
}
|
|
829
|
+
// If every trie was empty for this prefix
|
|
830
|
+
if (canonicalMatched.length === 0) {
|
|
831
|
+
if (isAutocompleteDebugEnabled()) {
|
|
832
|
+
// eslint-disable-next-line no-console
|
|
833
|
+
console.log(`%c[CTC]%c — abstain: no matches for "${currentWord}"`, CTC_STYLES.brand, CTC_STYLES.body);
|
|
401
834
|
}
|
|
402
|
-
}
|
|
403
|
-
|
|
404
|
-
// If both Tries are completely empty for this prefix
|
|
405
|
-
if (candidates.length === 0) {
|
|
406
835
|
return null;
|
|
407
836
|
}
|
|
408
837
|
const previousWord = extractPreviousWord(trimmed);
|
|
409
838
|
const contextVector = getContextVectorForScoring(trimmed);
|
|
410
839
|
const lmLogits = getStoredLmLogits();
|
|
411
|
-
|
|
412
|
-
// Raw LM Output Logger
|
|
413
|
-
if (isAutocompleteDebugEnabled() && lmLogits && Object.keys(lmLogits).length > 0) {
|
|
414
|
-
const rawLmTop = Object.entries(lmLogits).sort((a, b) => b[1] - a[1]).slice(0, 5).map(([word, score]) => ({
|
|
415
|
-
Word: word,
|
|
416
|
-
Prob: Number(score.toFixed(5))
|
|
417
|
-
}));
|
|
418
|
-
// eslint-disable-next-line no-console
|
|
419
|
-
console.log('%c[Raw LM Prediction]🧠', 'color: #e83e8c; font-weight: bold;', rawLmTop);
|
|
420
|
-
}
|
|
421
840
|
const mode = contextVector ? 'warm' : 'cold';
|
|
422
841
|
|
|
423
|
-
// Build ScoringCandidate array from
|
|
424
|
-
const scoringCandidates =
|
|
842
|
+
// Build ScoringCandidate array from matched terms (words + phrases)
|
|
843
|
+
const scoringCandidates = canonicalMatched.map(({
|
|
425
844
|
word,
|
|
426
845
|
node
|
|
427
846
|
}) => ({
|
|
@@ -429,29 +848,730 @@ export const predict = textBefore => {
|
|
|
429
848
|
tenantFreq: node.tenantFreq,
|
|
430
849
|
docFreq: node.docFreq,
|
|
431
850
|
authorFreq: node.authorFreq,
|
|
432
|
-
sessionFreq: node.sessionFreq
|
|
851
|
+
sessionFreq: node.sessionFreq,
|
|
852
|
+
termType: node.termType,
|
|
853
|
+
posSeq: node.posSeq,
|
|
854
|
+
headPos: node.headPos,
|
|
855
|
+
association: node.association
|
|
433
856
|
}));
|
|
434
857
|
|
|
435
858
|
// Filter the LM payload to only words matching the current prefix so that
|
|
436
859
|
// lmMax in rankCandidates reflects prefix-relevant signal, not the global distribution.
|
|
437
860
|
const prefix = currentWord.toLowerCase();
|
|
438
|
-
const
|
|
861
|
+
const currentWordSeparator = (_canonicalMatched$fin = canonicalMatched.find(candidate => candidate.node.termType === 'word')) === null || _canonicalMatched$fin === void 0 ? void 0 : _canonicalMatched$fin.separatorKind;
|
|
862
|
+
const prefixLmLogits = lmLogits && currentWordSeparator === 'whitespace' ? Object.fromEntries(Object.entries(lmLogits).filter(([word]) => word.startsWith(prefix))) : null;
|
|
863
|
+
const canonicalScoringSupported = isCanonicalSurfaceScoringSupported();
|
|
864
|
+
const eligibleContextKeys = Array.from(new Set(canonicalMatched.filter(candidate => candidate.canonicalTokenIds !== null).map(candidate => candidate.contextKey))).sort();
|
|
865
|
+
const familyKey = eligibleContextKeys.join('\u0001');
|
|
866
|
+
const primeRequests = selectBoundaryPrimeRequests(familyKey, canonicalMatched, PHRASE_MAX_WORDS);
|
|
867
|
+
for (const request of primeRequests) {
|
|
868
|
+
primeBoundaryLm(request);
|
|
869
|
+
}
|
|
870
|
+
const runtimeBySurface = new Map(canonicalMatched.map(candidate => [candidate.word, candidate]));
|
|
871
|
+
const canonicalEvidence = new Map();
|
|
872
|
+
const firstTokenGroups = new Map();
|
|
873
|
+
for (const candidate of canonicalMatched) {
|
|
874
|
+
var _firstTokenGroups$get;
|
|
875
|
+
if (candidate.canonicalTokenIds === null) {
|
|
876
|
+
continue;
|
|
877
|
+
}
|
|
878
|
+
// This accessor also materializes an exact cache entry when all tokens
|
|
879
|
+
// have already been covered by shared-prefix work.
|
|
880
|
+
getProgressiveSurfaceEvidence(candidate.contextKey, candidate.word);
|
|
881
|
+
const exact = getSurfaceScore(candidate.contextKey, candidate.word);
|
|
882
|
+
if (exact) {
|
|
883
|
+
canonicalEvidence.set(candidate.word, {
|
|
884
|
+
contextKey: candidate.contextKey,
|
|
885
|
+
meanTokenLogProbability: exact.meanTokenLogProbability,
|
|
886
|
+
score: 0,
|
|
887
|
+
separatorKind: 'whitespace',
|
|
888
|
+
source: 'canonical-full-surface',
|
|
889
|
+
totalLogProbability: exact.totalLogProbability,
|
|
890
|
+
totalSurfaceCharCount: candidate.word.length,
|
|
891
|
+
totalTokenCount: exact.tokenCount,
|
|
892
|
+
verifiedCharCount: candidate.word.length,
|
|
893
|
+
verifiedTokenCount: exact.tokenCount
|
|
894
|
+
});
|
|
895
|
+
continue;
|
|
896
|
+
}
|
|
897
|
+
const group = (_firstTokenGroups$get = firstTokenGroups.get(candidate.contextKey)) !== null && _firstTokenGroups$get !== void 0 ? _firstTokenGroups$get : [];
|
|
898
|
+
group.push(candidate);
|
|
899
|
+
firstTokenGroups.set(candidate.contextKey, group);
|
|
900
|
+
}
|
|
901
|
+
for (const [contextKey, group] of firstTokenGroups) {
|
|
902
|
+
const boundary = getBoundaryLmState(contextKey);
|
|
903
|
+
if (!boundary) {
|
|
904
|
+
continue;
|
|
905
|
+
}
|
|
906
|
+
let maxLogit = -Infinity;
|
|
907
|
+
for (const candidate of group) {
|
|
908
|
+
var _candidate$canonicalT;
|
|
909
|
+
const tokenId = (_candidate$canonicalT = candidate.canonicalTokenIds) === null || _candidate$canonicalT === void 0 ? void 0 : _candidate$canonicalT[0];
|
|
910
|
+
const rawLogit = tokenId === undefined ? undefined : boundary.rawLogits[tokenId];
|
|
911
|
+
if (rawLogit !== undefined && Number.isFinite(rawLogit) && rawLogit > maxLogit) {
|
|
912
|
+
maxLogit = rawLogit;
|
|
913
|
+
}
|
|
914
|
+
}
|
|
915
|
+
if (!Number.isFinite(maxLogit)) {
|
|
916
|
+
continue;
|
|
917
|
+
}
|
|
918
|
+
for (const candidate of group) {
|
|
919
|
+
var _candidate$canonicalT2, _candidate$canonicalT3, _candidate$canonicalT4;
|
|
920
|
+
const tokenId = (_candidate$canonicalT2 = candidate.canonicalTokenIds) === null || _candidate$canonicalT2 === void 0 ? void 0 : _candidate$canonicalT2[0];
|
|
921
|
+
const rawLogit = tokenId === undefined ? undefined : boundary.rawLogits[tokenId];
|
|
922
|
+
if (rawLogit === undefined || !Number.isFinite(rawLogit)) {
|
|
923
|
+
continue;
|
|
924
|
+
}
|
|
925
|
+
const tokenCount = (_candidate$canonicalT3 = (_candidate$canonicalT4 = candidate.canonicalTokenIds) === null || _candidate$canonicalT4 === void 0 ? void 0 : _candidate$canonicalT4.length) !== null && _candidate$canonicalT3 !== void 0 ? _candidate$canonicalT3 : 0;
|
|
926
|
+
if (tokenId !== undefined && tokenCount === 1) {
|
|
927
|
+
const totalLogProbability = logSoftmaxAt(boundary.rawLogits, tokenId);
|
|
928
|
+
if (!Number.isFinite(totalLogProbability)) {
|
|
929
|
+
continue;
|
|
930
|
+
}
|
|
931
|
+
canonicalEvidence.set(candidate.word, {
|
|
932
|
+
contextKey,
|
|
933
|
+
meanTokenLogProbability: totalLogProbability,
|
|
934
|
+
score: 0,
|
|
935
|
+
separatorKind: 'whitespace',
|
|
936
|
+
source: 'canonical-full-surface',
|
|
937
|
+
totalLogProbability,
|
|
938
|
+
totalSurfaceCharCount: candidate.word.length,
|
|
939
|
+
totalTokenCount: 1,
|
|
940
|
+
verifiedCharCount: candidate.word.length,
|
|
941
|
+
verifiedTokenCount: 1
|
|
942
|
+
});
|
|
943
|
+
continue;
|
|
944
|
+
}
|
|
945
|
+
canonicalEvidence.set(candidate.word, {
|
|
946
|
+
contextKey,
|
|
947
|
+
rawLogit,
|
|
948
|
+
score: 0,
|
|
949
|
+
separatorKind: 'whitespace',
|
|
950
|
+
source: 'canonical-first-token',
|
|
951
|
+
totalSurfaceCharCount: candidate.word.length,
|
|
952
|
+
totalTokenCount: tokenCount,
|
|
953
|
+
verifiedCharCount: 0,
|
|
954
|
+
verifiedTokenCount: 1
|
|
955
|
+
});
|
|
956
|
+
}
|
|
957
|
+
}
|
|
439
958
|
const {
|
|
440
959
|
candidates: ranked,
|
|
441
960
|
grammarMeta,
|
|
442
961
|
pipelineDebug
|
|
443
|
-
} = rankCandidates(scoringCandidates, contextVector, w => getWordVector(w), prefixLmLogits,
|
|
444
|
-
|
|
445
|
-
|
|
962
|
+
} = rankCandidates(scoringCandidates, contextVector, w => getWordVector(w), prefixLmLogits, {
|
|
963
|
+
word: wordTrie.maxTenantFreq,
|
|
964
|
+
bigram: maxBigramFreq,
|
|
965
|
+
phrase: maxPhraseFreq
|
|
966
|
+
}, previousWord, surface => {
|
|
967
|
+
var _canonicalEvidence$ge;
|
|
968
|
+
return (_canonicalEvidence$ge = canonicalEvidence.get(surface)) !== null && _canonicalEvidence$ge !== void 0 ? _canonicalEvidence$ge : null;
|
|
969
|
+
});
|
|
970
|
+
const progressiveEligible = ranked.filter(candidate => {
|
|
971
|
+
const runtime = runtimeBySurface.get(candidate.word);
|
|
972
|
+
return (runtime === null || runtime === void 0 ? void 0 : runtime.canonicalTokenIds) !== null && (runtime === null || runtime === void 0 ? void 0 : runtime.canonicalTokenIds) !== undefined;
|
|
973
|
+
});
|
|
974
|
+
if (canonicalScoringSupported && progressiveEligible.length > 0) {
|
|
975
|
+
const byContext = new Map();
|
|
976
|
+
for (const candidate of progressiveEligible) {
|
|
977
|
+
var _byContext$get;
|
|
978
|
+
const runtime = runtimeBySurface.get(candidate.word);
|
|
979
|
+
if (!runtime || runtime.canonicalTokenIds === null) {
|
|
980
|
+
continue;
|
|
981
|
+
}
|
|
982
|
+
const group = (_byContext$get = byContext.get(runtime.contextKey)) !== null && _byContext$get !== void 0 ? _byContext$get : [];
|
|
983
|
+
group.push({
|
|
984
|
+
runtime,
|
|
985
|
+
rankHint: candidate.stage1Score
|
|
986
|
+
});
|
|
987
|
+
byContext.set(runtime.contextKey, group);
|
|
988
|
+
}
|
|
989
|
+
for (const [contextKey, group] of byContext) {
|
|
990
|
+
requestProgressiveSurfaceScores({
|
|
991
|
+
familyKey,
|
|
992
|
+
contextKey,
|
|
993
|
+
prompt: group[0].runtime.contextBeforeSurface,
|
|
994
|
+
candidates: group.map(({
|
|
995
|
+
runtime,
|
|
996
|
+
rankHint
|
|
997
|
+
}) => {
|
|
998
|
+
var _runtime$canonicalTok;
|
|
999
|
+
return {
|
|
1000
|
+
surface: runtime.word,
|
|
1001
|
+
tokenIds: (_runtime$canonicalTok = runtime.canonicalTokenIds) !== null && _runtime$canonicalTok !== void 0 ? _runtime$canonicalTok : [],
|
|
1002
|
+
rankHint
|
|
1003
|
+
};
|
|
1004
|
+
})
|
|
1005
|
+
});
|
|
1006
|
+
}
|
|
1007
|
+
}
|
|
1008
|
+
|
|
1009
|
+
// The one/two-character passes exist only to hide model latency. They may
|
|
1010
|
+
// prime and expand token groups above, but cannot commit UI.
|
|
1011
|
+
const displayPrefixReady = currentWord.length >= DISPLAY_MIN_PREFIX_LENGTH;
|
|
1012
|
+
|
|
1013
|
+
// ── Arbitration: full-surface evidence → plausibility → winner margin ──
|
|
1014
|
+
const canonicalLmSupported = canonicalScoringSupported;
|
|
1015
|
+
const hasExactEvidence = candidate => {
|
|
1016
|
+
var _candidate$lmEvidence;
|
|
1017
|
+
return ((_candidate$lmEvidence = candidate.lmEvidence) === null || _candidate$lmEvidence === void 0 ? void 0 : _candidate$lmEvidence.source) === 'canonical-full-surface' && candidate.lmEvidence.meanTokenLogProbability !== undefined && Number.isFinite(candidate.lmEvidence.meanTokenLogProbability);
|
|
1018
|
+
};
|
|
1019
|
+
|
|
1020
|
+
/**
|
|
1021
|
+
* The evidence this candidate is judged on: the summed log-probability of
|
|
1022
|
+
* the tokens that have been read, their per-token mean, and whether they
|
|
1023
|
+
* cover the whole surface.
|
|
1024
|
+
*
|
|
1025
|
+
* `total` is the quantity the posterior is built from — it is a sequence
|
|
1026
|
+
* log-likelihood, so it is comparable across surfaces of different lengths
|
|
1027
|
+
* in a way the mean is not. `mean` is retained for reporting and for the
|
|
1028
|
+
* oracle arms, which compare aggregation rules against each other.
|
|
1029
|
+
*
|
|
1030
|
+
* Every token read costs a round trip, so a surface longer than
|
|
1031
|
+
* `REQUIRED_VERIFIED_TOKENS` is judged on its leading tokens and its tail is
|
|
1032
|
+
* left unread. Callers compensate with a wider winner margin rather than
|
|
1033
|
+
* treating the two kinds of evidence as equivalent.
|
|
1034
|
+
*
|
|
1035
|
+
* This is the depth-unaware read, and it is what the pool below is built
|
|
1036
|
+
* from. Arbitration goes through `judgedEvidenceFor`, which adds the one
|
|
1037
|
+
* requirement that can only be stated once the pool is known: a surface
|
|
1038
|
+
* cannot be judged against members it has not yet been read level with.
|
|
1039
|
+
*/
|
|
1040
|
+
const readJudgedEvidence = candidate => {
|
|
1041
|
+
const evidence = candidate.lmEvidence;
|
|
1042
|
+
const exactMean = evidence === null || evidence === void 0 ? void 0 : evidence.meanTokenLogProbability;
|
|
1043
|
+
if (hasExactEvidence(candidate) && evidence && exactMean !== undefined) {
|
|
1044
|
+
var _evidence$totalLogPro;
|
|
1045
|
+
const total = (_evidence$totalLogPro = evidence.totalLogProbability) !== null && _evidence$totalLogPro !== void 0 ? _evidence$totalLogPro : exactMean * evidence.totalTokenCount;
|
|
1046
|
+
return Number.isFinite(total) ? {
|
|
1047
|
+
complete: true,
|
|
1048
|
+
mean: exactMean,
|
|
1049
|
+
total
|
|
1050
|
+
} : null;
|
|
1051
|
+
}
|
|
1052
|
+
const runtime = runtimeBySurface.get(candidate.word);
|
|
1053
|
+
if (!runtime || runtime.canonicalTokenIds === null) {
|
|
1054
|
+
return null;
|
|
1055
|
+
}
|
|
1056
|
+
const progressive = getProgressiveSurfaceEvidence(runtime.contextKey, candidate.word);
|
|
1057
|
+
if (!progressive || progressive.scoredTokenCount < REQUIRED_VERIFIED_TOKENS) {
|
|
1058
|
+
return null;
|
|
1059
|
+
}
|
|
1060
|
+
const total = progressive.totalLogProbability;
|
|
1061
|
+
const mean = total / progressive.scoredTokenCount;
|
|
1062
|
+
return Number.isFinite(mean) && Number.isFinite(total) ? {
|
|
1063
|
+
complete: false,
|
|
1064
|
+
mean,
|
|
1065
|
+
total
|
|
1066
|
+
} : null;
|
|
1067
|
+
};
|
|
1068
|
+
|
|
1069
|
+
// Normalise each context's shortlist into a posterior. `total` is a sequence
|
|
1070
|
+
// log-likelihood, so `exp(total - logSumExp(totals))` is the share of the
|
|
1071
|
+
// shortlist's probability mass the model puts on that surface.
|
|
1072
|
+
//
|
|
1073
|
+
// Unknown future token log-probabilities cannot exceed zero, so a partially
|
|
1074
|
+
// read candidate's total is an upper bound on its eventual total, and its
|
|
1075
|
+
// posterior an upper bound on its eventual posterior. That is what lets the
|
|
1076
|
+
// plausibility floor and the display gate be the same threshold — one
|
|
1077
|
+
// applied to the bound, one to the verified value — instead of two numbers
|
|
1078
|
+
// that have to be kept consistent by hand.
|
|
1079
|
+
//
|
|
1080
|
+
// Candidates with no evidence at all are left out of the sum rather than
|
|
1081
|
+
// defaulted. Any default would have to stand in for a log-probability, and a
|
|
1082
|
+
// value low enough not to distort the normaliser is indistinguishable from
|
|
1083
|
+
// omitting the candidate.
|
|
1084
|
+
const optimisticTotalByWord = new Map();
|
|
1085
|
+
const contextTotals = new Map();
|
|
1086
|
+
const contextSurfaces = new Map();
|
|
1087
|
+
// Counted before the total is looked up, so this is every candidate the
|
|
1088
|
+
// context could have scored rather than every candidate it did. The gap
|
|
1089
|
+
// between the two is what separates a context holding one match from a
|
|
1090
|
+
// context whose rivals have not come back yet.
|
|
1091
|
+
const contextRequestedCount = new Map();
|
|
1092
|
+
const bestTotalByContext = new Map();
|
|
1093
|
+
const bestCandidateByContext = new Map();
|
|
1094
|
+
for (const candidate of ranked) {
|
|
1095
|
+
var _contextRequestedCoun, _judged$total;
|
|
1096
|
+
const runtime = runtimeBySurface.get(candidate.word);
|
|
1097
|
+
if (!runtime || runtime.canonicalTokenIds === null) {
|
|
1098
|
+
continue;
|
|
1099
|
+
}
|
|
1100
|
+
contextRequestedCount.set(runtime.contextKey, ((_contextRequestedCoun = contextRequestedCount.get(runtime.contextKey)) !== null && _contextRequestedCoun !== void 0 ? _contextRequestedCoun : 0) + 1);
|
|
1101
|
+
const judged = readJudgedEvidence(candidate);
|
|
1102
|
+
const progressive = getProgressiveSurfaceEvidence(runtime.contextKey, candidate.word);
|
|
1103
|
+
// Once a candidate has been read far enough to judge, its verified total
|
|
1104
|
+
// replaces the bound.
|
|
1105
|
+
const optimisticTotal = (_judged$total = judged === null || judged === void 0 ? void 0 : judged.total) !== null && _judged$total !== void 0 ? _judged$total : progressive === null || progressive === void 0 ? void 0 : progressive.totalLogProbability;
|
|
1106
|
+
if (optimisticTotal === undefined || !Number.isFinite(optimisticTotal)) {
|
|
1107
|
+
continue;
|
|
1108
|
+
}
|
|
1109
|
+
optimisticTotalByWord.set(candidate.word, optimisticTotal);
|
|
1110
|
+
const totals = contextTotals.get(runtime.contextKey);
|
|
1111
|
+
const surfaces = contextSurfaces.get(runtime.contextKey);
|
|
1112
|
+
if (totals && surfaces) {
|
|
1113
|
+
totals.push(optimisticTotal);
|
|
1114
|
+
surfaces.push(candidate.word);
|
|
1115
|
+
} else {
|
|
1116
|
+
contextTotals.set(runtime.contextKey, [optimisticTotal]);
|
|
1117
|
+
contextSurfaces.set(runtime.contextKey, [candidate.word]);
|
|
1118
|
+
}
|
|
1119
|
+
const best = bestTotalByContext.get(runtime.contextKey);
|
|
1120
|
+
if (best === undefined || optimisticTotal > best) {
|
|
1121
|
+
bestTotalByContext.set(runtime.contextKey, optimisticTotal);
|
|
1122
|
+
bestCandidateByContext.set(runtime.contextKey, candidate);
|
|
1123
|
+
}
|
|
1124
|
+
}
|
|
1125
|
+
|
|
1126
|
+
/**
|
|
1127
|
+
* Whether a shorter member of the same pool is this surface's word-boundary
|
|
1128
|
+
* prefix — `happy path` where `happy` is also present.
|
|
1129
|
+
*
|
|
1130
|
+
* Only a multi-word surface can extend another, and a pool is a set, so this
|
|
1131
|
+
* costs one lookup per space rather than a comparison against every member.
|
|
1132
|
+
*/
|
|
1133
|
+
const extendsAPoolMember = (surface, pool) => {
|
|
1134
|
+
for (let space = surface.indexOf(' '); space !== -1; space = surface.indexOf(' ', space + 1)) {
|
|
1135
|
+
if (pool.has(surface.slice(0, space))) {
|
|
1136
|
+
return true;
|
|
1137
|
+
}
|
|
1138
|
+
}
|
|
1139
|
+
return false;
|
|
1140
|
+
};
|
|
1141
|
+
|
|
1142
|
+
// A sequence total only falls as more of the sequence is read, so a partial
|
|
1143
|
+
// sum over `k` tokens sits above the same surface's total over `m > k`. An
|
|
1144
|
+
// extension read less far than the member it continues therefore carries a
|
|
1145
|
+
// total above that member's — and because the chain rule narrows the
|
|
1146
|
+
// denominator to the pool's minimal members, `exp(total - normaliser)` comes
|
|
1147
|
+
// out above 1 for a surface whose own continuation has not been looked at.
|
|
1148
|
+
// It needs a three-token first word to happen, which 2.6% of served bigrams
|
|
1149
|
+
// have, and it inflates both the posterior the gate reads and the
|
|
1150
|
+
// `confidenceScore` every other candidate's margin is measured against.
|
|
1151
|
+
//
|
|
1152
|
+
// A surface's canonical tokenization begins with the tokenization of its own
|
|
1153
|
+
// leading words — the producer encodes `" " + surface` in one call and the
|
|
1154
|
+
// ByteLevel pre-tokenizer splits on word boundaries, so no merge crosses a
|
|
1155
|
+
// space — which is what makes both corrections below exact rather than
|
|
1156
|
+
// approximate.
|
|
1157
|
+
//
|
|
1158
|
+
// The total is capped at what it continues: `P(happy path)` cannot exceed
|
|
1159
|
+
// `P(happy)`. Shortest-first, so a three-word phrase is capped against a
|
|
1160
|
+
// two-word prefix that has already been capped itself.
|
|
1161
|
+
//
|
|
1162
|
+
// And the surface is held unjudgeable until it has been read level with what
|
|
1163
|
+
// it continues, because the cap alone would leave it looking exactly as
|
|
1164
|
+
// certain as its prefix while saying nothing about its own tail.
|
|
1165
|
+
const underReadExtensions = new Set();
|
|
1166
|
+
for (const [contextKey, surfaces] of contextSurfaces) {
|
|
1167
|
+
const pool = new Set(surfaces);
|
|
1168
|
+
for (const surface of [...surfaces].sort((a, b) => a.length - b.length)) {
|
|
1169
|
+
var _getProgressiveSurfac, _getProgressiveSurfac2, _runtimeBySurface$get4, _runtimeBySurface$get5, _runtimeBySurface$get6;
|
|
1170
|
+
const own = optimisticTotalByWord.get(surface);
|
|
1171
|
+
if (own === undefined) {
|
|
1172
|
+
continue;
|
|
1173
|
+
}
|
|
1174
|
+
let cap = Infinity;
|
|
1175
|
+
let continuedDepth = 0;
|
|
1176
|
+
for (let space = surface.indexOf(' '); space !== -1; space = surface.indexOf(' ', space + 1)) {
|
|
1177
|
+
var _runtimeBySurface$get, _runtimeBySurface$get2, _runtimeBySurface$get3;
|
|
1178
|
+
const prefix = surface.slice(0, space);
|
|
1179
|
+
if (!pool.has(prefix)) {
|
|
1180
|
+
continue;
|
|
1181
|
+
}
|
|
1182
|
+
const prefixTotal = optimisticTotalByWord.get(prefix);
|
|
1183
|
+
if (prefixTotal !== undefined && prefixTotal < cap) {
|
|
1184
|
+
cap = prefixTotal;
|
|
1185
|
+
}
|
|
1186
|
+
const prefixDepth = (_runtimeBySurface$get = (_runtimeBySurface$get2 = runtimeBySurface.get(prefix)) === null || _runtimeBySurface$get2 === void 0 ? void 0 : (_runtimeBySurface$get3 = _runtimeBySurface$get2.canonicalTokenIds) === null || _runtimeBySurface$get3 === void 0 ? void 0 : _runtimeBySurface$get3.length) !== null && _runtimeBySurface$get !== void 0 ? _runtimeBySurface$get : 0;
|
|
1187
|
+
if (prefixDepth > continuedDepth) {
|
|
1188
|
+
continuedDepth = prefixDepth;
|
|
1189
|
+
}
|
|
1190
|
+
}
|
|
1191
|
+
if (own > cap) {
|
|
1192
|
+
optimisticTotalByWord.set(surface, cap);
|
|
1193
|
+
}
|
|
1194
|
+
const scoredDepth = (_getProgressiveSurfac = (_getProgressiveSurfac2 = getProgressiveSurfaceEvidence(contextKey, surface)) === null || _getProgressiveSurfac2 === void 0 ? void 0 : _getProgressiveSurfac2.scoredTokenCount) !== null && _getProgressiveSurfac !== void 0 ? _getProgressiveSurfac : 0;
|
|
1195
|
+
const surfaceDepth = (_runtimeBySurface$get4 = (_runtimeBySurface$get5 = runtimeBySurface.get(surface)) === null || _runtimeBySurface$get5 === void 0 ? void 0 : (_runtimeBySurface$get6 = _runtimeBySurface$get5.canonicalTokenIds) === null || _runtimeBySurface$get6 === void 0 ? void 0 : _runtimeBySurface$get6.length) !== null && _runtimeBySurface$get4 !== void 0 ? _runtimeBySurface$get4 : 0;
|
|
1196
|
+
if (scoredDepth < continuedDepth && scoredDepth < surfaceDepth) {
|
|
1197
|
+
underReadExtensions.add(surface);
|
|
1198
|
+
}
|
|
1199
|
+
}
|
|
1200
|
+
}
|
|
1201
|
+
|
|
1202
|
+
/**
|
|
1203
|
+
* The evidence arbitration judges a candidate on.
|
|
1204
|
+
*
|
|
1205
|
+
* Wraps the depth-unaware read with the pool-relative requirement: a surface
|
|
1206
|
+
* that continues another pool member is not judgeable until it has been read
|
|
1207
|
+
* level with it, so the two totals being compared are taken at comparable
|
|
1208
|
+
* depths.
|
|
1209
|
+
*/
|
|
1210
|
+
const judgedEvidenceFor = candidate => underReadExtensions.has(candidate.word) ? null : readJudgedEvidence(candidate);
|
|
1211
|
+
const hasJudgeableEvidence = candidate => judgedEvidenceFor(candidate) !== null;
|
|
1212
|
+
|
|
1213
|
+
// Normalise over the pool's minimal members only, and score everyone —
|
|
1214
|
+
// extensions included — against that.
|
|
1215
|
+
//
|
|
1216
|
+
// A sequence total is its prefix's total plus a log-probability that cannot
|
|
1217
|
+
// be positive, so summing a surface and its own extension double-counts:
|
|
1218
|
+
// `exp(total)` for `happy` already contains every continuation of `happy`,
|
|
1219
|
+
// `happy path` among them. Dividing one pool's mass between the two capped
|
|
1220
|
+
// the shorter form at half however certain it was, and the longer form below
|
|
1221
|
+
// that — both under gates neither could then clear, for a reason that was
|
|
1222
|
+
// arithmetic rather than evidence.
|
|
1223
|
+
//
|
|
1224
|
+
// Excluding extensions from the denominator is the chain rule: the minimal
|
|
1225
|
+
// members partition the mass, and an extension's share of that same
|
|
1226
|
+
// denominator is `P(prefix) * P(continuation | prefix)`, which is exactly
|
|
1227
|
+
// what a multi-word suggestion should be held to. Extensions stay in
|
|
1228
|
+
// `contextTotals`, so how contested a context is still counts every scored
|
|
1229
|
+
// candidate.
|
|
1230
|
+
const logSumExpByContext = new Map();
|
|
1231
|
+
for (const [contextKey, surfaces] of contextSurfaces) {
|
|
1232
|
+
const pool = new Set(surfaces);
|
|
1233
|
+
const minimalTotals = [];
|
|
1234
|
+
for (const surface of surfaces) {
|
|
1235
|
+
const total = optimisticTotalByWord.get(surface);
|
|
1236
|
+
if (total !== undefined && !extendsAPoolMember(surface, pool)) {
|
|
1237
|
+
minimalTotals.push(total);
|
|
1238
|
+
}
|
|
1239
|
+
}
|
|
1240
|
+
// An extension is strictly longer than what it extends, so the shortest
|
|
1241
|
+
// member of any non-empty pool is always minimal and this is never empty.
|
|
1242
|
+
logSumExpByContext.set(contextKey, logSumExp(minimalTotals));
|
|
1243
|
+
}
|
|
1244
|
+
|
|
1245
|
+
/**
|
|
1246
|
+
* A candidate's share of its context shortlist's probability mass.
|
|
1247
|
+
*
|
|
1248
|
+
* Pass an optimistic (partially read) total for an upper bound on the
|
|
1249
|
+
* eventual posterior, or a verified total for the posterior itself.
|
|
1250
|
+
*/
|
|
1251
|
+
const posteriorFor = (candidate, total) => {
|
|
1252
|
+
const runtime = runtimeBySurface.get(candidate.word);
|
|
1253
|
+
const normalizer = runtime ? logSumExpByContext.get(runtime.contextKey) : undefined;
|
|
1254
|
+
if (total === undefined || normalizer === undefined || !Number.isFinite(normalizer)) {
|
|
1255
|
+
return 0;
|
|
1256
|
+
}
|
|
1257
|
+
return Math.exp(total - normalizer);
|
|
1258
|
+
};
|
|
1259
|
+
const optimisticPosterior = candidate => posteriorFor(candidate, optimisticTotalByWord.get(candidate.word));
|
|
1260
|
+
const judgedPosterior = candidate => {
|
|
1261
|
+
var _judgedEvidenceFor;
|
|
1262
|
+
return posteriorFor(candidate, (_judgedEvidenceFor = judgedEvidenceFor(candidate)) === null || _judgedEvidenceFor === void 0 ? void 0 : _judgedEvidenceFor.total);
|
|
1263
|
+
};
|
|
1264
|
+
|
|
1265
|
+
// A candidate stays in the race for as long as its optimistic posterior
|
|
1266
|
+
// could still clear the gate it will be held to. The bound only falls as
|
|
1267
|
+
// more tokens are read, so nothing dropped here could have gone on to win.
|
|
1268
|
+
const couldClearGate = candidate => optimisticPosterior(candidate) >= MIN_LM_POSTERIOR[candidate.termType];
|
|
1269
|
+
const passesLmFloor = candidate => judgedEvidenceFor(candidate) !== null && couldClearGate(candidate);
|
|
1270
|
+
const hasRequiredEvidence = candidate => {
|
|
1271
|
+
var _candidate$lmEvidence2;
|
|
1272
|
+
if (canonicalLmSupported) {
|
|
1273
|
+
return passesLmFloor(candidate);
|
|
1274
|
+
}
|
|
1275
|
+
return candidate.termType === 'word' && ((_candidate$lmEvidence2 = candidate.lmEvidence) === null || _candidate$lmEvidence2 === void 0 ? void 0 : _candidate$lmEvidence2.source) === 'network-logit';
|
|
1276
|
+
};
|
|
1277
|
+
|
|
1278
|
+
// ── Stabilization guards (QI-2) ──────────────────────────────────────────
|
|
1279
|
+
// Whole-surface repetition: drop a candidate whose full surface already equals
|
|
1280
|
+
// the run of tokens immediately before the cursor — accepting it would
|
|
1281
|
+
// duplicate what was just typed (`end to end` → `end to end to end`).
|
|
1282
|
+
const beforeTokens = tokenize(trimmed);
|
|
1283
|
+
const duplicatesPreceding = c => {
|
|
1284
|
+
const surfaceTokens = tokenize(c.word);
|
|
1285
|
+
const n = surfaceTokens.length;
|
|
1286
|
+
if (n === 0 || beforeTokens.length < n) {
|
|
1287
|
+
return false;
|
|
1288
|
+
}
|
|
1289
|
+
for (let i = 0; i < n; i++) {
|
|
1290
|
+
if (beforeTokens[beforeTokens.length - n + i] !== surfaceTokens[i]) {
|
|
1291
|
+
return false;
|
|
1292
|
+
}
|
|
1293
|
+
}
|
|
1294
|
+
return true;
|
|
1295
|
+
};
|
|
1296
|
+
// Post-accept cooldown: don't re-offer the surface the user just accepted while
|
|
1297
|
+
// its cooldown is still active (see cooldown advance near t0).
|
|
1298
|
+
const isCooledDown = c => cooledSurface !== null && c.word.toLowerCase() === cooledSurface;
|
|
1299
|
+
const isStabilized = candidate => !duplicatesPreceding(candidate) && !isCooledDown(candidate);
|
|
1300
|
+
// A candidate the user has all but finished typing is not worth a ghost, and
|
|
1301
|
+
// a candidate we would never show is not worth waiting for either.
|
|
1302
|
+
const suggestionLengthFor = candidate => {
|
|
1303
|
+
var _prefixLenByWord$get;
|
|
1304
|
+
return candidate.word.length - ((_prefixLenByWord$get = prefixLenByWord.get(candidate.word)) !== null && _prefixLenByWord$get !== void 0 ? _prefixLenByWord$get : currentWord.length);
|
|
1305
|
+
};
|
|
1306
|
+
const isWorthShowing = candidate => suggestionLengthFor(candidate) >= MIN_SUGGESTION_LENGTH;
|
|
1307
|
+
const evidenceBacked = ranked.filter(candidate => hasRequiredEvidence(candidate) && isStabilized(candidate));
|
|
1308
|
+
const confidenceScore = candidate => {
|
|
1309
|
+
if (!canonicalLmSupported) {
|
|
1310
|
+
return candidate.finalScore;
|
|
1311
|
+
}
|
|
1312
|
+
const runtime = runtimeBySurface.get(candidate.word);
|
|
1313
|
+
if ((runtime === null || runtime === void 0 ? void 0 : runtime.canonicalTokenIds) === null || !optimisticTotalByWord.has(candidate.word)) {
|
|
1314
|
+
return candidate.stage1Score;
|
|
1315
|
+
}
|
|
1316
|
+
return STAGE1_WEIGHT * candidate.stage1Score + STAGE2_WEIGHT * optimisticPosterior(candidate);
|
|
1317
|
+
};
|
|
1318
|
+
const exactConfidenceScore = candidate => {
|
|
1319
|
+
if (!canonicalLmSupported || judgedEvidenceFor(candidate) === null) {
|
|
1320
|
+
return candidate.finalScore;
|
|
1321
|
+
}
|
|
1322
|
+
return STAGE1_WEIGHT * candidate.stage1Score + STAGE2_WEIGHT * judgedPosterior(candidate);
|
|
1323
|
+
};
|
|
1324
|
+
|
|
1325
|
+
/**
|
|
1326
|
+
* How many candidates in this one's context were scored at all.
|
|
1327
|
+
*
|
|
1328
|
+
* Read off pool membership, which counts every candidate that contributed a
|
|
1329
|
+
* total, rather than off the normaliser, which the chain rule narrows to the
|
|
1330
|
+
* pool's minimal members.
|
|
1331
|
+
*/
|
|
1332
|
+
const scoredPoolSize = candidate => {
|
|
1333
|
+
var _runtimeBySurface$get7, _contextTotals$get$le, _contextTotals$get;
|
|
1334
|
+
const contextKey = (_runtimeBySurface$get7 = runtimeBySurface.get(candidate.word)) === null || _runtimeBySurface$get7 === void 0 ? void 0 : _runtimeBySurface$get7.contextKey;
|
|
1335
|
+
return contextKey === undefined ? 0 : (_contextTotals$get$le = (_contextTotals$get = contextTotals.get(contextKey)) === null || _contextTotals$get === void 0 ? void 0 : _contextTotals$get.length) !== null && _contextTotals$get$le !== void 0 ? _contextTotals$get$le : 0;
|
|
1336
|
+
};
|
|
1337
|
+
|
|
1338
|
+
/**
|
|
1339
|
+
* How many candidates the context held before any of them were scored.
|
|
1340
|
+
*
|
|
1341
|
+
* A pool of one means two opposite things. Either the vocabulary offered a
|
|
1342
|
+
* single continuation of what was typed, which is the least contested case
|
|
1343
|
+
* there is; or rivals were offered and have not been read yet, which is the
|
|
1344
|
+
* least informed. Only the second deserves refusing, and the two are
|
|
1345
|
+
* distinguishable exactly here.
|
|
1346
|
+
*/
|
|
1347
|
+
const requestedPoolSize = candidate => {
|
|
1348
|
+
var _runtimeBySurface$get8, _contextRequestedCoun2;
|
|
1349
|
+
const contextKey = (_runtimeBySurface$get8 = runtimeBySurface.get(candidate.word)) === null || _runtimeBySurface$get8 === void 0 ? void 0 : _runtimeBySurface$get8.contextKey;
|
|
1350
|
+
return contextKey === undefined ? 0 : (_contextRequestedCoun2 = contextRequestedCount.get(contextKey)) !== null && _contextRequestedCoun2 !== void 0 ? _contextRequestedCoun2 : 0;
|
|
1351
|
+
};
|
|
1352
|
+
|
|
1353
|
+
// A suppressed short completion still counts as competition below, so losing
|
|
1354
|
+
// to one abstains rather than promoting the runner-up in its place.
|
|
1355
|
+
const gateCleared = evidenceBacked.filter(isWorthShowing).map(candidate => ({
|
|
1356
|
+
candidate,
|
|
1357
|
+
posterior: judgedPosterior(candidate),
|
|
1358
|
+
score: exactConfidenceScore(candidate)
|
|
1359
|
+
}))
|
|
1360
|
+
// The gate is the model's own confidence in the surface; the blended score
|
|
1361
|
+
// only orders what has already cleared it, so a strong corpus prior can no
|
|
1362
|
+
// longer carry a surface the model is unsure of onto the screen.
|
|
1363
|
+
.filter(({
|
|
1364
|
+
candidate,
|
|
1365
|
+
posterior
|
|
1366
|
+
}) => posterior >= MIN_LM_POSTERIOR[candidate.termType]);
|
|
1367
|
+
/**
|
|
1368
|
+
* Whether the model finds the surface plausible on its own terms.
|
|
1369
|
+
*
|
|
1370
|
+
* The gate above asks which candidate won its pool; this asks whether
|
|
1371
|
+
* winning it meant anything. The two come apart exactly where a pool is
|
|
1372
|
+
* thin — a shortlist of one hands its only member 1.0 by construction — and
|
|
1373
|
+
* a relative test can never see through that however it is tuned.
|
|
1374
|
+
*
|
|
1375
|
+
* Waived without canonical scoring, where there is no judged mean to test
|
|
1376
|
+
* and the network-logit path would otherwise refuse everything.
|
|
1377
|
+
*/
|
|
1378
|
+
const isPlausibleSurface = candidate => {
|
|
1379
|
+
var _judgedEvidenceFor2;
|
|
1380
|
+
if (!canonicalLmSupported) {
|
|
1381
|
+
return true;
|
|
1382
|
+
}
|
|
1383
|
+
const mean = (_judgedEvidenceFor2 = judgedEvidenceFor(candidate)) === null || _judgedEvidenceFor2 === void 0 ? void 0 : _judgedEvidenceFor2.mean;
|
|
1384
|
+
return mean !== undefined && mean >= MIN_MEAN_TOKEN_LOG_PROBABILITY;
|
|
1385
|
+
};
|
|
1386
|
+
// Kept as its own stage rather than folded into the gate so the three
|
|
1387
|
+
// populations stay separable in the abstain cascade: cleared its pool and was
|
|
1388
|
+
// implausible, was plausible and had nothing to clear the pool against, or
|
|
1389
|
+
// cleared both. A candidate refused here stays in `ranked` and so still
|
|
1390
|
+
// counts as competition below — promoting the runner-up in place of an
|
|
1391
|
+
// implausible leader would show something worse, not something better.
|
|
1392
|
+
const plausible = gateCleared.filter(({
|
|
1393
|
+
candidate
|
|
1394
|
+
}) => isPlausibleSurface(candidate));
|
|
1395
|
+
// Applied after the gate rather than folded into it, so the two populations
|
|
1396
|
+
// stay separable: a surface refused here cleared its threshold and was
|
|
1397
|
+
// refused for having had nothing to clear it against.
|
|
1398
|
+
const eligible = plausible.filter(({
|
|
1399
|
+
candidate
|
|
1400
|
+
}) => !canonicalLmSupported || scoredPoolSize(candidate) >= MIN_SCORED_POOL_SIZE || requestedPoolSize(candidate) <= 1).sort((a, b) => b.score - a.score);
|
|
1401
|
+
const selected = (_eligible$ = eligible[0]) === null || _eligible$ === void 0 ? void 0 : _eligible$.candidate;
|
|
1402
|
+
const selectedDisplayScore = (_eligible$0$score = (_eligible$2 = eligible[0]) === null || _eligible$2 === void 0 ? void 0 : _eligible$2.score) !== null && _eligible$0$score !== void 0 ? _eligible$0$score : 0;
|
|
1403
|
+
const selectedEvidence = selected && hasRequiredEvidence(selected) ? selected.lmEvidence : null;
|
|
1404
|
+
/**
|
|
1405
|
+
* Whether `longer` is `shorter` continued past a word boundary, in the same
|
|
1406
|
+
* normaliser.
|
|
1407
|
+
*
|
|
1408
|
+
* Shared by the two places that have to agree on what an extension is: the
|
|
1409
|
+
* chain rule, which stops dividing a pool's mass between a sequence and its
|
|
1410
|
+
* own prefix, and the winner margin below, which stops treating one as the
|
|
1411
|
+
* other's rival. They were the same category error and are now the same test.
|
|
1412
|
+
*/
|
|
1413
|
+
const extendsInSamePool = (shorter, longer) => {
|
|
1414
|
+
var _runtimeBySurface$get9, _runtimeBySurface$get0;
|
|
1415
|
+
if (longer.word === shorter.word || !optimisticTotalByWord.has(longer.word)) {
|
|
1416
|
+
return false;
|
|
1417
|
+
}
|
|
1418
|
+
const pool = (_runtimeBySurface$get9 = runtimeBySurface.get(shorter.word)) === null || _runtimeBySurface$get9 === void 0 ? void 0 : _runtimeBySurface$get9.contextKey;
|
|
1419
|
+
if (pool === undefined || ((_runtimeBySurface$get0 = runtimeBySurface.get(longer.word)) === null || _runtimeBySurface$get0 === void 0 ? void 0 : _runtimeBySurface$get0.contextKey) !== pool) {
|
|
1420
|
+
return false;
|
|
1421
|
+
}
|
|
1422
|
+
return longer.word.length > shorter.word.length && longer.word.startsWith(shorter.word) && longer.word[shorter.word.length] === ' ';
|
|
1423
|
+
};
|
|
1424
|
+
// A candidate that extends the selection is not competing with it. Whichever
|
|
1425
|
+
// continuation the user meant, the shorter surface is a correct ghost — it is
|
|
1426
|
+
// the prefix of both — so the margin has nothing to arbitrate and charging the
|
|
1427
|
+
// selection for its own extension abstains on a case that could not be wrong.
|
|
1428
|
+
// The chain rule already removed this from the denominator; leaving it in the
|
|
1429
|
+
// margin meant a nested leader cleared its gate and then lost to the candidate
|
|
1430
|
+
// that had just been freed from dividing its mass. It penalised bigrams and
|
|
1431
|
+
// phrases specifically, because a nested pool is where they mostly appear.
|
|
1432
|
+
const runnerUpScore = selected ? Math.max(...ranked.filter(candidate => candidate.word !== selected.word && isStabilized(candidate) && !extendsInSamePool(selected, candidate)).map(confidenceScore), 0) : 0;
|
|
1433
|
+
const winnerMargin = selected ? selectedDisplayScore - runnerUpScore : 0;
|
|
1434
|
+
const hasMissingArtifactCompetitor = canonicalLmSupported && ranked.some(candidate => {
|
|
1435
|
+
const runtime = runtimeBySurface.get(candidate.word);
|
|
1436
|
+
return (runtime === null || runtime === void 0 ? void 0 : runtime.separatorKind) === 'whitespace' && runtime.canonicalTokenIds === null;
|
|
1437
|
+
});
|
|
1438
|
+
// A candidate with canonical tokens but no evidence at all cannot join the
|
|
1439
|
+
// posterior: it has no likelihood to contribute, and any stand-in value would
|
|
1440
|
+
// distort the normaliser for every other candidate in its context. Absent
|
|
1441
|
+
// evidence is not evidence of absence though — the context's boundary may
|
|
1442
|
+
// simply not be primed yet — so it holds the ghost back instead of being
|
|
1443
|
+
// silently ignored. In a primed context every candidate has at least
|
|
1444
|
+
// first-token evidence, so this only fires while a context is still cold.
|
|
1445
|
+
const hasUnscoredCompetitor = canonicalLmSupported && ranked.some(candidate => {
|
|
1446
|
+
const runtime = runtimeBySurface.get(candidate.word);
|
|
1447
|
+
return candidate.word !== (selected === null || selected === void 0 ? void 0 : selected.word) && (runtime === null || runtime === void 0 ? void 0 : runtime.canonicalTokenIds) !== null && (runtime === null || runtime === void 0 ? void 0 : runtime.canonicalTokenIds) !== undefined && !optimisticTotalByWord.has(candidate.word) && isStabilized(candidate) && isWorthShowing(candidate);
|
|
1448
|
+
});
|
|
1449
|
+
// A rival only holds the ghost back while it is still too unread to judge.
|
|
1450
|
+
// Under full-surface evidence that meant any long surface blocked everything
|
|
1451
|
+
// until every one of its tokens had been paid for, which abstained far more
|
|
1452
|
+
// often than it ever changed the winner. A rival now becomes judgeable after
|
|
1453
|
+
// `REQUIRED_VERIFIED_TOKENS`, so this settles within the budget.
|
|
1454
|
+
const hasUnresolvedPotential = canonicalLmSupported && ranked.some(candidate => {
|
|
1455
|
+
const runtime = runtimeBySurface.get(candidate.word);
|
|
1456
|
+
return candidate.word !== (selected === null || selected === void 0 ? void 0 : selected.word) && (runtime === null || runtime === void 0 ? void 0 : runtime.canonicalTokenIds) !== null && (runtime === null || runtime === void 0 ? void 0 : runtime.canonicalTokenIds) !== undefined && !hasJudgeableEvidence(candidate) && couldClearGate(candidate) && isStabilized(candidate) && isWorthShowing(candidate);
|
|
1457
|
+
});
|
|
1458
|
+
const requiredWinnerMargin = MIN_WINNER_MARGIN + (selected && ((_judgedEvidenceFor3 = judgedEvidenceFor(selected)) === null || _judgedEvidenceFor3 === void 0 ? void 0 : _judgedEvidenceFor3.complete) === false ? PARTIAL_EVIDENCE_MARGIN_PREMIUM : 0);
|
|
1459
|
+
// Everything the display decision needs except the veto itself. Splitting it
|
|
1460
|
+
// out is what lets the veto be priced: the value here at the moment the veto
|
|
1461
|
+
// fires is exactly the ghost the veto cost us.
|
|
1462
|
+
const clearsMarginBeforeColdVeto = selected !== undefined && !hasMissingArtifactCompetitor && winnerMargin >= requiredWinnerMargin;
|
|
1463
|
+
const clearsWinnerMargin = clearsMarginBeforeColdVeto && !hasUnscoredCompetitor;
|
|
1464
|
+
const suggestion = displayPrefixReady && selected && clearsWinnerMargin ? selected.word.slice((_prefixLenByWord$get2 = prefixLenByWord.get(selected.word)) !== null && _prefixLenByWord$get2 !== void 0 ? _prefixLenByWord$get2 : currentWord.length) : null;
|
|
1465
|
+
|
|
1466
|
+
// Which constraint bound. Computed on every evaluation rather than only under
|
|
1467
|
+
// debug, because it is counted for the session as well as printed, and
|
|
1468
|
+
// deriving the debug header from it keeps the two from disagreeing.
|
|
1469
|
+
const resolveAbstainReason = () => {
|
|
1470
|
+
if (suggestion !== null && suggestion.length > 0) {
|
|
1471
|
+
return null;
|
|
1472
|
+
}
|
|
1473
|
+
if (!displayPrefixReady) {
|
|
1474
|
+
return 'prefetch';
|
|
1475
|
+
}
|
|
1476
|
+
if (ranked.length === 0) {
|
|
1477
|
+
return 'no-candidate';
|
|
1478
|
+
}
|
|
1479
|
+
if (hasMissingArtifactCompetitor) {
|
|
1480
|
+
return 'missing-artifact';
|
|
1481
|
+
}
|
|
1482
|
+
if (hasUnscoredCompetitor) {
|
|
1483
|
+
return 'cold-competitor';
|
|
1484
|
+
}
|
|
1485
|
+
if (hasUnresolvedPotential && !clearsWinnerMargin) {
|
|
1486
|
+
return 'unresolved-rival';
|
|
1487
|
+
}
|
|
1488
|
+
if (eligible.length > 0) {
|
|
1489
|
+
return selected && !clearsWinnerMargin ? 'winner-margin' : 'empty-completion';
|
|
1490
|
+
}
|
|
1491
|
+
if (plausible.length > 0) {
|
|
1492
|
+
// Cleared its gate, was plausible on its own terms, and was refused for
|
|
1493
|
+
// the shortlist it cleared that gate against holding nobody else.
|
|
1494
|
+
return 'lone-candidate';
|
|
1495
|
+
}
|
|
1496
|
+
if (gateCleared.length > 0) {
|
|
1497
|
+
// Held the largest share of its shortlist and still was not a surface
|
|
1498
|
+
// the model found plausible — which is only possible because a share is
|
|
1499
|
+
// relative and this is not.
|
|
1500
|
+
return 'implausible-surface';
|
|
1501
|
+
}
|
|
1502
|
+
if (evidenceBacked.length > 0 && evidenceBacked.every(candidate => !isWorthShowing(candidate))) {
|
|
1503
|
+
return 'short-completion';
|
|
1504
|
+
}
|
|
1505
|
+
// The floor and the gate are one threshold, applied to the bound and to
|
|
1506
|
+
// the verified value, so a candidate short of it is dropped before
|
|
1507
|
+
// `evidenceBacked` is built. Asking whether anything was judgeable
|
|
1508
|
+
// separates a gate that rejected read candidates from a context where
|
|
1509
|
+
// nothing was read at all — the first is a threshold to calibrate, the
|
|
1510
|
+
// second is scheduling.
|
|
1511
|
+
return ranked.some(hasJudgeableEvidence) ? 'below-posterior-gate' : 'no-evidence';
|
|
1512
|
+
};
|
|
1513
|
+
const abstainReason = resolveAbstainReason();
|
|
1514
|
+
|
|
1515
|
+
// The leader is the best-supported candidate, not the selected one: an
|
|
1516
|
+
// evaluation that showed nothing is exactly the one whose posterior needs
|
|
1517
|
+
// recording, and it has no selection to report.
|
|
1518
|
+
const posteriorLeader = ranked.reduce((best, candidate) => {
|
|
1519
|
+
const posterior = optimisticPosterior(candidate);
|
|
1520
|
+
return posterior > 0 && (best === null || posterior > best.posterior) ? {
|
|
1521
|
+
candidate,
|
|
1522
|
+
posterior
|
|
1523
|
+
} : best;
|
|
1524
|
+
}, null);
|
|
1525
|
+
/**
|
|
1526
|
+
* The longer surface in the leader's normaliser that extends the given
|
|
1527
|
+
* candidate, if the pool holds one.
|
|
1528
|
+
*
|
|
1529
|
+
* `logSumExp` divides one pool's mass between a sequence and its own prefix,
|
|
1530
|
+
* and the longer total is the shorter one plus a log-probability that cannot
|
|
1531
|
+
* be positive — so the longer form holds at most half, or at most a third
|
|
1532
|
+
* where both shorter forms are present. Both sit under the gate it is held
|
|
1533
|
+
* to, so it cannot display however certain its continuation is.
|
|
1534
|
+
*
|
|
1535
|
+
* Asked from the shorter form because that is the one that leads: the
|
|
1536
|
+
* extending candidate is strictly lower in the same pool and so can never be
|
|
1537
|
+
* the leader.
|
|
1538
|
+
*/
|
|
1539
|
+
const poolExtensionOf = shorter => ranked.find(candidate => extendsInSamePool(shorter, candidate));
|
|
446
1540
|
if (isAutocompleteDebugEnabled()) {
|
|
1541
|
+
var _posteriorLeader$cand, _posteriorLeader$post, _selectedEvidence$mea, _selectedEvidence$mea2, _acceptCooldown$predi, _acceptCooldown;
|
|
1542
|
+
const verbose = isAutocompleteDebugVerbose();
|
|
447
1543
|
const latencyMs = performance.now() - t0;
|
|
448
1544
|
const tokens = tokenize(trimmed);
|
|
449
1545
|
const contextWords = tokens.slice(-CONTEXT_WORDS);
|
|
450
|
-
|
|
451
|
-
|
|
1546
|
+
|
|
1547
|
+
// Decision drives the (collapsed) group header. Abstains carry the reason
|
|
1548
|
+
// the session counters recorded, plus the numbers behind it, so it is clear
|
|
1549
|
+
// *why* nothing showed without expanding the group.
|
|
1550
|
+
const abstainDetail = {
|
|
1551
|
+
'below-posterior-gate': `posterior below ${MIN_LM_POSTERIOR[((_posteriorLeader$cand = posteriorLeader === null || posteriorLeader === void 0 ? void 0 : posteriorLeader.candidate) !== null && _posteriorLeader$cand !== void 0 ? _posteriorLeader$cand : ranked[0]).termType]} (best ${((_posteriorLeader$post = posteriorLeader === null || posteriorLeader === void 0 ? void 0 : posteriorLeader.posterior) !== null && _posteriorLeader$post !== void 0 ? _posteriorLeader$post : 0).toFixed(2)})`,
|
|
1552
|
+
'cold-competitor': 'competitor has no LM evidence yet',
|
|
1553
|
+
'empty-completion': 'empty completion',
|
|
1554
|
+
'implausible-surface': `mean per-token log-probability below ${MIN_MEAN_TOKEN_LOG_PROBABILITY} (best ${gateCleared.map(({
|
|
1555
|
+
candidate
|
|
1556
|
+
}) => {
|
|
1557
|
+
var _judgedEvidenceFor$me, _judgedEvidenceFor4;
|
|
1558
|
+
return (_judgedEvidenceFor$me = (_judgedEvidenceFor4 = judgedEvidenceFor(candidate)) === null || _judgedEvidenceFor4 === void 0 ? void 0 : _judgedEvidenceFor4.mean) !== null && _judgedEvidenceFor$me !== void 0 ? _judgedEvidenceFor$me : -Infinity;
|
|
1559
|
+
}).reduce((best, mean) => Math.max(best, mean), -Infinity).toFixed(2)})`,
|
|
1560
|
+
'lone-candidate': `cleared its gate against fewer than ${MIN_SCORED_POOL_SIZE} scored candidates, rivals unread`,
|
|
1561
|
+
'missing-artifact': 'canonical artifact coverage missing',
|
|
1562
|
+
'no-candidate': 'nothing cleared scoring',
|
|
1563
|
+
'no-evidence': 'full-surface evidence absent',
|
|
1564
|
+
prefetch: `prefetch: ${currentWord.length}/${DISPLAY_MIN_PREFIX_LENGTH} chars`,
|
|
1565
|
+
'short-completion': `completion shorter than ${MIN_SUGGESTION_LENGTH} chars`,
|
|
1566
|
+
'unresolved-rival': 'expanding plausible token-prefix groups',
|
|
1567
|
+
'winner-margin': `winner margin ${winnerMargin.toFixed(2)} < ${requiredWinnerMargin.toFixed(2)}`
|
|
1568
|
+
};
|
|
1569
|
+
const decision = abstainReason === null ? `✨ "${suggestion !== null && suggestion !== void 0 ? suggestion : ''}"` : abstainReason === 'prefetch' ? `⏳ ${abstainDetail.prefetch}` : `— abstain: ${abstainDetail[abstainReason]}`;
|
|
452
1570
|
lastPredictionDebug = {
|
|
1571
|
+
awaitingAsyncEvidence: hasUnresolvedPotential && !clearsWinnerMargin,
|
|
453
1572
|
textBefore: trimmed,
|
|
454
1573
|
currentWord,
|
|
1574
|
+
decision,
|
|
455
1575
|
mode,
|
|
456
1576
|
contextWords,
|
|
457
1577
|
topCandidates: ranked.slice(0, 5).map(r => ({
|
|
@@ -464,62 +1584,179 @@ export const predict = textBefore => {
|
|
|
464
1584
|
suggestion: suggestion && suggestion.length > 0 ? suggestion : null
|
|
465
1585
|
};
|
|
466
1586
|
|
|
467
|
-
//
|
|
1587
|
+
// Mode describes the semantic-vector source without implying that a
|
|
1588
|
+
// network backend ran; the snapshot may come from the local MLC embedder.
|
|
468
1589
|
const slowLaneVec = getStoredContextVector();
|
|
469
1590
|
const isUsingSlowLaneVector = slowLaneVec !== null && vectorStore !== null && slowLaneVec.length === vectorStore.dim;
|
|
470
|
-
const modeLabel = !contextVector ? 'COLD' : isUsingSlowLaneVector ? 'WARM(
|
|
471
|
-
const modeColor = modeLabel === 'WARM(
|
|
1591
|
+
const modeLabel = !contextVector ? 'COLD' : isUsingSlowLaneVector ? 'WARM(semantic)' : 'WARM(local-avg)';
|
|
1592
|
+
const modeColor = modeLabel === 'WARM(semantic)' ? CTC_STYLES.good : modeLabel === 'WARM(local-avg)' ? CTC_STYLES.warn : CTC_STYLES.cold;
|
|
472
1593
|
|
|
473
|
-
//
|
|
1594
|
+
// Group header: [CTC:<mode>] <decision> · <mode> · <type> · <latency>
|
|
1595
|
+
// arbitrationMode ('v1') tags the line so this deploy's logs diff cleanly
|
|
1596
|
+
// against the baseline deploy's.
|
|
474
1597
|
// eslint-disable-next-line no-console
|
|
475
|
-
console.groupCollapsed(`%c[
|
|
1598
|
+
console.groupCollapsed(`%c[CTC:${ARBITRATION_MODE}]%c ${decision} %c· ${modeLabel}${selected ? ` · ${selected.termType}` : ''} · ⏱ ${latencyMs.toFixed(1)}ms`, CTC_STYLES.brand, CTC_STYLES.body, modeColor);
|
|
1599
|
+
const semanticInput = getStoredContextInput();
|
|
1600
|
+
const causalPrompts = primeRequests.map((request, index) => {
|
|
1601
|
+
const tail = request.prompt.slice(-DEBUG_TEXT_TAIL_CHARS);
|
|
1602
|
+
return `#${index + 1}:${JSON.stringify(tail)}`;
|
|
1603
|
+
});
|
|
476
1604
|
|
|
477
|
-
//
|
|
478
|
-
|
|
479
|
-
|
|
1605
|
+
// Keep the exact model inputs separate from normalized lookup tokens.
|
|
1606
|
+
ctcSection('INPUT', `raw: ${JSON.stringify(trimmed.slice(-DEBUG_TEXT_TAIL_CHARS))} · prev: ${previousWord ? JSON.stringify(previousWord) : '—'}`);
|
|
1607
|
+
ctcSection('LOOKUP', `normalized(last ${CONTEXT_WORDS}): ${contextWords.length ? JSON.stringify(contextWords.join(' ')) : '(none)'}`);
|
|
1608
|
+
ctcSection('SEMANTIC', `snapshot: ${semanticInput ? JSON.stringify(semanticInput.slice(-DEBUG_TEXT_TAIL_CHARS)) : '(unavailable)'}`);
|
|
1609
|
+
ctcSection('CAUSAL', `prompt${causalPrompts.length === 1 ? '' : 's'}: ${causalPrompts.join(' · ') || '(not ready)'}`);
|
|
480
1610
|
|
|
481
|
-
//
|
|
482
|
-
const
|
|
483
|
-
const
|
|
484
|
-
|
|
485
|
-
|
|
1611
|
+
// SIGNALS — semantic state plus context-keyed canonical LM coverage.
|
|
1612
|
+
const logitCount = lmLogits ? Object.keys(lmLogits).length : 0;
|
|
1613
|
+
const semanticStatus = isUsingSlowLaneVector ? `semantic ✅ snapshot(${slowLaneVec === null || slowLaneVec === void 0 ? void 0 : slowLaneVec.length}d)` : vectorStore ? 'semantic ⚠️ local-avg' : 'semantic ❌ cold';
|
|
1614
|
+
const tierACount = ranked.filter(candidate => {
|
|
1615
|
+
var _candidate$lmEvidence3;
|
|
1616
|
+
return ((_candidate$lmEvidence3 = candidate.lmEvidence) === null || _candidate$lmEvidence3 === void 0 ? void 0 : _candidate$lmEvidence3.source) === 'canonical-first-token';
|
|
1617
|
+
}).length;
|
|
1618
|
+
const exactCount = ranked.filter(candidate => {
|
|
1619
|
+
var _candidate$lmEvidence4;
|
|
1620
|
+
return ((_candidate$lmEvidence4 = candidate.lmEvidence) === null || _candidate$lmEvidence4 === void 0 ? void 0 : _candidate$lmEvidence4.source) === 'canonical-full-surface';
|
|
1621
|
+
}).length;
|
|
1622
|
+
const boundaryReady = primeRequests.filter(request => getBoundaryLmState(request.contextKey) !== null).length;
|
|
1623
|
+
const artifactEligible = canonicalMatched.filter(candidate => candidate.canonicalTokenIds !== null).length;
|
|
1624
|
+
const documentStartFallbacks = canonicalMatched.filter(candidate => candidate.separatorKind === 'document-start').length;
|
|
1625
|
+
const punctuationFallbacks = canonicalMatched.filter(candidate => candidate.separatorKind === 'non-space').length;
|
|
1626
|
+
const logitsStatus = tierACount + exactCount > 0 ? `canonical ✅ first-token:${tierACount} exact:${exactCount}` : logitCount > 0 ? `network logits ✅ ${logitCount}` : 'canonical ⏳/absent';
|
|
1627
|
+
const formula = tierACount + exactCount + logitCount > 0 ? `Stage1×${STAGE1_WEIGHT}+LM×${STAGE2_WEIGHT}` : 'Stage1-only';
|
|
1628
|
+
ctcSection('SIGNALS', `${semanticStatus} · ${logitsStatus} · ${formula}`);
|
|
1629
|
+
ctcSection('CANONICAL', `eligible ${artifactEligible}/${canonicalMatched.length} · separator fallback doc:${documentStartFallbacks} punct:${punctuationFallbacks} · contexts ${boundaryReady}/${primeRequests.length} ready (≤${PHRASE_MAX_WORDS}) · family=${familyKey.slice(0, 72) || 'none'}`);
|
|
1630
|
+
if (verbose && logitCount > 0 && lmLogits) {
|
|
1631
|
+
const rawLmTop = Object.entries(lmLogits).sort((a, b) => b[1] - a[1]).slice(0, 5).map(([word, score]) => `${word}:${score.toFixed(3)}`).join(', ');
|
|
1632
|
+
ctcSection(' rawLM', `🧠 ${rawLmTop}`);
|
|
1633
|
+
}
|
|
486
1634
|
|
|
487
|
-
//
|
|
488
|
-
const
|
|
489
|
-
|
|
490
|
-
|
|
1635
|
+
// GENERATE — how many candidates matched, split by term type
|
|
1636
|
+
const genByType = {
|
|
1637
|
+
word: 0,
|
|
1638
|
+
bigram: 0,
|
|
1639
|
+
phrase: 0
|
|
1640
|
+
};
|
|
1641
|
+
for (const m of canonicalMatched) {
|
|
1642
|
+
genByType[m.node.termType] += 1;
|
|
1643
|
+
}
|
|
1644
|
+
ctcSection('GENERATE', `matched ${canonicalMatched.length} → word:${genByType.word} bigram:${genByType.bigram} phrase:${genByType.phrase}${canonicalLmSupported ? ' · display needs exact surface evidence' : ''}`);
|
|
491
1645
|
|
|
492
|
-
//
|
|
1646
|
+
// SCORE — Stage-1 + grammar funnel and canonical evidence depth.
|
|
1647
|
+
const lmCoverage = ranked.slice(0, 10).filter(r => r.lmScore > 0).length;
|
|
1648
|
+
ctcSection('SCORE', `in ${pipelineDebug.initial} → stage1(<${MIN_STAGE1_SCORE}) −${pipelineDebug.stage1Rejected.length} → grammar −${pipelineDebug.grammarRejected.length} → final ${pipelineDebug.final} · LM cov ${lmCoverage}/${Math.min(ranked.length, 10)} · first-token ${tierACount} · exact ${exactCount}`);
|
|
493
1649
|
if (grammarMeta) {
|
|
494
|
-
|
|
495
|
-
console.log(`%c[Grammar] "${grammarMeta.prevWord}" [${grammarMeta.prevTags.join('|')}] → ${grammarMeta.before} candidates → ${grammarMeta.after} after filter`, 'color: #4caf50; font-weight: bold;');
|
|
496
|
-
if (grammarMeta.dropped.length > 0) {
|
|
497
|
-
// eslint-disable-next-line no-console
|
|
498
|
-
console.log(`%c🚫 Dropped: ${grammarMeta.dropped.join(', ')}`, 'color: #f44336; font-style: italic;');
|
|
499
|
-
}
|
|
1650
|
+
ctcSection(' grammar', `"${grammarMeta.prevWord}" [${grammarMeta.prevTags.join('|')}] ${grammarMeta.before}→${grammarMeta.after}${verbose && grammarMeta.dropped.length > 0 ? ` · dropped: ${grammarMeta.dropped.join(', ')}` : ''}`);
|
|
500
1651
|
}
|
|
1652
|
+
const gateReasonFor = candidate => {
|
|
1653
|
+
const runtime = runtimeBySurface.get(candidate.word);
|
|
1654
|
+
if ((runtime === null || runtime === void 0 ? void 0 : runtime.separatorKind) !== 'whitespace') {
|
|
1655
|
+
var _runtime$separatorKin;
|
|
1656
|
+
return `separator:${(_runtime$separatorKin = runtime === null || runtime === void 0 ? void 0 : runtime.separatorKind) !== null && _runtime$separatorKin !== void 0 ? _runtime$separatorKin : 'unknown'}`;
|
|
1657
|
+
}
|
|
1658
|
+
if (runtime.canonicalTokenIds === null) {
|
|
1659
|
+
return 'missing-artifact';
|
|
1660
|
+
}
|
|
1661
|
+
if (!hasJudgeableEvidence(candidate)) {
|
|
1662
|
+
return `awaiting-tokens:${REQUIRED_VERIFIED_TOKENS}`;
|
|
1663
|
+
}
|
|
1664
|
+
if (!passesLmFloor(candidate)) {
|
|
1665
|
+
return `bound:${optimisticPosterior(candidate).toFixed(2)}<${MIN_LM_POSTERIOR[candidate.termType]}`;
|
|
1666
|
+
}
|
|
1667
|
+
if (duplicatesPreceding(candidate)) {
|
|
1668
|
+
return 'repetition';
|
|
1669
|
+
}
|
|
1670
|
+
if (isCooledDown(candidate)) {
|
|
1671
|
+
return 'cooldown';
|
|
1672
|
+
}
|
|
1673
|
+
if (!isWorthShowing(candidate)) {
|
|
1674
|
+
return `suffix:${suggestionLengthFor(candidate)}<${MIN_SUGGESTION_LENGTH}`;
|
|
1675
|
+
}
|
|
1676
|
+
const floor = MIN_LM_POSTERIOR[candidate.termType];
|
|
1677
|
+
const posterior = judgedPosterior(candidate);
|
|
1678
|
+
if (posterior < floor) {
|
|
1679
|
+
return `posterior:${posterior.toFixed(2)}<${floor}`;
|
|
1680
|
+
}
|
|
1681
|
+
if (!isPlausibleSurface(candidate)) {
|
|
1682
|
+
var _judgedEvidenceFor$me2, _judgedEvidenceFor5;
|
|
1683
|
+
return `implausible:${((_judgedEvidenceFor$me2 = (_judgedEvidenceFor5 = judgedEvidenceFor(candidate)) === null || _judgedEvidenceFor5 === void 0 ? void 0 : _judgedEvidenceFor5.mean) !== null && _judgedEvidenceFor$me2 !== void 0 ? _judgedEvidenceFor$me2 : NaN).toFixed(2)}<${MIN_MEAN_TOKEN_LOG_PROBABILITY}`;
|
|
1684
|
+
}
|
|
1685
|
+
return 'eligible';
|
|
1686
|
+
};
|
|
1687
|
+
const gateFunnel = termType => {
|
|
1688
|
+
const typeRanked = ranked.filter(candidate => candidate.termType === termType);
|
|
1689
|
+
const exact = typeRanked.filter(hasJudgeableEvidence);
|
|
1690
|
+
const absolute = exact.filter(passesLmFloor);
|
|
1691
|
+
const stabilized = absolute.filter(isStabilized);
|
|
1692
|
+
const longEnough = stabilized.filter(isWorthShowing);
|
|
1693
|
+
const floorPassed = longEnough.filter(candidate => judgedPosterior(candidate) >= MIN_LM_POSTERIOR[termType]);
|
|
1694
|
+
const plausiblePassed = floorPassed.filter(isPlausibleSurface);
|
|
1695
|
+
return `${termType} m:${genByType[termType]} r:${typeRanked.length} exact:${exact.length} abs:${absolute.length} stable:${stabilized.length} suffix:${longEnough.length} floor:${floorPassed.length} plausible:${plausiblePassed.length} eligible:${eligible.filter(({
|
|
1696
|
+
candidate
|
|
1697
|
+
}) => candidate.termType === termType).length}`;
|
|
1698
|
+
};
|
|
1699
|
+
ctcSection('GATES', `${gateFunnel('word')} | ${gateFunnel('bigram')} | ${gateFunnel('phrase')}`);
|
|
501
1700
|
|
|
502
|
-
//
|
|
503
|
-
//
|
|
504
|
-
|
|
1701
|
+
// One line per context: how many candidates share the normaliser, and how
|
|
1702
|
+
// much of the mass the leader holds. A leader well under its threshold
|
|
1703
|
+
// means the context is contested, which is the abstention we want.
|
|
1704
|
+
const contextLeaders = Array.from(bestCandidateByContext.entries()).slice(0, PHRASE_MAX_WORDS).map(([contextKey, leader]) => {
|
|
1705
|
+
var _contextTotals$get$le2, _contextTotals$get2;
|
|
1706
|
+
const shortlistSize = (_contextTotals$get$le2 = (_contextTotals$get2 = contextTotals.get(contextKey)) === null || _contextTotals$get2 === void 0 ? void 0 : _contextTotals$get2.length) !== null && _contextTotals$get$le2 !== void 0 ? _contextTotals$get$le2 : 0;
|
|
1707
|
+
const evidenceKind = hasExactEvidence(leader) ? 'exact' : 'upper';
|
|
1708
|
+
return `${contextKey.slice(0, 32)} → n=${shortlistSize} ${leader.termType}:"${leader.word}" ${evidenceKind} p=${optimisticPosterior(leader).toFixed(3)}/${MIN_LM_POSTERIOR[leader.termType]}`;
|
|
1709
|
+
}).join(' | ');
|
|
1710
|
+
ctcSection('NORMALIZE', contextLeaders.length > 0 ? contextLeaders : 'no scored candidate in any context');
|
|
1711
|
+
ctcSection('READINESS', `prefix ${currentWord.length}/${DISPLAY_MIN_PREFIX_LENGTH} · boundary ${boundaryReady}/${primeRequests.length} · exact word:${ranked.filter(candidate => candidate.termType === 'word' && hasExactEvidence(candidate)).length} bigram:${ranked.filter(candidate => candidate.termType === 'bigram' && hasExactEvidence(candidate)).length} phrase:${ranked.filter(candidate => candidate.termType === 'phrase' && hasExactEvidence(candidate)).length} · ${suggestion ? 'display-ready' : decision}`);
|
|
505
1712
|
|
|
506
|
-
//
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
1713
|
+
// ARBITRATE — expose every condition that can authorize or suppress ghost.
|
|
1714
|
+
const topOfType = t => ranked.find(c => c.termType === t);
|
|
1715
|
+
const fmtType = t => {
|
|
1716
|
+
var _top$lmEvidence$sourc, _top$lmEvidence;
|
|
1717
|
+
const top = topOfType(t);
|
|
1718
|
+
if (!top) {
|
|
1719
|
+
return `${t}:—`;
|
|
1720
|
+
}
|
|
1721
|
+
const floor = MIN_LM_POSTERIOR[t];
|
|
1722
|
+
const bound = optimisticPosterior(top);
|
|
1723
|
+
const evidence = hasRequiredEvidence(top) ? 'TierB✅' : `${(_top$lmEvidence$sourc = (_top$lmEvidence = top.lmEvidence) === null || _top$lmEvidence === void 0 ? void 0 : _top$lmEvidence.source) !== null && _top$lmEvidence$sourc !== void 0 ? _top$lmEvidence$sourc : 'absent'}❌`;
|
|
1724
|
+
return `${t}:"${top.word}" p≤${bound.toFixed(3)}${bound >= floor ? '≥' : '<'}${floor} fs≤${confidenceScore(top).toFixed(2)} ${evidence}`;
|
|
1725
|
+
};
|
|
1726
|
+
ctcSection('ARBITRATE', `${selected ? `▸ ${selected.termType} "${selected.word}" fs=${selectedDisplayScore.toFixed(2)} mean=${(_selectedEvidence$mea = selectedEvidence === null || selectedEvidence === void 0 ? void 0 : (_selectedEvidence$mea2 = selectedEvidence.meanTokenLogProbability) === null || _selectedEvidence$mea2 === void 0 ? void 0 : _selectedEvidence$mea2.toFixed(2)) !== null && _selectedEvidence$mea !== void 0 ? _selectedEvidence$mea : 'network'} margin=${winnerMargin.toFixed(2)}${clearsWinnerMargin ? '✅' : '❌'}` : '▸ (none)'} · prefix ${currentWord.length}/${DISPLAY_MIN_PREFIX_LENGTH}${displayPrefixReady ? '✅' : '⏳'} · grouped pending ${hasUnresolvedPotential ? 'yes' : 'no'} | ${fmtType('word')} ${fmtType('bigram')} ${fmtType('phrase')}`);
|
|
1727
|
+
|
|
1728
|
+
// STABILIZE — post-accept cooldown + whole-surface repetition (QI-2)
|
|
1729
|
+
const repetitionBlocked = ranked.filter(c => hasRequiredEvidence(c) && duplicatesPreceding(c)).map(c => c.word);
|
|
1730
|
+
const cooldownLabel = cooledSurface ? `cooldown "${cooledSurface}" (${(_acceptCooldown$predi = (_acceptCooldown = acceptCooldown) === null || _acceptCooldown === void 0 ? void 0 : _acceptCooldown.predictionsSince) !== null && _acceptCooldown$predi !== void 0 ? _acceptCooldown$predi : 0}/${COOLDOWN_KEYSTROKES} keys · ${COOLDOWN_MS}ms)` : 'cooldown —';
|
|
1731
|
+
ctcSection('STABILIZE', `${cooldownLabel} · repetition-blocked: ${repetitionBlocked.length > 0 ? repetitionBlocked.join(', ') : '—'}`);
|
|
1732
|
+
|
|
1733
|
+
// CANDIDATES — full scored table (verbose only)
|
|
1734
|
+
if (verbose && ranked.length > 0) {
|
|
511
1735
|
const tableData = ranked.slice(0, 10).map(r => {
|
|
1736
|
+
var _r$lmEvidence, _contextTotals$get$le3, _contextTotals$get3, _r$lmEvidence$source, _r$lmEvidence2, _runtime$separatorKin2, _runtime$canonicalTok2, _runtime$canonicalTok3, _runtime$contextKey, _r$lmEvidence3, _r$lmEvidence4;
|
|
512
1737
|
let rawLogit = 'Not in Payload';
|
|
513
|
-
if (
|
|
1738
|
+
if (((_r$lmEvidence = r.lmEvidence) === null || _r$lmEvidence === void 0 ? void 0 : _r$lmEvidence.rawLogit) !== undefined) {
|
|
1739
|
+
rawLogit = Number(r.lmEvidence.rawLogit.toFixed(5));
|
|
1740
|
+
} else if (prefixLmLogits) {
|
|
514
1741
|
const val = prefixLmLogits[r.word.toLowerCase()];
|
|
515
1742
|
if (val !== undefined) {
|
|
516
1743
|
rawLogit = Number(val.toFixed(5));
|
|
517
1744
|
}
|
|
518
1745
|
}
|
|
519
1746
|
const original = scoringCandidates.find(sc => sc.word === r.word);
|
|
1747
|
+
const runtime = runtimeBySurface.get(r.word);
|
|
1748
|
+
const progress = runtime ? getProgressiveSurfaceEvidence(runtime.contextKey, r.word) : null;
|
|
1749
|
+
const optimisticTotal = optimisticTotalByWord.get(r.word);
|
|
1750
|
+
const normalizer = runtime ? logSumExpByContext.get(runtime.contextKey) : undefined;
|
|
1751
|
+
const shortlistSize = runtime ? (_contextTotals$get$le3 = (_contextTotals$get3 = contextTotals.get(runtime.contextKey)) === null || _contextTotals$get3 === void 0 ? void 0 : _contextTotals$get3.length) !== null && _contextTotals$get$le3 !== void 0 ? _contextTotals$get$le3 : 0 : 0;
|
|
1752
|
+
const contextLeader = runtime ? bestCandidateByContext.get(runtime.contextKey) : undefined;
|
|
520
1753
|
let source = 'Unknown';
|
|
521
1754
|
if (original) {
|
|
522
|
-
if (original.
|
|
1755
|
+
if (original.termType === 'bigram') {
|
|
1756
|
+
source = '🔗 L2 (Bigram)';
|
|
1757
|
+
} else if (original.termType === 'phrase') {
|
|
1758
|
+
source = '🧩 L2 (Phrase)';
|
|
1759
|
+
} else if (original.docFreq === 0 && original.tenantFreq === L3_BASELINE_FREQ) {
|
|
523
1760
|
source = '🌍 L3 (Generic)';
|
|
524
1761
|
} else if (original.sessionFreq > 0 && original.tenantFreq === 0) {
|
|
525
1762
|
source = '👤 L1 (Session Only)';
|
|
@@ -527,13 +1764,40 @@ export const predict = textBefore => {
|
|
|
527
1764
|
source = '🏢 L2 (Domain)';
|
|
528
1765
|
}
|
|
529
1766
|
}
|
|
1767
|
+
const floor = MIN_LM_POSTERIOR[r.termType];
|
|
530
1768
|
return {
|
|
531
1769
|
Candidate: r.word,
|
|
532
1770
|
Source: source,
|
|
1771
|
+
Type: r.termType,
|
|
533
1772
|
'Final Score': Number(r.finalScore.toFixed(4)),
|
|
1773
|
+
'Bounded Score': Number(confidenceScore(r).toFixed(4)),
|
|
1774
|
+
'Exact Gate Score': hasExactEvidence(r) ? Number(exactConfidenceScore(r).toFixed(4)) : '—',
|
|
1775
|
+
Floor: floor,
|
|
1776
|
+
'Posterior Floor': optimisticPosterior(r) >= floor ? '✅' : '❌',
|
|
1777
|
+
'LM Floor': hasExactEvidence(r) ? passesLmFloor(r) ? '✅' : '❌' : '⏳',
|
|
1778
|
+
'Gate Reason': gateReasonFor(r),
|
|
1779
|
+
'Display Eligible': hasRequiredEvidence(r) && isStabilized(r) && judgedPosterior(r) >= floor ? '✅' : '❌',
|
|
534
1780
|
Semantics: Number(r.semanticScore.toFixed(4)),
|
|
535
1781
|
Freq: Number(r.freqScore.toFixed(4)),
|
|
536
1782
|
'LM Score': Number(r.lmScore.toFixed(4)),
|
|
1783
|
+
'LM Evidence': (_r$lmEvidence$source = (_r$lmEvidence2 = r.lmEvidence) === null || _r$lmEvidence2 === void 0 ? void 0 : _r$lmEvidence2.source) !== null && _r$lmEvidence$source !== void 0 ? _r$lmEvidence$source : 'absent',
|
|
1784
|
+
'Verified Tokens': r.lmEvidence ? `${r.lmEvidence.verifiedTokenCount}/${r.lmEvidence.totalTokenCount}` : '0/0',
|
|
1785
|
+
'Progressive Tokens': progress ? `${progress.scoredTokenCount}/${progress.totalTokenCount}` : '0/0',
|
|
1786
|
+
'LM Mean Upper': progress !== null ? Number(progress.meanTokenLogProbabilityUpperBound.toFixed(5)) : '—',
|
|
1787
|
+
'Optimistic Total': optimisticTotal !== undefined ? Number(optimisticTotal.toFixed(5)) : '—',
|
|
1788
|
+
'Context logSumExp': normalizer !== undefined && Number.isFinite(normalizer) ? Number(normalizer.toFixed(5)) : '—',
|
|
1789
|
+
'Shortlist Size': shortlistSize,
|
|
1790
|
+
'Posterior (bound)': Number(optimisticPosterior(r).toFixed(5)),
|
|
1791
|
+
'Posterior (judged)': hasJudgeableEvidence(r) ? Number(judgedPosterior(r).toFixed(5)) : '—',
|
|
1792
|
+
'Context Leader': contextLeader ? `${contextLeader.termType}:${contextLeader.word}` : '—',
|
|
1793
|
+
'Verified Chars': r.lmEvidence ? `${r.lmEvidence.verifiedCharCount}/${r.lmEvidence.totalSurfaceCharCount}` : `0/${r.word.length}`,
|
|
1794
|
+
Separator: (_runtime$separatorKin2 = runtime === null || runtime === void 0 ? void 0 : runtime.separatorKind) !== null && _runtime$separatorKin2 !== void 0 ? _runtime$separatorKin2 : 'unknown',
|
|
1795
|
+
'Canonical Eligibility': (runtime === null || runtime === void 0 ? void 0 : runtime.separatorKind) !== 'whitespace' ? 'incompatible-separator' : runtime.canonicalTokenIds === null ? 'missing-artifact' : 'eligible',
|
|
1796
|
+
'Artifact Tokens': (_runtime$canonicalTok2 = runtime === null || runtime === void 0 ? void 0 : (_runtime$canonicalTok3 = runtime.canonicalTokenIds) === null || _runtime$canonicalTok3 === void 0 ? void 0 : _runtime$canonicalTok3.join(',')) !== null && _runtime$canonicalTok2 !== void 0 ? _runtime$canonicalTok2 : 'absent',
|
|
1797
|
+
'Context Key': (_runtime$contextKey = runtime === null || runtime === void 0 ? void 0 : runtime.contextKey) !== null && _runtime$contextKey !== void 0 ? _runtime$contextKey : '—',
|
|
1798
|
+
'Exact Total': ((_r$lmEvidence3 = r.lmEvidence) === null || _r$lmEvidence3 === void 0 ? void 0 : _r$lmEvidence3.totalLogProbability) !== undefined ? Number(r.lmEvidence.totalLogProbability.toFixed(5)) : '—',
|
|
1799
|
+
'Exact Mean': ((_r$lmEvidence4 = r.lmEvidence) === null || _r$lmEvidence4 === void 0 ? void 0 : _r$lmEvidence4.meanTokenLogProbability) !== undefined ? Number(r.lmEvidence.meanTokenLogProbability.toFixed(5)) : '—',
|
|
1800
|
+
Assoc: typeof (original === null || original === void 0 ? void 0 : original.association) === 'number' ? Number(original.association.toFixed(4)) : '—',
|
|
537
1801
|
'Raw Logit': rawLogit,
|
|
538
1802
|
'Session Freq': (original === null || original === void 0 ? void 0 : original.sessionFreq) || 0
|
|
539
1803
|
};
|
|
@@ -541,19 +1805,105 @@ export const predict = textBefore => {
|
|
|
541
1805
|
|
|
542
1806
|
// eslint-disable-next-line no-console
|
|
543
1807
|
console.table(tableData);
|
|
544
|
-
} else {
|
|
545
|
-
// eslint-disable-next-line no-console
|
|
546
|
-
console.log('No candidates found.');
|
|
547
1808
|
}
|
|
548
1809
|
|
|
549
1810
|
// eslint-disable-next-line no-console
|
|
550
1811
|
console.groupEnd();
|
|
551
1812
|
}
|
|
552
|
-
|
|
1813
|
+
const selectedContextKey = selected ? (_runtimeBySurface$get1 = runtimeBySurface.get(selected.word)) === null || _runtimeBySurface$get1 === void 0 ? void 0 : _runtimeBySurface$get1.contextKey : undefined;
|
|
1814
|
+
return suggestion && suggestion.length > 0 && selected && selectedEvidence ? {
|
|
1815
|
+
text: suggestion,
|
|
1816
|
+
surface: selected.word,
|
|
1817
|
+
termType: selected.termType,
|
|
1818
|
+
posterior: judgedPosterior(selected),
|
|
1819
|
+
meanTokenLogProbability: (_judgedEvidenceFor$me3 = (_judgedEvidenceFor6 = judgedEvidenceFor(selected)) === null || _judgedEvidenceFor6 === void 0 ? void 0 : _judgedEvidenceFor6.mean) !== null && _judgedEvidenceFor$me3 !== void 0 ? _judgedEvidenceFor$me3 : NaN,
|
|
1820
|
+
poolHeldExtension: poolExtensionOf(selected) !== undefined,
|
|
1821
|
+
shortlistSize: selectedContextKey === undefined ? 1 : (_contextTotals$get$le4 = (_contextTotals$get4 = contextTotals.get(selectedContextKey)) === null || _contextTotals$get4 === void 0 ? void 0 : _contextTotals$get4.length) !== null && _contextTotals$get$le4 !== void 0 ? _contextTotals$get$le4 : 1,
|
|
1822
|
+
rankScore: selectedDisplayScore,
|
|
1823
|
+
evidenceTier: (selectedEvidence === null || selectedEvidence === void 0 ? void 0 : selectedEvidence.source) === 'network-logit' ? 'network-logit' : 'canonical-full-surface',
|
|
1824
|
+
evidenceDepth: {
|
|
1825
|
+
verifiedTokens: (_selectedEvidence$ver = selectedEvidence === null || selectedEvidence === void 0 ? void 0 : selectedEvidence.verifiedTokenCount) !== null && _selectedEvidence$ver !== void 0 ? _selectedEvidence$ver : 0,
|
|
1826
|
+
totalTokens: (_selectedEvidence$tot = selectedEvidence === null || selectedEvidence === void 0 ? void 0 : selectedEvidence.totalTokenCount) !== null && _selectedEvidence$tot !== void 0 ? _selectedEvidence$tot : 0,
|
|
1827
|
+
verifiedChars: (_selectedEvidence$ver2 = selectedEvidence === null || selectedEvidence === void 0 ? void 0 : selectedEvidence.verifiedCharCount) !== null && _selectedEvidence$ver2 !== void 0 ? _selectedEvidence$ver2 : 0,
|
|
1828
|
+
totalChars: selected.word.length
|
|
1829
|
+
},
|
|
1830
|
+
winnerMargin
|
|
1831
|
+
} : null;
|
|
553
1832
|
};
|
|
554
1833
|
|
|
555
1834
|
// ─── Data Loading ────────────────────────────────────────────────────────────
|
|
556
1835
|
|
|
1836
|
+
const isVocabularyJson = payload => {
|
|
1837
|
+
if (payload == null || typeof payload !== 'object') {
|
|
1838
|
+
return false;
|
|
1839
|
+
}
|
|
1840
|
+
const words = payload.words;
|
|
1841
|
+
return words != null && typeof words === 'object';
|
|
1842
|
+
};
|
|
1843
|
+
const isStringArray = payload => Array.isArray(payload) && payload.every(entry => typeof entry === 'string');
|
|
1844
|
+
const isWordToOffsetMap = value => value != null && typeof value === 'object' && Object.values(value).every(entry => typeof entry === 'number');
|
|
1845
|
+
const isWordIndexPayload = payload => {
|
|
1846
|
+
if (payload == null || typeof payload !== 'object') {
|
|
1847
|
+
return false;
|
|
1848
|
+
}
|
|
1849
|
+
const index = payload.index;
|
|
1850
|
+
return index === undefined ? isWordToOffsetMap(payload) : isWordToOffsetMap(index);
|
|
1851
|
+
};
|
|
1852
|
+
|
|
1853
|
+
/**
|
|
1854
|
+
* The word index has shipped both bare and wrapped in `{ index: ... }`, so
|
|
1855
|
+
* accept either rather than silently building an empty vector store.
|
|
1856
|
+
*/
|
|
1857
|
+
const unwrapWordIndex = payload => {
|
|
1858
|
+
const wrapped = payload.index;
|
|
1859
|
+
return wrapped !== null && wrapped !== void 0 ? wrapped : payload;
|
|
1860
|
+
};
|
|
1861
|
+
|
|
1862
|
+
/**
|
|
1863
|
+
* Per-term stats shape for `bigrams.json` / `phrases.json`. Field names/types
|
|
1864
|
+
* confirmed against the producer (`l2_vocabulary_creation._build_ngram_stat_payload`
|
|
1865
|
+
* + `artifact_release._validate_ngram_payload`): `freq`/`doc_freq`/`author_freq`
|
|
1866
|
+
* are ints, `pos_seq` a string array, `head_pos` a string or null, `association`
|
|
1867
|
+
* a number.
|
|
1868
|
+
*/
|
|
1869
|
+
|
|
1870
|
+
/** Normalized `{term: stats}` map after unwrapping any producer wrapper key. */
|
|
1871
|
+
|
|
1872
|
+
const isPhraseStats = value => value != null && typeof value === 'object' && typeof value.freq === 'number';
|
|
1873
|
+
const isTermStatsMap = value => {
|
|
1874
|
+
if (value == null || typeof value !== 'object') {
|
|
1875
|
+
return false;
|
|
1876
|
+
}
|
|
1877
|
+
const values = Object.values(value);
|
|
1878
|
+
return values.length > 0 && values.every(isPhraseStats);
|
|
1879
|
+
};
|
|
1880
|
+
|
|
1881
|
+
/**
|
|
1882
|
+
* Normalize a `bigrams.json` / `phrases.json` payload into a flat
|
|
1883
|
+
* `{term: stats}` map. Tolerant of the exact wire shape (not yet finalized by
|
|
1884
|
+
* the producer): accepts either the flat map from spec §9 or a single wrapper
|
|
1885
|
+
* key (`terms`/`bigrams`/`phrases`/`words`). Returns `null` if unrecognized.
|
|
1886
|
+
*
|
|
1887
|
+
* :params:
|
|
1888
|
+
* payload: Raw JSON parsed from the artifact endpoint
|
|
1889
|
+
* :returns:
|
|
1890
|
+
* A `{term: stats}` map, or `null` when the shape is not a term-stats map
|
|
1891
|
+
*/
|
|
1892
|
+
const normalizePhraseArtifact = payload => {
|
|
1893
|
+
if (payload == null || typeof payload !== 'object') {
|
|
1894
|
+
return null;
|
|
1895
|
+
}
|
|
1896
|
+
if (isTermStatsMap(payload)) {
|
|
1897
|
+
return payload;
|
|
1898
|
+
}
|
|
1899
|
+
const obj = payload;
|
|
1900
|
+
for (const key of ['terms', 'bigrams', 'phrases', 'words']) {
|
|
1901
|
+
if (isTermStatsMap(obj[key])) {
|
|
1902
|
+
return obj[key];
|
|
1903
|
+
}
|
|
1904
|
+
}
|
|
1905
|
+
return null;
|
|
1906
|
+
};
|
|
557
1907
|
export const loadVectorsAsync = async options => {
|
|
558
1908
|
var _options$isLocalLLM;
|
|
559
1909
|
if (vectorStore || vectorsLoadStarted) {
|
|
@@ -568,53 +1918,17 @@ export const loadVectorsAsync = async options => {
|
|
|
568
1918
|
surface
|
|
569
1919
|
} : {})
|
|
570
1920
|
});
|
|
571
|
-
let url;
|
|
572
|
-
try {
|
|
573
|
-
url = await getArtifactUrl(ARTIFACT_NAME.WORD_VECTORS);
|
|
574
|
-
} catch (e) {
|
|
575
|
-
vectorsLoadStarted = false;
|
|
576
|
-
failExp(EXPERIENCE_NAME.LOAD_VECTORS, 'singleton', {
|
|
577
|
-
isLocalLLM,
|
|
578
|
-
errorType: 'resolve_url',
|
|
579
|
-
...(surface ? {
|
|
580
|
-
surface
|
|
581
|
-
} : {})
|
|
582
|
-
});
|
|
583
|
-
// eslint-disable-next-line no-console
|
|
584
|
-
console.warn('[text-predictor] Failed to resolve vectors URL:', e);
|
|
585
|
-
return;
|
|
586
|
-
}
|
|
587
1921
|
try {
|
|
588
|
-
const
|
|
589
|
-
if (!res.ok) {
|
|
590
|
-
vectorsLoadStarted = false;
|
|
591
|
-
failExp(EXPERIENCE_NAME.LOAD_VECTORS, 'singleton', {
|
|
592
|
-
isLocalLLM,
|
|
593
|
-
status: res.status,
|
|
594
|
-
errorType: 'http_error',
|
|
595
|
-
...(surface ? {
|
|
596
|
-
surface
|
|
597
|
-
} : {})
|
|
598
|
-
});
|
|
599
|
-
// eslint-disable-next-line no-console
|
|
600
|
-
console.warn(`[text-predictor] Failed to load vectors: ${res.status}`);
|
|
601
|
-
return;
|
|
602
|
-
}
|
|
603
|
-
const buffer = await res.arrayBuffer();
|
|
1922
|
+
const buffer = await fetchAutocompleteArtifactBinary(ARTIFACT_NAME.WORD_VECTORS, 'word_vectors_10k');
|
|
604
1923
|
const float32 = new Float32Array(buffer);
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
// bare index every value is a number.
|
|
611
|
-
const wordIndexPayload = await fetchArtifactJson(ARTIFACT_NAME.WORD_INDEX);
|
|
612
|
-
const wrappedIndex = wordIndexPayload === null || wordIndexPayload === void 0 ? void 0 : wordIndexPayload.index;
|
|
613
|
-
const wordIndex = typeof wrappedIndex === 'object' && wrappedIndex !== null ? wrappedIndex : wordIndexPayload !== null && wordIndexPayload !== void 0 ? wordIndexPayload : {};
|
|
1924
|
+
const wordIndexPayload = await fetchAutocompleteArtifactJson(ARTIFACT_NAME.WORD_INDEX, {
|
|
1925
|
+
summarize: payload => `${Object.keys(unwrapWordIndex(payload)).length} entries`,
|
|
1926
|
+
validate: isWordIndexPayload
|
|
1927
|
+
});
|
|
1928
|
+
const wordIndex = unwrapWordIndex(wordIndexPayload);
|
|
614
1929
|
const nWords = Object.keys(wordIndex).length;
|
|
615
1930
|
if (nWords === 0) {
|
|
616
|
-
|
|
617
|
-
console.warn(`[text-predictor] ${ARTIFACT_NAME.WORD_INDEX} was empty — semantic scoring will be a no-op.`);
|
|
1931
|
+
ctcTag('init', '⚠️ word_index_10k.json was empty — semantic scoring will be a no-op', CTC_STYLES.warn);
|
|
618
1932
|
}
|
|
619
1933
|
const dim = float32.length / nWords;
|
|
620
1934
|
vectorStore = {
|
|
@@ -631,14 +1945,7 @@ export const loadVectorsAsync = async options => {
|
|
|
631
1945
|
surface
|
|
632
1946
|
} : {})
|
|
633
1947
|
});
|
|
634
|
-
|
|
635
|
-
// eslint-disable-next-line no-console
|
|
636
|
-
console.log('[text-predictor] Vectors loaded:', {
|
|
637
|
-
wordCount: nWords,
|
|
638
|
-
dim,
|
|
639
|
-
sizeBytes: float32.byteLength
|
|
640
|
-
});
|
|
641
|
-
}
|
|
1948
|
+
ctcTag('init', `vectors loaded: ${nWords} words · dim ${dim} · ${float32.byteLength}B`);
|
|
642
1949
|
} catch (e) {
|
|
643
1950
|
vectorsLoadStarted = false;
|
|
644
1951
|
failExp(EXPERIENCE_NAME.LOAD_VECTORS, 'singleton', {
|
|
@@ -648,23 +1955,88 @@ export const loadVectorsAsync = async options => {
|
|
|
648
1955
|
surface
|
|
649
1956
|
} : {})
|
|
650
1957
|
});
|
|
651
|
-
|
|
652
|
-
console.warn('[text-predictor] Failed to load vectors:', e);
|
|
1958
|
+
ctcTag('init', `⚠️ failed to load vectors: ${String(e)}`, CTC_STYLES.bad);
|
|
653
1959
|
}
|
|
654
1960
|
};
|
|
655
1961
|
export const initVectors = store => {
|
|
656
1962
|
vectorStore = store;
|
|
657
1963
|
};
|
|
1964
|
+
|
|
1965
|
+
/**
|
|
1966
|
+
* Load the producer's `bigrams.json` + `phrases.json` completion-term artifacts
|
|
1967
|
+
* over the TDP-OS gateway and insert them into the phrase trie.
|
|
1968
|
+
*
|
|
1969
|
+
* Each file is fetched independently (`Promise.allSettled`) so a missing or
|
|
1970
|
+
* late-published artifact only skips that term type — word completion and the
|
|
1971
|
+
* other term type are unaffected. Phrase VECTORS are not fetched here: per the
|
|
1972
|
+
* producer's `extend` decision they are appended into the existing
|
|
1973
|
+
* `word-index-10k.json` / `word-vectors-10k.bin`, so `loadVectorsAsync` already
|
|
1974
|
+
* covers them.
|
|
1975
|
+
*
|
|
1976
|
+
* :params:
|
|
1977
|
+
* options.isLocalLLM: Tags the UFO experience so latency/success feeds the same SLO
|
|
1978
|
+
* :returns:
|
|
1979
|
+
* A promise that resolves once both fetches have settled
|
|
1980
|
+
*/
|
|
1981
|
+
export const loadPhraseArtifacts = async options => {
|
|
1982
|
+
var _options$isLocalLLM2;
|
|
1983
|
+
if (phrasesLoadStarted) {
|
|
1984
|
+
return;
|
|
1985
|
+
}
|
|
1986
|
+
phrasesLoadStarted = true;
|
|
1987
|
+
const isLocalLLM = (_options$isLocalLLM2 = options === null || options === void 0 ? void 0 : options.isLocalLLM) !== null && _options$isLocalLLM2 !== void 0 ? _options$isLocalLLM2 : false;
|
|
1988
|
+
startExp(EXPERIENCE_NAME.LOAD_PHRASES, 'singleton', {
|
|
1989
|
+
isLocalLLM
|
|
1990
|
+
});
|
|
1991
|
+
const loadOne = async (artifactName, termType, label) => {
|
|
1992
|
+
const payload = await fetchAutocompleteArtifactJson(artifactName, {
|
|
1993
|
+
label,
|
|
1994
|
+
validate: p => p != null && typeof p === 'object'
|
|
1995
|
+
});
|
|
1996
|
+
const normalized = normalizePhraseArtifact(payload);
|
|
1997
|
+
if (!normalized) {
|
|
1998
|
+
throw new Error(`[text-predictor] ${label} payload was not a recognised term-stats map`);
|
|
1999
|
+
}
|
|
2000
|
+
return initPhrases(normalized, termType);
|
|
2001
|
+
};
|
|
2002
|
+
const [bigramsResult, phrasesResult] = await Promise.allSettled([loadOne(ARTIFACT_NAME.BIGRAMS, 'bigram', 'bigrams'), loadOne(ARTIFACT_NAME.PHRASES, 'phrase', 'phrases')]);
|
|
2003
|
+
const bigramCount = bigramsResult.status === 'fulfilled' ? bigramsResult.value : 0;
|
|
2004
|
+
const phraseCount = phrasesResult.status === 'fulfilled' ? phrasesResult.value : 0;
|
|
2005
|
+
if (bigramsResult.status === 'rejected') {
|
|
2006
|
+
ctcTag('init', `⚠️ failed to load bigrams.json: ${String(bigramsResult.reason)}`, CTC_STYLES.warn);
|
|
2007
|
+
}
|
|
2008
|
+
if (phrasesResult.status === 'rejected') {
|
|
2009
|
+
ctcTag('init', `⚠️ failed to load phrases.json: ${String(phrasesResult.reason)}`, CTC_STYLES.warn);
|
|
2010
|
+
}
|
|
2011
|
+
if (bigramsResult.status === 'fulfilled' || phrasesResult.status === 'fulfilled') {
|
|
2012
|
+
phrasesLoaded = true;
|
|
2013
|
+
succeedExp(EXPERIENCE_NAME.LOAD_PHRASES, 'singleton', {
|
|
2014
|
+
isLocalLLM,
|
|
2015
|
+
bigramCount,
|
|
2016
|
+
phraseCount
|
|
2017
|
+
});
|
|
2018
|
+
ctcTag('init', `phrase artifacts loaded: ${bigramCount} bigrams · ${phraseCount} phrases`);
|
|
2019
|
+
} else {
|
|
2020
|
+
// Both failed — e.g. artifacts not published to the tenant manifest yet.
|
|
2021
|
+
// Reset the guard so a later focus/predict can retry once they land.
|
|
2022
|
+
phrasesLoadStarted = false;
|
|
2023
|
+
failExp(EXPERIENCE_NAME.LOAD_PHRASES, 'singleton', {
|
|
2024
|
+
isLocalLLM,
|
|
2025
|
+
errorType: 'network'
|
|
2026
|
+
});
|
|
2027
|
+
}
|
|
2028
|
+
};
|
|
658
2029
|
let vocabularyLoadPromise;
|
|
659
2030
|
export const loadDefaultVocabulary = options => {
|
|
660
|
-
var _options$
|
|
2031
|
+
var _options$isLocalLLM3, _options$source;
|
|
661
2032
|
if (isInitialized) {
|
|
662
2033
|
return Promise.resolve();
|
|
663
2034
|
}
|
|
664
2035
|
if (vocabularyLoadPromise) {
|
|
665
2036
|
return vocabularyLoadPromise;
|
|
666
2037
|
}
|
|
667
|
-
const isLocalLLM = (_options$
|
|
2038
|
+
const isLocalLLM = (_options$isLocalLLM3 = options === null || options === void 0 ? void 0 : options.isLocalLLM) !== null && _options$isLocalLLM3 !== void 0 ? _options$isLocalLLM3 : false;
|
|
2039
|
+
const source = (_options$source = options === null || options === void 0 ? void 0 : options.source) !== null && _options$source !== void 0 ? _options$source : 'predict';
|
|
668
2040
|
const surface = options === null || options === void 0 ? void 0 : options.surface;
|
|
669
2041
|
vocabularyLoadPromise = (async () => {
|
|
670
2042
|
startExp(EXPERIENCE_NAME.LOAD_VOCABULARY, 'singleton', {
|
|
@@ -674,10 +2046,36 @@ export const loadDefaultVocabulary = options => {
|
|
|
674
2046
|
} : {})
|
|
675
2047
|
});
|
|
676
2048
|
try {
|
|
677
|
-
|
|
678
|
-
if ((
|
|
679
|
-
|
|
2049
|
+
ctcTag('init', `loading artifacts (trigger: ${source} · localLLM: ${isLocalLLM})`);
|
|
2050
|
+
if (isAutocompleteDebugVerbose()) {
|
|
2051
|
+
// eslint-disable-next-line no-console
|
|
2052
|
+
console.groupCollapsed('%c[CTC:init]%c artifact manifest', CTC_STYLES.brand, CTC_STYLES.body);
|
|
2053
|
+
// eslint-disable-next-line no-console
|
|
2054
|
+
console.log('Eager:', [ARTIFACT_NAME.VOCABULARY, ARTIFACT_NAME.L3_VOCABULARY, ARTIFACT_NAME.POS_TAGS, ARTIFACT_NAME.GHOST_POS_TAGS, ARTIFACT_NAME.GRAMMAR_TRANSITIONS]);
|
|
2055
|
+
// eslint-disable-next-line no-console
|
|
2056
|
+
console.log('Conditional:', [`${ARTIFACT_NAME.WORD_INDEX} (only when vectors load; phrase/bigram surfaces share this index)`, `${ARTIFACT_NAME.BIGRAMS} + ${ARTIFACT_NAME.PHRASES} (completion-term stats; fire-and-forget)`, `${ARTIFACT_NAME.PHRASE_CONTINUATION_TOKENS} (local model only; canonical token IDs for the full served union)`]);
|
|
2057
|
+
// eslint-disable-next-line no-console
|
|
2058
|
+
console.groupEnd();
|
|
680
2059
|
}
|
|
2060
|
+
const [vocabularyData, l3VocabularyData] = await Promise.all([fetchAutocompleteArtifactJson(ARTIFACT_NAME.VOCABULARY, {
|
|
2061
|
+
summarize: payload => `${Object.keys(payload.words).length} words`,
|
|
2062
|
+
validate: isVocabularyJson
|
|
2063
|
+
}), fetchAutocompleteArtifactJson(ARTIFACT_NAME.L3_VOCABULARY, {
|
|
2064
|
+
summarize: payload => `${payload.length} words`,
|
|
2065
|
+
validate: isStringArray
|
|
2066
|
+
}),
|
|
2067
|
+
// Awaited alongside the vocabulary so the grammar filter is settled
|
|
2068
|
+
// before the first suggestion can be produced. Without this the
|
|
2069
|
+
// predictor initialises on the smaller vocabulary payload and serves
|
|
2070
|
+
// candidates the filter would have dropped until the grammar lands.
|
|
2071
|
+
// Only settlement is required: a failed load leaves the filter as a
|
|
2072
|
+
// pass-through, which is the same degradation as an absent artifact.
|
|
2073
|
+
loadGrammarDataAsync({
|
|
2074
|
+
isLocalLLM,
|
|
2075
|
+
surface
|
|
2076
|
+
}).catch(error => {
|
|
2077
|
+
ctcTag('init', `⚠️ grammar data unavailable; filtering skipped: ${String(error)}`, CTC_STYLES.warn);
|
|
2078
|
+
})]);
|
|
681
2079
|
const terms = Object.entries(vocabularyData.words).map(([word, stats]) => ({
|
|
682
2080
|
word,
|
|
683
2081
|
freq: stats.freq,
|
|
@@ -692,6 +2090,12 @@ export const loadDefaultVocabulary = options => {
|
|
|
692
2090
|
initVocabulary({
|
|
693
2091
|
terms
|
|
694
2092
|
});
|
|
2093
|
+
|
|
2094
|
+
// Phrase/bigram artifacts load independently and must never affect the
|
|
2095
|
+
// word path — fire-and-forget with its own error handling inside.
|
|
2096
|
+
void loadPhraseArtifacts({
|
|
2097
|
+
isLocalLLM
|
|
2098
|
+
}).catch(() => {});
|
|
695
2099
|
succeedExp(EXPERIENCE_NAME.LOAD_VOCABULARY, 'singleton', {
|
|
696
2100
|
isLocalLLM,
|
|
697
2101
|
l2WordCount: terms.length,
|
|
@@ -703,7 +2107,7 @@ export const loadDefaultVocabulary = options => {
|
|
|
703
2107
|
} catch (e) {
|
|
704
2108
|
failExp(EXPERIENCE_NAME.LOAD_VOCABULARY, 'singleton', {
|
|
705
2109
|
isLocalLLM,
|
|
706
|
-
errorType: '
|
|
2110
|
+
errorType: 'parse_error',
|
|
707
2111
|
...(surface ? {
|
|
708
2112
|
surface
|
|
709
2113
|
} : {})
|