coauthored 0.0.0-stage → 1.0.1
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/LICENSE +21 -0
- package/PRIVACY.md +107 -0
- package/README.md +113 -3
- package/THIRD_PARTY_LICENSES.md +105 -0
- package/dist/cli/analytics/anchors.js +39 -0
- package/dist/cli/analytics/archetypes.js +193 -0
- package/dist/cli/analytics/content/analyzer.js +945 -0
- package/dist/cli/analytics/content/classify.js +115 -0
- package/dist/cli/analytics/content/demo-corpus.js +301 -0
- package/dist/cli/analytics/content/sketch.js +54 -0
- package/dist/cli/analytics/dataset.js +321 -0
- package/dist/cli/analytics/demo-fixtures.js +531 -0
- package/dist/cli/analytics/fdr.js +183 -0
- package/dist/cli/analytics/helicorder.js +66 -0
- package/dist/cli/analytics/insights.js +589 -0
- package/dist/cli/analytics/models.js +75 -0
- package/dist/cli/analytics/pricing.js +121 -0
- package/dist/cli/analytics/probable-cause.js +115 -0
- package/dist/cli/analytics/report-builder.js +162 -0
- package/dist/cli/analytics/statistics.js +91 -0
- package/dist/cli/analytics/time.js +252 -0
- package/dist/cli/cli/args.js +105 -0
- package/dist/cli/cli/browser.js +71 -0
- package/dist/cli/cli/index.js +20 -0
- package/dist/cli/cli/main.js +520 -0
- package/dist/cli/cli/phrase-review.js +78 -0
- package/dist/cli/cli/server.js +481 -0
- package/dist/cli/cli/terminal.js +363 -0
- package/dist/cli/ingest/adapters/aider.js +116 -0
- package/dist/cli/ingest/adapters/claude-code.js +139 -0
- package/dist/cli/ingest/adapters/cline-roo.js +89 -0
- package/dist/cli/ingest/adapters/codex-cli.js +240 -0
- package/dist/cli/ingest/adapters/content.js +99 -0
- package/dist/cli/ingest/adapters/cursor-ide.js +149 -0
- package/dist/cli/ingest/adapters/gemini-cli.js +208 -0
- package/dist/cli/ingest/adapters/index.js +18 -0
- package/dist/cli/ingest/adapters/opencode.js +203 -0
- package/dist/cli/ingest/adapters/pi-agent.js +85 -0
- package/dist/cli/ingest/adapters/shared.js +484 -0
- package/dist/cli/ingest/content-sink.js +31 -0
- package/dist/cli/ingest/discovery.js +50 -0
- package/dist/cli/ingest/message-digests.js +61 -0
- package/dist/cli/ingest/pipeline.js +155 -0
- package/dist/cli/ingest/safe-fs.js +284 -0
- package/dist/cli/ingest/sqlite-stage.js +139 -0
- package/dist/cli/ingest/time-window.js +34 -0
- package/dist/cli/ingest/tool-map.js +24 -0
- package/dist/cli/ingest/types.js +1 -0
- package/dist/cli/ingest/worker.js +97 -0
- package/dist/cli/report/content/emoji-names.js +3956 -0
- package/dist/cli/report/content/insights.js +41 -0
- package/dist/cli/report/content/lexicons.js +112 -0
- package/dist/cli/report/content/policy.js +77 -0
- package/dist/cli/report/content/redact.js +164 -0
- package/dist/cli/report/content/stopwords.js +8848 -0
- package/dist/cli/report/content/suppression.js +2617 -0
- package/dist/cli/report/content/validate.js +152 -0
- package/dist/cli/report/copy-lint.js +105 -0
- package/dist/cli/report/share.js +132 -0
- package/dist/cli/report/types.js +1 -0
- package/dist/cli/report/validators.js +334 -0
- package/dist/web/assets/Archivo-VF-BohoA-Sn.woff2 +0 -0
- package/dist/web/assets/DelaGothicOne-subset-CpoJGhTq.woff2 +0 -0
- package/dist/web/assets/Film-BkhZFxG9.css +1 -0
- package/dist/web/assets/MartianMono-VF-CmJ1nXx9.woff2 +0 -0
- package/dist/web/assets/app-Dw1a5h5V.js +38 -0
- package/dist/web/assets/bricolage-grotesque-latin-700-normal-gtcctNPv.woff2 +0 -0
- package/dist/web/assets/bricolage-grotesque-latin-800-normal-J50vIsBe.woff2 +0 -0
- package/dist/web/assets/chorus-D7bfON5Z.ogg +0 -0
- package/dist/web/assets/chorus-bass-CBTKpMv_.ogg +0 -0
- package/dist/web/assets/chorus-drums-BOzgLSoq.ogg +0 -0
- package/dist/web/assets/chorus-harmony-DnJYs_tp.ogg +0 -0
- package/dist/web/assets/chorus-lead-CFpg5DC1.ogg +0 -0
- package/dist/web/assets/chunk-BNfsY4o8.js +1 -0
- package/dist/web/assets/chunk-BSm8IhPY.js +1 -0
- package/dist/web/assets/chunk-Bi6EQAkf.js +1 -0
- package/dist/web/assets/chunk-D6HyoJCB.js +46 -0
- package/dist/web/assets/chunk-DrEayQLY.js +1 -0
- package/dist/web/assets/chunk-V3YGpFIw.js +1 -0
- package/dist/web/assets/chunk-XGhNFWse.js +1 -0
- package/dist/web/assets/dialogue-card-A5zmbNhu.ogg +0 -0
- package/dist/web/assets/groove-bass-BFNelLKi.ogg +0 -0
- package/dist/web/assets/groove-drums-BY1SBntR.ogg +0 -0
- package/dist/web/assets/groove-harmony-C0CrBzu3.ogg +0 -0
- package/dist/web/assets/groove-lead-CEYPzm5U.ogg +0 -0
- package/dist/web/assets/groove-ln-zQmTb.ogg +0 -0
- package/dist/web/assets/guess-high-CL6mF18x.ogg +0 -0
- package/dist/web/assets/guess-low-C3UnKayZ.ogg +0 -0
- package/dist/web/assets/higher-BevsMIWl.ogg +0 -0
- package/dist/web/assets/identity-0EPS3msD.ogg +0 -0
- package/dist/web/assets/index-DpT0dtHc.css +1 -0
- package/dist/web/assets/intro-DeRh6kUx.ogg +0 -0
- package/dist/web/assets/intro-bass-D63IPU0H.ogg +0 -0
- package/dist/web/assets/intro-drums-Dt9QO534.ogg +0 -0
- package/dist/web/assets/intro-harmony-DBsMG9jJ.ogg +0 -0
- package/dist/web/assets/intro-lead-DWcWS1ia.ogg +0 -0
- package/dist/web/assets/jar-coin-rtCvspuq.ogg +0 -0
- package/dist/web/assets/jetbrains-mono-latin-400-normal-V6pRDFza.woff2 +0 -0
- package/dist/web/assets/jetbrains-mono-latin-600-normal-C8RAYTDA.woff2 +0 -0
- package/dist/web/assets/ledger-tick-C1rQgQGX.ogg +0 -0
- package/dist/web/assets/night-B_bMOZcf.ogg +0 -0
- package/dist/web/assets/night-bass-B-7Ay9ME.ogg +0 -0
- package/dist/web/assets/night-drums-zEtqWXX3.ogg +0 -0
- package/dist/web/assets/night-harmony-C5Ix2yce.ogg +0 -0
- package/dist/web/assets/night-lead-B7KMlRyj.ogg +0 -0
- package/dist/web/assets/ourturn-DX78hTEz.ogg +0 -0
- package/dist/web/assets/plus-jakarta-sans-latin-400-normal-Dhut76fR.woff2 +0 -0
- package/dist/web/assets/plus-jakarta-sans-latin-500-normal-Bf-nb4oT.woff2 +0 -0
- package/dist/web/assets/plus-jakarta-sans-latin-600-normal-DLTa1BUW.woff2 +0 -0
- package/dist/web/assets/plus-jakarta-sans-latin-700-normal-CfpNZvy6.woff2 +0 -0
- package/dist/web/assets/reveal-BmWAGHih.ogg +0 -0
- package/dist/web/assets/review-split-Dac4zagw.ogg +0 -0
- package/dist/web/assets/shutter-uhz2Y9S9.ogg +0 -0
- package/dist/web/assets/soclose-CiUFR5St.ogg +0 -0
- package/dist/web/assets/stinger-TnnzHAMN.ogg +0 -0
- package/dist/web/assets/stomp-mzIk4cGm.ogg +0 -0
- package/dist/web/assets/syne-latin-700-normal-AF3Rs61n.woff2 +0 -0
- package/dist/web/assets/syne-latin-800-normal-EehdNYzx.woff2 +0 -0
- package/dist/web/assets/tension-BHvWG5ru.ogg +0 -0
- package/dist/web/assets/tension-bass-4G-2qA9W.ogg +0 -0
- package/dist/web/assets/tension-drums-D7sdehJr.ogg +0 -0
- package/dist/web/assets/tension-harmony-FyPldmLb.ogg +0 -0
- package/dist/web/assets/tension-lead-C5uoFMR8.ogg +0 -0
- package/dist/web/assets/why-clock-Dzs1A_ym.ogg +0 -0
- package/dist/web/favicon.svg +1 -0
- package/dist/web/index.html +16 -0
- package/dist/web/licenses/OFL-Archivo.txt +93 -0
- package/dist/web/licenses/OFL-DelaGothic.txt +93 -0
- package/dist/web/licenses/OFL-MartianMono.txt +93 -0
- package/package.json +63 -6
|
@@ -0,0 +1,945 @@
|
|
|
1
|
+
import { EMOJI_NAMES } from '../../report/content/emoji-names.js';
|
|
2
|
+
import { displayLexiconTerm, HEADLINE_TERMS } from '../../report/content/lexicons.js';
|
|
3
|
+
import { INJECTED_USER_TEXT, MAX_MESSAGE_BYTES, MAX_OPEN_WORD_CHARS, CONTENT_EXCLUDED, CONTENT_FIELDS, CONTENT_VETO_ONLY, CONTENT_GATES, LEXICON_HASHES, SCRIPTS, THANKS_LANGUAGES, categoriesFor, censor, fold, isCapsWord, isStopword, validEmoji, validOpenTerm } from '../../report/content/policy.js';
|
|
4
|
+
import { codingDate, localParts } from '../time.js';
|
|
5
|
+
import { groupBy, lowerBound } from '../dataset.js';
|
|
6
|
+
import { MARK, RULE_CLASS, normalizeContentText, redact, redactBlocks } from '../../report/content/redact.js';
|
|
7
|
+
import { splitProse } from './classify.js';
|
|
8
|
+
import { SpaceSaving } from './sketch.js';
|
|
9
|
+
const segmenter = new Intl.Segmenter('und', { granularity: 'word' });
|
|
10
|
+
// UTS #51-shaped sequence pattern. Measured ~25x faster in V8 than /\p{RGI_Emoji}/v on the same input, and equal on
|
|
11
|
+
// ZWJ families, skin tones, flags, keycaps and tag sequences. Text-default symbols (©, ™) are rejected by isEmoji
|
|
12
|
+
// unless followed by VS16, which matches RGI_Emoji behaviour.
|
|
13
|
+
const EMOJI = /\p{Extended_Pictographic}(?:\p{EMod}|️⃣?|[\u{E0020}-\u{E007E}]+\u{E007F})?(?:\p{Extended_Pictographic}(?:\p{EMod}|️⃣?)?)*|\p{Regional_Indicator}{2}|[#*0-9]️⃣/gu;
|
|
14
|
+
const isEmoji = (glyph) => glyph.length <= 32 && Object.hasOwn(EMOJI_NAMES, glyph);
|
|
15
|
+
const SKIN_TONE = /[\u{1F3FB}-\u{1F3FF}]/u;
|
|
16
|
+
const SKIN_TONES = /[\u{1F3FB}-\u{1F3FF}]/gu;
|
|
17
|
+
const EMOTICON = /(?<![\w/:])(?:[:;=8][-^o']?[)(\]\[dDpP/\\|*3oO0]|<3|¯\\_\(ツ\)_\/¯|\^_\^|-_-|o_O|O_o|T_T|xD|XD)(?![\w])/g;
|
|
18
|
+
const CLAUSE = /([.!?;:,()[\]"“”«»…。!?、,;:\n]+)/;
|
|
19
|
+
const SENTENCE_END = /[.!?…。!?]/;
|
|
20
|
+
const CJK = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Thai}]/u;
|
|
21
|
+
const IDENTIFIER = /[_\p{N}.]|\p{Ll}\p{Lu}/u; // snake_case, digits, camelCase, dotted, PascalCase-ish
|
|
22
|
+
const LENGTH_BUCKETS = [1, 3, 10, 30, 100, 300, Infinity];
|
|
23
|
+
const ASCII = /^[\x00-\x7F]*$/;
|
|
24
|
+
const ASCII_WORD = /[A-Za-z0-9_]+(?:['.][A-Za-z0-9_]+)*/g;
|
|
25
|
+
const ASCII_LETTER = /[A-Za-z]/;
|
|
26
|
+
const DOTTED = /[\p{L}\p{M}\p{N}_]+(?:\.[\p{L}\p{M}\p{N}_]+)+/gu;
|
|
27
|
+
const EMOTICON_HINT = /[:;=<^_TxXoO8]/;
|
|
28
|
+
const EMOJI_HINT = /[\p{Extended_Pictographic}\p{Regional_Indicator}\u20e3]/u;
|
|
29
|
+
// Harness interrupt markers written into the user role (L2). Claude Code writes these as plain user text blocks.
|
|
30
|
+
// A Codex <turn_aborted> user block is a harness tag that WRAPPER drops; Codex turn_aborted events and Pi aborted
|
|
31
|
+
// stops are metadata, never content. Marker lines are removed even when other prose shares the message.
|
|
32
|
+
const INTERRUPT_LINE = /^[^\S\r\n]*\[Request interrupted by user(?: for tool use)?(?:…|\.\.\.)?\][^\S\r\n]*$/gim;
|
|
33
|
+
const NEIGHBOUR_LIMIT = 1 << 20;
|
|
34
|
+
const IDENTIFIER_TEXT_LIMIT = 16 * 1024;
|
|
35
|
+
const NEIGHBOUR_HINT = new RegExp(`[\\\\/@${MARK}]`);
|
|
36
|
+
// A word glued to an emoji with no space ("jane👍🏽", "qwhzkvbn😀mrtplxcd") is treated like an identifier.
|
|
37
|
+
const EMOJI_GLUE = /\p{Extended_Pictographic}|\p{Regional_Indicator}|⃣/u;
|
|
38
|
+
const HAS_LETTER = /\p{L}/u;
|
|
39
|
+
const MESSAGE_TOKEN_LIMIT = 4096;
|
|
40
|
+
const SKIP_MESSAGE = Symbol('content message budget');
|
|
41
|
+
const SKIP_TOKENS = Symbol('content message token limit');
|
|
42
|
+
// Phase 2 candidate quality. These rules only remove candidates, never add one.
|
|
43
|
+
const ARTICLES = new Set(['the', 'a', 'an']);
|
|
44
|
+
/** A shorter phrase inside a longer surviving one is dropped when its count is at most this multiple of the longer's. */
|
|
45
|
+
const SUBGRAM_RATIO = 1.2;
|
|
46
|
+
/** A phrase is a mid-clause fragment when one extra word on either side accounts for at least this share of it. */
|
|
47
|
+
const FRAGMENT_SHARE = 0.8;
|
|
48
|
+
function makeNeighbourHasher() {
|
|
49
|
+
// The synthetic demo also runs in the browser. Real ingestion always has Node's HMAC.
|
|
50
|
+
const runtime = globalThis.process;
|
|
51
|
+
const crypto = runtime?.getBuiltinModule?.('node:crypto');
|
|
52
|
+
if (!crypto)
|
|
53
|
+
return undefined;
|
|
54
|
+
const key = crypto.randomBytes(32);
|
|
55
|
+
return (term) => crypto.createHmac('sha256', key).update(fold(term)).digest();
|
|
56
|
+
}
|
|
57
|
+
// Veto words are kept only as the first 64 bits of a keyed HMAC, in an open-addressing table that never evicts.
|
|
58
|
+
// A collision can only veto an extra word. Past NEIGHBOUR_LIMIT entries the analyzer stops producing candidates.
|
|
59
|
+
class DigestSet64 {
|
|
60
|
+
slots = new Uint32Array(2 * 4096);
|
|
61
|
+
size = 0;
|
|
62
|
+
find(hi, lo) {
|
|
63
|
+
const mask = this.slots.length - 2;
|
|
64
|
+
for (let i = ((hi ^ lo) << 1) & mask;; i = (i + 2) & mask) {
|
|
65
|
+
const a = this.slots[i], b = this.slots[i + 1];
|
|
66
|
+
if ((a === 0 && b === 0) || (a === hi && b === lo))
|
|
67
|
+
return i;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
static key(digest) {
|
|
71
|
+
const hi = (digest[0] | digest[1] << 8 | digest[2] << 16 | digest[3] << 24) >>> 0;
|
|
72
|
+
const lo = (digest[4] | digest[5] << 8 | digest[6] << 16 | digest[7] << 24) >>> 0;
|
|
73
|
+
return hi === 0 && lo === 0 ? [0, 1] : [hi, lo];
|
|
74
|
+
}
|
|
75
|
+
add(digest) {
|
|
76
|
+
const [hi, lo] = DigestSet64.key(digest);
|
|
77
|
+
const i = this.find(hi, lo);
|
|
78
|
+
if (this.slots[i] === hi && this.slots[i + 1] === lo)
|
|
79
|
+
return;
|
|
80
|
+
this.slots[i] = hi;
|
|
81
|
+
this.slots[i + 1] = lo;
|
|
82
|
+
if (++this.size * 4 >= this.slots.length) {
|
|
83
|
+
const old = this.slots;
|
|
84
|
+
this.slots = new Uint32Array(old.length * 2);
|
|
85
|
+
for (let j = 0; j < old.length; j += 2) {
|
|
86
|
+
if (old[j] === 0 && old[j + 1] === 0)
|
|
87
|
+
continue;
|
|
88
|
+
const k = this.find(old[j], old[j + 1]);
|
|
89
|
+
this.slots[k] = old[j];
|
|
90
|
+
this.slots[k + 1] = old[j + 1];
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
has(digest) {
|
|
95
|
+
const [hi, lo] = DigestSet64.key(digest);
|
|
96
|
+
const i = this.find(hi, lo);
|
|
97
|
+
return this.slots[i] === hi && this.slots[i + 1] === lo;
|
|
98
|
+
}
|
|
99
|
+
clear() { this.slots = new Uint32Array(2 * 4096); this.size = 0; }
|
|
100
|
+
}
|
|
101
|
+
// Splits identifier-shaped text into the lowercase words an open-vocabulary candidate could contain: letter runs,
|
|
102
|
+
// split again on camelCase (acmeZephyrPortal → acme, zephyr, portal, acmezephyrportal).
|
|
103
|
+
const LETTER_RUN = /\p{L}[\p{L}\p{M}'’ʼ']*/gu;
|
|
104
|
+
const CAMEL = /(?<=\p{Ll})(?=\p{Lu})|(?<=\p{Lu})(?=\p{Lu}\p{Ll})/u;
|
|
105
|
+
export function* identifierWords(text) {
|
|
106
|
+
for (const [run] of text.matchAll(LETTER_RUN)) {
|
|
107
|
+
if (run.length > 64)
|
|
108
|
+
continue;
|
|
109
|
+
yield run;
|
|
110
|
+
if (/\p{Lu}/u.test(run.slice(1)))
|
|
111
|
+
for (const part of run.split(CAMEL))
|
|
112
|
+
if (part !== run)
|
|
113
|
+
yield part;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
// Spaced folder names between two separators (C:\Clients\Quokka Freight Ltd\plan).
|
|
117
|
+
const SPACED_SEGMENT = /(?<=[\\/])[^\\/\r\n"'<>|*?]{1,64}(?=[\\/])/gu;
|
|
118
|
+
const MARK_NEIGHBOUR_AFTER = new RegExp(`[\\\\/@${MARK}][,;:]?[^\\S\\r\\n]*(\\p{L}[\\p{L}\\p{M}'’ʼ']*)`, 'gu');
|
|
119
|
+
const MARK_NEIGHBOUR_BEFORE = new RegExp(`(?<![\\p{L}\\p{M}'’ʼ'])(\\p{L}[\\p{L}\\p{M}'’ʼ']*)(?=[,;:]?[^\\S\\r\\n]*[\\\\/@${MARK}])`, 'gu');
|
|
120
|
+
function segmentWords(text) {
|
|
121
|
+
const out = [];
|
|
122
|
+
for (const s of segmenter.segment(text))
|
|
123
|
+
if (s.isWordLike)
|
|
124
|
+
out.push(s.segment);
|
|
125
|
+
return out;
|
|
126
|
+
}
|
|
127
|
+
function buildMatcher(role, categories) {
|
|
128
|
+
const index = new Map();
|
|
129
|
+
for (const category of categories) {
|
|
130
|
+
if (category.role !== role)
|
|
131
|
+
continue;
|
|
132
|
+
for (const raw of category.phrases) {
|
|
133
|
+
const tokens = segmentWords(fold(raw));
|
|
134
|
+
if (!tokens.length)
|
|
135
|
+
continue;
|
|
136
|
+
const list = index.get(tokens[0]) ?? [];
|
|
137
|
+
list.push({ tokens, category: category.id, key: raw });
|
|
138
|
+
index.set(tokens[0], list);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
for (const list of index.values())
|
|
142
|
+
list.sort((a, b) => b.tokens.length - a.tokens.length); // longest match wins
|
|
143
|
+
return index;
|
|
144
|
+
}
|
|
145
|
+
const USER_TURN = 1;
|
|
146
|
+
const WHY_TURN = 2;
|
|
147
|
+
const SORRY_TURN = 4;
|
|
148
|
+
const ONE_WORD_TURN = 8;
|
|
149
|
+
const GO_ON_SHIFT = 4;
|
|
150
|
+
const scripts = Object.entries(SCRIPTS);
|
|
151
|
+
const addSession = (sessions, session) => {
|
|
152
|
+
if (sessions.size < 5)
|
|
153
|
+
sessions.add(session);
|
|
154
|
+
};
|
|
155
|
+
export class ContentAnalyzer {
|
|
156
|
+
preview;
|
|
157
|
+
timezone;
|
|
158
|
+
vocabulary;
|
|
159
|
+
userMatcher;
|
|
160
|
+
agentMatcher;
|
|
161
|
+
goOnWords;
|
|
162
|
+
oneWordLexicon;
|
|
163
|
+
categories = new Map();
|
|
164
|
+
sessionIndex = new Map();
|
|
165
|
+
sessionInfo = [];
|
|
166
|
+
swearSessions = new Set();
|
|
167
|
+
oneWords = new Map();
|
|
168
|
+
calendar;
|
|
169
|
+
agentOpeners = new Map();
|
|
170
|
+
catchphrasesByHarness = {};
|
|
171
|
+
thanksByLanguage = {};
|
|
172
|
+
userEmojiTotal = 0;
|
|
173
|
+
agentEmojiTotal = 0;
|
|
174
|
+
userProse = 0;
|
|
175
|
+
userOther = 0;
|
|
176
|
+
stackLines = 0;
|
|
177
|
+
letterPrompts = 0;
|
|
178
|
+
oversizedMessagesSkipped = 0;
|
|
179
|
+
timeBudgetMessagesSkipped = 0;
|
|
180
|
+
tokenLimitMessagesSkipped = 0;
|
|
181
|
+
injectedMessagesSkipped = 0;
|
|
182
|
+
analysisMs = 0;
|
|
183
|
+
messageBudgetMs;
|
|
184
|
+
totalBudgetMs;
|
|
185
|
+
failed = false;
|
|
186
|
+
neighbourDigest = makeNeighbourHasher();
|
|
187
|
+
neighbours = new DigestSet64();
|
|
188
|
+
learnedInMessage = new Set();
|
|
189
|
+
suppressCandidates = false;
|
|
190
|
+
/** Every Phase 1 lexicon phrase, tokenized like open vocabulary. Already counted and shown, so never a candidate. */
|
|
191
|
+
lexiconTerms;
|
|
192
|
+
identifierSourcesRead = false;
|
|
193
|
+
duplicateMessagesSkipped = 0;
|
|
194
|
+
deferredMessagesSkipped = 0;
|
|
195
|
+
userWords = new SpaceSaving(4096);
|
|
196
|
+
agentWords = new SpaceSaving(4096);
|
|
197
|
+
userPhrases = new SpaceSaving(8192);
|
|
198
|
+
openers = new SpaceSaving(512);
|
|
199
|
+
userEmoji = new SpaceSaving(512);
|
|
200
|
+
agentEmoji = new SpaceSaving(512);
|
|
201
|
+
userTokens = 0;
|
|
202
|
+
agentTokens = 0;
|
|
203
|
+
recordsSeen = { user: 0, agent: 0 };
|
|
204
|
+
charsSeen = 0;
|
|
205
|
+
proseChars = 0;
|
|
206
|
+
otherChars = 0;
|
|
207
|
+
wrapperBlocks = 0;
|
|
208
|
+
lineKinds = {};
|
|
209
|
+
redactions = {};
|
|
210
|
+
agentRedactions = {};
|
|
211
|
+
scripts = {};
|
|
212
|
+
prompt = {
|
|
213
|
+
count: 0, words: 0, oneWord: 0, questions: 0, lowercaseOnly: 0, shouting: 0, exclaims: 0, longestWords: 0, longestMonth: -1, lengthBuckets: LENGTH_BUCKETS.map(() => 0),
|
|
214
|
+
byMonth: Array(12).fill(0),
|
|
215
|
+
};
|
|
216
|
+
agent = { exclaims: 0 };
|
|
217
|
+
constructor(options = {}) {
|
|
218
|
+
this.timezone = options.timezone ?? 'UTC';
|
|
219
|
+
this.preview = options.previewLexicons === true;
|
|
220
|
+
this.messageBudgetMs = options.messageBudgetMs ?? 250;
|
|
221
|
+
this.totalBudgetMs = options.totalBudgetMs ?? 120_000;
|
|
222
|
+
this.vocabulary = categoriesFor(this.preview);
|
|
223
|
+
this.userMatcher = buildMatcher('user', this.vocabulary);
|
|
224
|
+
this.agentMatcher = buildMatcher('agent', this.vocabulary);
|
|
225
|
+
this.goOnWords = this.vocabulary.find(c => c.id === 'go-on').phrases.filter(w => !w.includes(' '));
|
|
226
|
+
this.oneWordLexicon = new Set(this.vocabulary.filter(c => c.role === 'user' && !c.censor).flatMap(c => c.phrases));
|
|
227
|
+
this.lexiconTerms = new Set(this.vocabulary.flatMap(c => c.phrases.map(raw => segmentWords(fold(raw)).join(' ').replace(/[‘’ʼ']/g, "'"))));
|
|
228
|
+
for (const c of this.vocabulary) {
|
|
229
|
+
this.categories.set(c.id, { total: 0, messages: 0, byHour: Array(24).fill(0), byMonth: Array(12).fill(0),
|
|
230
|
+
sessions: new Set(), terms: new Map() });
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
add(record) {
|
|
234
|
+
if (this.failed || !record.text || !Number.isFinite(record.ts))
|
|
235
|
+
return;
|
|
236
|
+
const start = performance.now();
|
|
237
|
+
try {
|
|
238
|
+
this.addRecord(record, start + this.messageBudgetMs);
|
|
239
|
+
}
|
|
240
|
+
catch (error) {
|
|
241
|
+
this.learnedInMessage.clear();
|
|
242
|
+
if (error === SKIP_MESSAGE || error === SKIP_TOKENS) {
|
|
243
|
+
// Fails closed (R8): a skipped message could have held veto words, so no phrase candidates this run.
|
|
244
|
+
if (error === SKIP_TOKENS)
|
|
245
|
+
this.tokenLimitMessagesSkipped++;
|
|
246
|
+
else
|
|
247
|
+
this.timeBudgetMessagesSkipped++;
|
|
248
|
+
this.suppressCandidates = true;
|
|
249
|
+
}
|
|
250
|
+
else
|
|
251
|
+
this.failed = true;
|
|
252
|
+
}
|
|
253
|
+
finally {
|
|
254
|
+
this.learnedInMessage.clear();
|
|
255
|
+
this.analysisMs += performance.now() - start;
|
|
256
|
+
if (this.analysisMs >= this.totalBudgetMs)
|
|
257
|
+
this.failed = true;
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
disable() { this.failed = true; }
|
|
261
|
+
// R2/H3: every word that sits inside an identifier anywhere in the run vetoes open vocabulary. That covers every
|
|
262
|
+
// token of every path segment (split on - _ . and camelCase), spaced folder names between separators, the words of
|
|
263
|
+
// every redacted path, file name, host, email or URL, words touching a separator, @ or redaction marker, and,
|
|
264
|
+
// through learnIdentifiers, session folders and tool-argument paths the adapters pass in.
|
|
265
|
+
learnWord(word) {
|
|
266
|
+
if (this.suppressCandidates || word.length > MAX_OPEN_WORD_CHARS)
|
|
267
|
+
return;
|
|
268
|
+
if (!this.neighbourDigest) {
|
|
269
|
+
this.suppressCandidates = true;
|
|
270
|
+
return;
|
|
271
|
+
}
|
|
272
|
+
// Within one message the same word is hashed once. The set lives only while that message is processed.
|
|
273
|
+
if (this.learnedInMessage.has(word))
|
|
274
|
+
return;
|
|
275
|
+
this.learnedInMessage.add(word);
|
|
276
|
+
this.neighbours.add(this.neighbourDigest(word));
|
|
277
|
+
if (this.neighbours.size >= NEIGHBOUR_LIMIT) {
|
|
278
|
+
// Never evict: a word dropped from the set could be re-admitted. Stop producing candidates instead.
|
|
279
|
+
this.suppressCandidates = true;
|
|
280
|
+
this.neighbours.clear();
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
learnWords(text) {
|
|
284
|
+
for (const word of identifierWords(text))
|
|
285
|
+
this.learnWord(word);
|
|
286
|
+
}
|
|
287
|
+
learnRedaction = (_rule, match) => this.learnWords(match);
|
|
288
|
+
rememberNeighbours(text) {
|
|
289
|
+
if (this.suppressCandidates)
|
|
290
|
+
return;
|
|
291
|
+
const glued = EMOJI_GLUE.test(text);
|
|
292
|
+
if (!glued && !NEIGHBOUR_HINT.test(text))
|
|
293
|
+
return;
|
|
294
|
+
for (const token of text.split(/\s+/)) {
|
|
295
|
+
if (NEIGHBOUR_HINT.test(token) || (glued && EMOJI_GLUE.test(token) && HAS_LETTER.test(token)))
|
|
296
|
+
this.learnWords(token);
|
|
297
|
+
}
|
|
298
|
+
if (!NEIGHBOUR_HINT.test(text))
|
|
299
|
+
return;
|
|
300
|
+
if (/[\\/]/.test(text))
|
|
301
|
+
for (const [segment] of text.matchAll(SPACED_SEGMENT))
|
|
302
|
+
this.learnWords(segment);
|
|
303
|
+
for (const pattern of [MARK_NEIGHBOUR_AFTER, MARK_NEIGHBOUR_BEFORE]) {
|
|
304
|
+
for (const match of text.matchAll(pattern))
|
|
305
|
+
this.learnWord(match[1]);
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
// Identifier text from outside analyzed prose: session and project folders ('path', every word) and tool
|
|
309
|
+
// arguments ('text', only path-, file-, host- and address-shaped parts). Never counted, never stored as text.
|
|
310
|
+
learnIdentifiers(text, kind) {
|
|
311
|
+
if (this.failed || !text)
|
|
312
|
+
return;
|
|
313
|
+
this.identifierSourcesRead = true;
|
|
314
|
+
if (this.suppressCandidates)
|
|
315
|
+
return;
|
|
316
|
+
try {
|
|
317
|
+
const bounded = text.length > IDENTIFIER_TEXT_LIMIT ? text.slice(0, IDENTIFIER_TEXT_LIMIT) : text;
|
|
318
|
+
if (kind === 'path') {
|
|
319
|
+
this.learnWords(normalizeContentText(bounded));
|
|
320
|
+
return;
|
|
321
|
+
}
|
|
322
|
+
for (const line of normalizeContentText(bounded).split(/\r?\n/)) {
|
|
323
|
+
if (!line.trim())
|
|
324
|
+
continue;
|
|
325
|
+
this.rememberNeighbours(line);
|
|
326
|
+
redact(line, this.learnRedaction);
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
catch {
|
|
330
|
+
this.suppressCandidates = true;
|
|
331
|
+
}
|
|
332
|
+
finally {
|
|
333
|
+
this.learnedInMessage.clear();
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
addRecord(record, deadline) {
|
|
337
|
+
if (record.text.length > MAX_MESSAGE_BYTES ||
|
|
338
|
+
(record.text.length > MAX_MESSAGE_BYTES / 3 && encoder.encode(record.text).byteLength > MAX_MESSAGE_BYTES)) {
|
|
339
|
+
this.oversizedMessagesSkipped++;
|
|
340
|
+
return;
|
|
341
|
+
}
|
|
342
|
+
const checkTime = () => { if (performance.now() >= deadline)
|
|
343
|
+
throw SKIP_MESSAGE; };
|
|
344
|
+
const blocks = redactBlocks(record.text);
|
|
345
|
+
const text = record.role === 'user' && blocks.text.includes('[Request ') ? blocks.text.replace(INTERRUPT_LINE, '') : blocks.text;
|
|
346
|
+
if (record.role === 'user' && INJECTED_USER_TEXT.test(text)) {
|
|
347
|
+
this.injectedMessagesSkipped++;
|
|
348
|
+
return;
|
|
349
|
+
}
|
|
350
|
+
this.rememberNeighbours(text);
|
|
351
|
+
const split = splitProse(text);
|
|
352
|
+
checkTime();
|
|
353
|
+
const pendingRedactions = { ...blocks.hits };
|
|
354
|
+
const emoji = [];
|
|
355
|
+
const clauses = [];
|
|
356
|
+
let plannedTokens = 0;
|
|
357
|
+
let exclaim = false;
|
|
358
|
+
for (const rawLine of split.prose) {
|
|
359
|
+
const { text: scrubbed, hits } = redact(rawLine, this.learnRedaction);
|
|
360
|
+
if (hits)
|
|
361
|
+
for (const [rule, n] of Object.entries(hits))
|
|
362
|
+
pendingRedactions[rule] = (pendingRedactions[rule] ?? 0) + n;
|
|
363
|
+
this.rememberNeighbours(scrubbed);
|
|
364
|
+
const ascii = ASCII.test(scrubbed);
|
|
365
|
+
let line = scrubbed;
|
|
366
|
+
if (!ascii && EMOJI_HINT.test(line))
|
|
367
|
+
line = line.replace(EMOJI, glyph => {
|
|
368
|
+
// R7: skin-tone modifiers are folded to the base emoji before anything is counted.
|
|
369
|
+
const base = SKIN_TONE.test(glyph) ? glyph.replace(SKIN_TONES, '') : glyph;
|
|
370
|
+
if (isEmoji(base))
|
|
371
|
+
emoji.push(base);
|
|
372
|
+
return MARK;
|
|
373
|
+
});
|
|
374
|
+
if (EMOTICON_HINT.test(line))
|
|
375
|
+
line = line.replace(EMOTICON, MARK);
|
|
376
|
+
exclaim ||= line.includes('!');
|
|
377
|
+
if (!ascii)
|
|
378
|
+
line = line.replace(/[‘’ʼ']/g, "'");
|
|
379
|
+
const dot = line.indexOf('.');
|
|
380
|
+
if (dot >= 0 && dot < line.length - 1)
|
|
381
|
+
line = line.replace(DOTTED, MARK);
|
|
382
|
+
let startsSentence = true;
|
|
383
|
+
for (const [part, clause] of line.split(CLAUSE).entries()) {
|
|
384
|
+
checkTime();
|
|
385
|
+
if (part % 2 === 1) {
|
|
386
|
+
if (SENTENCE_END.test(clause))
|
|
387
|
+
startsSentence = true;
|
|
388
|
+
continue;
|
|
389
|
+
}
|
|
390
|
+
if (!clause.trim())
|
|
391
|
+
continue;
|
|
392
|
+
const ownAscii = ascii || ASCII.test(clause);
|
|
393
|
+
const words = ownAscii ? (clause.match(ASCII_WORD) ?? []) : segmentWords(clause);
|
|
394
|
+
plannedTokens += words.length;
|
|
395
|
+
if (plannedTokens > MESSAGE_TOKEN_LIMIT)
|
|
396
|
+
throw SKIP_TOKENS;
|
|
397
|
+
if (!words.length)
|
|
398
|
+
continue;
|
|
399
|
+
clauses.push({ words, ascii: ownAscii, startsSentence });
|
|
400
|
+
startsSentence = false;
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
checkTime();
|
|
404
|
+
// Commit only after the bounded text pass succeeds. A skipped message never partly updates the report.
|
|
405
|
+
const isUser = record.role === 'user';
|
|
406
|
+
const sink = isUser ? this.redactions : this.agentRedactions;
|
|
407
|
+
for (const [rule, n] of Object.entries(pendingRedactions))
|
|
408
|
+
sink[rule] = (sink[rule] ?? 0) + n;
|
|
409
|
+
this.proseChars += split.proseChars;
|
|
410
|
+
this.otherChars += split.otherChars;
|
|
411
|
+
this.wrapperBlocks += split.wrapperBlocks;
|
|
412
|
+
if (isUser) {
|
|
413
|
+
this.userProse += split.proseChars;
|
|
414
|
+
this.userOther += split.otherChars;
|
|
415
|
+
this.stackLines += split.kinds.stack ?? 0;
|
|
416
|
+
}
|
|
417
|
+
for (const [kind, n] of Object.entries(split.kinds))
|
|
418
|
+
this.lineKinds[kind] = (this.lineKinds[kind] ?? 0) + n;
|
|
419
|
+
if (!plannedTokens && !emoji.length)
|
|
420
|
+
return;
|
|
421
|
+
const local = localParts(record.ts, this.timezone);
|
|
422
|
+
const { hour } = local;
|
|
423
|
+
const beforeBoundary = local.minuteOfDay < 240;
|
|
424
|
+
if (this.calendar?.date !== local.date || this.calendar.beforeBoundary !== beforeBoundary) {
|
|
425
|
+
this.calendar = { date: local.date, beforeBoundary, month: Number(local.date.slice(5, 7)) - 1,
|
|
426
|
+
day: Date.parse(codingDate(local)) / 86_400_000 };
|
|
427
|
+
}
|
|
428
|
+
const { month, day } = this.calendar;
|
|
429
|
+
let session = this.sessionIndex.get(record.session);
|
|
430
|
+
if (session === undefined) {
|
|
431
|
+
session = this.sessionInfo.length;
|
|
432
|
+
this.sessionIndex.set(record.session, session);
|
|
433
|
+
this.sessionInfo.push({ start: record.ts, end: record.ts, lastPromptTs: -Infinity, lastPromptThanks: false,
|
|
434
|
+
turnTimes: [], turnFlags: [], turnsOutOfOrder: false });
|
|
435
|
+
}
|
|
436
|
+
const info = this.sessionInfo[session];
|
|
437
|
+
info.start = Math.min(info.start, record.ts);
|
|
438
|
+
info.end = Math.max(info.end, record.ts);
|
|
439
|
+
this.charsSeen += record.text.length;
|
|
440
|
+
this.recordsSeen[record.role]++;
|
|
441
|
+
const emojiSketch = isUser ? this.userEmoji : this.agentEmoji;
|
|
442
|
+
for (const glyph of emoji)
|
|
443
|
+
emojiSketch.add(glyph, session, day);
|
|
444
|
+
if (isUser)
|
|
445
|
+
this.userEmojiTotal += emoji.length;
|
|
446
|
+
else
|
|
447
|
+
this.agentEmojiTotal += emoji.length;
|
|
448
|
+
const matcher = isUser ? this.userMatcher : this.agentMatcher;
|
|
449
|
+
const hitCategories = new Set();
|
|
450
|
+
let messageTokens = 0;
|
|
451
|
+
let opener;
|
|
452
|
+
let openerCapitalized = false;
|
|
453
|
+
let agentOpener;
|
|
454
|
+
const marks = { why: 0, catchphrases: 0 };
|
|
455
|
+
let letterCount = 0;
|
|
456
|
+
let capsWords = 0;
|
|
457
|
+
let letterWords = 0;
|
|
458
|
+
let hasUpper = false;
|
|
459
|
+
let onlyToken;
|
|
460
|
+
for (const { words, ascii: ownAscii, startsSentence } of clauses) {
|
|
461
|
+
let afterWords = !startsSentence;
|
|
462
|
+
const tokens = [];
|
|
463
|
+
const safe = [];
|
|
464
|
+
const capital = [];
|
|
465
|
+
for (const raw of words) {
|
|
466
|
+
const lower = raw.toLowerCase();
|
|
467
|
+
if (isUser) {
|
|
468
|
+
const hasLetter = ownAscii ? ASCII_LETTER.test(raw) : /\p{L}/u.test(raw);
|
|
469
|
+
if (hasLetter) {
|
|
470
|
+
letterWords++;
|
|
471
|
+
if (letterCount < 3)
|
|
472
|
+
letterCount += raw.match(/\p{L}/gu)?.length ?? 0;
|
|
473
|
+
if (raw !== lower) {
|
|
474
|
+
hasUpper = true;
|
|
475
|
+
if (isCapsWord(raw))
|
|
476
|
+
capsWords++;
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
if (!ownAscii)
|
|
480
|
+
this.countScript(raw);
|
|
481
|
+
else if (hasLetter)
|
|
482
|
+
this.scripts.Latin = (this.scripts.Latin ?? 0) + 1;
|
|
483
|
+
}
|
|
484
|
+
tokens.push(lower);
|
|
485
|
+
safe.push(lower.length > MAX_OPEN_WORD_CHARS || IDENTIFIER.test(raw) ? MARK : lower);
|
|
486
|
+
capital.push(afterWords && raw[0] !== lower[0]);
|
|
487
|
+
afterWords = true;
|
|
488
|
+
}
|
|
489
|
+
messageTokens += tokens.length;
|
|
490
|
+
if (isUser && opener === undefined) {
|
|
491
|
+
opener = safe.slice(0, 2);
|
|
492
|
+
openerCapitalized = capital.slice(0, 2).some(Boolean);
|
|
493
|
+
}
|
|
494
|
+
if (!isUser && agentOpener === undefined)
|
|
495
|
+
agentOpener = tokens.slice(0, 4);
|
|
496
|
+
if (isUser && messageTokens === 1)
|
|
497
|
+
onlyToken = safe[0];
|
|
498
|
+
this.matchPhrases(tokens, matcher, hitCategories, hour, month, session, marks);
|
|
499
|
+
this.countOpenVocabulary(safe, capital, isUser, session, day);
|
|
500
|
+
}
|
|
501
|
+
for (const id of hitCategories)
|
|
502
|
+
this.categories.get(id).messages++;
|
|
503
|
+
const thanks = hitCategories.has('thanks');
|
|
504
|
+
const goOn = onlyToken && messageTokens === 1 ? this.goOnWords.indexOf(onlyToken) + 1 : 0;
|
|
505
|
+
info.turnsOutOfOrder ||= record.ts < (info.turnTimes[info.turnTimes.length - 1] ?? -Infinity);
|
|
506
|
+
info.turnTimes.push(record.ts);
|
|
507
|
+
info.turnFlags.push((goOn << GO_ON_SHIFT) | (isUser ? USER_TURN : 0) | (marks.why ? WHY_TURN : 0) |
|
|
508
|
+
(hitCategories.has('agent-sorry') ? SORRY_TURN : 0) | (messageTokens === 1 ? ONE_WORD_TURN : 0));
|
|
509
|
+
if (isUser) {
|
|
510
|
+
this.userTokens += messageTokens;
|
|
511
|
+
if (hitCategories.has('swear-mild') || hitCategories.has('swear-strong'))
|
|
512
|
+
addSession(this.swearSessions, session);
|
|
513
|
+
if (record.ts >= info.lastPromptTs) {
|
|
514
|
+
info.lastPromptThanks = thanks;
|
|
515
|
+
info.lastPromptTs = record.ts;
|
|
516
|
+
}
|
|
517
|
+
const p = this.prompt;
|
|
518
|
+
p.count++;
|
|
519
|
+
p.byMonth[month]++;
|
|
520
|
+
p.words += messageTokens;
|
|
521
|
+
p.lengthBuckets[LENGTH_BUCKETS.findIndex(limit => messageTokens <= limit)]++;
|
|
522
|
+
if (messageTokens > p.longestWords) {
|
|
523
|
+
p.longestWords = messageTokens;
|
|
524
|
+
p.longestMonth = month;
|
|
525
|
+
}
|
|
526
|
+
if (messageTokens === 1) {
|
|
527
|
+
p.oneWord++;
|
|
528
|
+
if (onlyToken && this.oneWordLexicon.has(onlyToken))
|
|
529
|
+
this.oneWords.set(onlyToken, (this.oneWords.get(onlyToken) ?? 0) + 1);
|
|
530
|
+
}
|
|
531
|
+
const opening = opener?.join(' ');
|
|
532
|
+
if (opening && this.safeSketchTerm(opening))
|
|
533
|
+
this.openers.add(opening, session, day, openerCapitalized);
|
|
534
|
+
if (/\?\s*$/.test(split.prose.at(-1) ?? ''))
|
|
535
|
+
p.questions++;
|
|
536
|
+
if (letterCount >= 3) {
|
|
537
|
+
this.letterPrompts++;
|
|
538
|
+
if (!hasUpper)
|
|
539
|
+
p.lowercaseOnly++;
|
|
540
|
+
}
|
|
541
|
+
if (capsWords >= 3 && capsWords / letterWords >= 0.5)
|
|
542
|
+
p.shouting++;
|
|
543
|
+
if (exclaim)
|
|
544
|
+
p.exclaims++;
|
|
545
|
+
}
|
|
546
|
+
else {
|
|
547
|
+
this.agentTokens += messageTokens;
|
|
548
|
+
if (exclaim)
|
|
549
|
+
this.agent.exclaims++;
|
|
550
|
+
if (record.harness && marks.catchphrases) {
|
|
551
|
+
this.catchphrasesByHarness[record.harness] = (this.catchphrasesByHarness[record.harness] ?? 0) + marks.catchphrases;
|
|
552
|
+
}
|
|
553
|
+
const first = agentOpener?.[0];
|
|
554
|
+
const opening = first && this.agentMatcher.get(first)?.find(p => p.tokens.length >= 2 &&
|
|
555
|
+
p.tokens.length <= agentOpener.length && p.tokens.every((token, i) => token === agentOpener[i]));
|
|
556
|
+
if (opening) {
|
|
557
|
+
const state = this.agentOpeners.get(opening.key) ?? { count: 0, sessions: new Set() };
|
|
558
|
+
state.count++;
|
|
559
|
+
addSession(state.sessions, session);
|
|
560
|
+
this.agentOpeners.set(opening.key, state);
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
countScript(token) {
|
|
565
|
+
for (const [name, re] of scripts) {
|
|
566
|
+
if (re.test(token)) {
|
|
567
|
+
this.scripts[name] = (this.scripts[name] ?? 0) + 1;
|
|
568
|
+
return;
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
matchPhrases(tokens, matcher, hits, hour, month, session, marks) {
|
|
573
|
+
let nextPosition;
|
|
574
|
+
for (let i = 0; i < tokens.length; i++) {
|
|
575
|
+
const phrases = matcher.get(tokens[i]);
|
|
576
|
+
if (!phrases)
|
|
577
|
+
continue;
|
|
578
|
+
for (const phrase of phrases) {
|
|
579
|
+
if (i < (nextPosition?.get(phrase.category) ?? 0) || i + phrase.tokens.length > tokens.length ||
|
|
580
|
+
!phrase.tokens.every((token, offset) => token === tokens[i + offset]))
|
|
581
|
+
continue;
|
|
582
|
+
const state = this.categories.get(phrase.category);
|
|
583
|
+
state.total++;
|
|
584
|
+
state.byHour[hour]++;
|
|
585
|
+
state.byMonth[month]++;
|
|
586
|
+
addSession(state.sessions, session);
|
|
587
|
+
const term = state.terms.get(phrase.key) ?? { count: 0, sessions: new Set() };
|
|
588
|
+
term.count++;
|
|
589
|
+
addSession(term.sessions, session);
|
|
590
|
+
state.terms.set(phrase.key, term);
|
|
591
|
+
hits.add(phrase.category);
|
|
592
|
+
(nextPosition ??= new Map()).set(phrase.category, i + phrase.tokens.length);
|
|
593
|
+
if (phrase.category === 'why')
|
|
594
|
+
marks.why++;
|
|
595
|
+
if (phrase.category === 'agent-agree' &&
|
|
596
|
+
(phrase.key === "you're absolutely right" || phrase.key === 'you are absolutely right'))
|
|
597
|
+
marks.catchphrases++;
|
|
598
|
+
if (phrase.category === 'thanks') {
|
|
599
|
+
const lang = THANKS_LANGUAGES[phrase.key] ?? 'en';
|
|
600
|
+
this.thanksByLanguage[lang] = (this.thanksByLanguage[lang] ?? 0) + 1;
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
safeSketchTerm(term) {
|
|
606
|
+
return term.length <= CONTENT_GATES.maxChars && !term.includes(MARK);
|
|
607
|
+
}
|
|
608
|
+
countOpenVocabulary(tokens, capital, isUser, session, day) {
|
|
609
|
+
const words = isUser ? this.userWords : this.agentWords;
|
|
610
|
+
// Identifier-like and numeric tokens act as hard phrase boundaries.
|
|
611
|
+
const canEnd = [];
|
|
612
|
+
for (let start = 0; start < tokens.length;) {
|
|
613
|
+
let end = start;
|
|
614
|
+
for (; end < tokens.length; end++) {
|
|
615
|
+
const token = tokens[end];
|
|
616
|
+
if (!this.safeSketchTerm(token))
|
|
617
|
+
break;
|
|
618
|
+
const keep = !isStopword(token, this.preview);
|
|
619
|
+
canEnd[end] = keep;
|
|
620
|
+
if (keep && (token.length >= 2 || CJK.test(token)))
|
|
621
|
+
words.add(token, session, day, capital[end]);
|
|
622
|
+
}
|
|
623
|
+
if (isUser) {
|
|
624
|
+
// Keep the sketch's update order: changing it can change which keys are evicted.
|
|
625
|
+
for (let n = 2; n <= 4; n++) {
|
|
626
|
+
for (let i = start; i + n <= end; i++) {
|
|
627
|
+
if (!canEnd[i + n - 1])
|
|
628
|
+
continue;
|
|
629
|
+
let term = tokens[i];
|
|
630
|
+
let capitalized = capital[i];
|
|
631
|
+
for (let j = i + 1; j < i + n; j++) {
|
|
632
|
+
term += ' ' + tokens[j];
|
|
633
|
+
capitalized ||= capital[j];
|
|
634
|
+
}
|
|
635
|
+
if (term.length <= CONTENT_GATES.maxChars)
|
|
636
|
+
this.userPhrases.add(term, session, day, capitalized);
|
|
637
|
+
}
|
|
638
|
+
}
|
|
639
|
+
}
|
|
640
|
+
start = end + 1;
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
passes(key, entry) {
|
|
644
|
+
const g = CONTENT_GATES;
|
|
645
|
+
const lower = entry.count - entry.error;
|
|
646
|
+
return lower >= g.minCount && entry.sessions.length >= g.minSessions && entry.days.length >= g.minDays &&
|
|
647
|
+
entry.capitalized / lower <= g.maxCapitalizedShare && validOpenTerm(key, this.preview) && !this.lexiconTerms.has(key) &&
|
|
648
|
+
(!this.neighbours.size || !key.split(' ').some(word => this.neighbours.has(this.neighbourDigest(word))));
|
|
649
|
+
}
|
|
650
|
+
// Phase 2 phrase quality (stricter only). Phase 1 lexicon phrases ("still failing") are already excluded in passes().
|
|
651
|
+
// 0. A phrase that starts or ends with a lexicon phrase is dropped too: that part is already counted and shown, and
|
|
652
|
+
// the rest is its own candidate ("check the amber build", "revert the interrupted build").
|
|
653
|
+
// 1. A leading article plus one word ("the amber") is not a phrase.
|
|
654
|
+
// 2. A phrase may not start mid-clause:
|
|
655
|
+
// - on a function word other than an article ("is still failing", "at midnight");
|
|
656
|
+
// - on a word that some other word (not an article) precedes in at least FRAGMENT_SHARE of its uses
|
|
657
|
+
// ("sure the amber": "make sure"; "error on the replay": "same error").
|
|
658
|
+
// 3. A phrase may not end mid-clause: on a word that one word follows in at least FRAGMENT_SHARE of its uses
|
|
659
|
+
// ("make sure the amber": "amber build").
|
|
660
|
+
// 4. An article-led phrase is dropped when the same phrase without the article survives ("the amber build").
|
|
661
|
+
// 5. Overlapping n-grams collapse to the maximal phrase when the shorter one's count is within SUBGRAM_RATIO of it.
|
|
662
|
+
phraseCandidates(limit) {
|
|
663
|
+
if (this.suppressCandidates)
|
|
664
|
+
return [];
|
|
665
|
+
const pool = this.userPhrases.top(limit * 4, (term, e) => this.passes(term, e)).map(([term, e]) => ({
|
|
666
|
+
term, count: e.count - e.error, sessions: e.sessions.length, days: e.days.length,
|
|
667
|
+
}));
|
|
668
|
+
// The strongest single left and right neighbour of every word, from the counted bigrams.
|
|
669
|
+
const leftOf = new Map();
|
|
670
|
+
const rightOf = new Map();
|
|
671
|
+
for (const [key, entry] of this.userPhrases.table) {
|
|
672
|
+
const space = key.indexOf(' ');
|
|
673
|
+
if (space < 0 || key.indexOf(' ', space + 1) >= 0)
|
|
674
|
+
continue;
|
|
675
|
+
const first = key.slice(0, space);
|
|
676
|
+
const second = key.slice(space + 1);
|
|
677
|
+
const n = entry.count - entry.error;
|
|
678
|
+
if (!ARTICLES.has(first))
|
|
679
|
+
leftOf.set(second, Math.max(leftOf.get(second) ?? 0, n));
|
|
680
|
+
rightOf.set(first, Math.max(rightOf.get(first) ?? 0, n));
|
|
681
|
+
}
|
|
682
|
+
const uses = (word) => this.userWords.lower(word);
|
|
683
|
+
const boundTo = (neighbour, word) => {
|
|
684
|
+
const total = uses(word);
|
|
685
|
+
return neighbour !== undefined && total > 0 && neighbour >= total * FRAGMENT_SHARE;
|
|
686
|
+
};
|
|
687
|
+
const shaped = pool.filter(({ term }) => {
|
|
688
|
+
const words = term.split(' ');
|
|
689
|
+
const first = words[0];
|
|
690
|
+
const last = words.at(-1);
|
|
691
|
+
if (words.length === 2 && ARTICLES.has(first))
|
|
692
|
+
return false;
|
|
693
|
+
for (let k = 1; k < words.length && k <= 3; k++) {
|
|
694
|
+
if (this.lexiconTerms.has(words.slice(0, k).join(' ')) || this.lexiconTerms.has(words.slice(-k).join(' ')))
|
|
695
|
+
return false;
|
|
696
|
+
}
|
|
697
|
+
if (!ARTICLES.has(first) && isStopword(first, this.preview))
|
|
698
|
+
return false;
|
|
699
|
+
if (!ARTICLES.has(first) && boundTo(leftOf.get(first), first))
|
|
700
|
+
return false;
|
|
701
|
+
if (boundTo(rightOf.get(last), last))
|
|
702
|
+
return false;
|
|
703
|
+
return true;
|
|
704
|
+
});
|
|
705
|
+
const present = new Set(shaped.map(c => c.term));
|
|
706
|
+
const unarticled = shaped.filter(({ term }) => {
|
|
707
|
+
const [first, ...rest] = term.split(' ');
|
|
708
|
+
return !(ARTICLES.has(first) && present.has(rest.join(' ')));
|
|
709
|
+
});
|
|
710
|
+
const inside = (outer, inner) => outer !== inner && ` ${outer} `.includes(` ${inner} `);
|
|
711
|
+
return unarticled
|
|
712
|
+
.filter(c => !unarticled.some(o => inside(o.term, c.term) && c.count <= o.count * SUBGRAM_RATIO))
|
|
713
|
+
.slice(0, limit);
|
|
714
|
+
}
|
|
715
|
+
candidates(sketch, limit) {
|
|
716
|
+
if (this.suppressCandidates)
|
|
717
|
+
return [];
|
|
718
|
+
return sketch.top(limit, (term, e) => this.passes(term, e)).map(([term, e]) => ({
|
|
719
|
+
term, count: e.count - e.error, sessions: e.sessions.length, days: e.days.length,
|
|
720
|
+
}));
|
|
721
|
+
}
|
|
722
|
+
finish(join) {
|
|
723
|
+
if (this.failed)
|
|
724
|
+
throw new Error('CONTENT_ANALYSIS_UNAVAILABLE');
|
|
725
|
+
const start = performance.now();
|
|
726
|
+
const chapter = this.finishChapter(join);
|
|
727
|
+
if (this.analysisMs + performance.now() - start >= this.totalBudgetMs)
|
|
728
|
+
throw new Error('CONTENT_ANALYSIS_UNAVAILABLE');
|
|
729
|
+
return chapter;
|
|
730
|
+
}
|
|
731
|
+
finishChapter(join) {
|
|
732
|
+
const lexiconVersion = this.preview ? 'lex-2026.1-preview' : 'lex-2026.1-en';
|
|
733
|
+
const words = this.agentTokens ? this.candidates(this.userWords, 400).flatMap(word => {
|
|
734
|
+
const a = word.count;
|
|
735
|
+
const b = Math.min(this.agentTokens, this.agentWords.upper(word.term));
|
|
736
|
+
if (a / this.userTokens <= b / this.agentTokens)
|
|
737
|
+
return [];
|
|
738
|
+
const rate = (a + b) / (this.userTokens + this.agentTokens);
|
|
739
|
+
const pairs = [[a, this.userTokens * rate], [b, this.agentTokens * rate],
|
|
740
|
+
[this.userTokens - a, this.userTokens * (1 - rate)], [this.agentTokens - b, this.agentTokens * (1 - rate)]];
|
|
741
|
+
const g2 = 2 * pairs.reduce((sum, [n, expected]) => n ? sum + n * Math.log(n / expected) : sum, 0);
|
|
742
|
+
return g2 >= 10.83 ? [{ ...word, agentCountAtMost: b, g2: Math.round(g2 * 100) / 100 }] : [];
|
|
743
|
+
}).sort((a, b) => b.g2 - a.g2).slice(0, 15) : [];
|
|
744
|
+
const topLexicon = (terms, censored = false) => [...terms].sort((a, b) => b[1].count - a[1].count).slice(0, 5)
|
|
745
|
+
.map(([canonical, state]) => {
|
|
746
|
+
const term = censored ? censor(canonical) : canonical;
|
|
747
|
+
return { term, display: displayLexiconTerm(term), count: state.count, sessions: state.sessions.size };
|
|
748
|
+
});
|
|
749
|
+
const lexicon = this.vocabulary.flatMap(c => {
|
|
750
|
+
const state = this.categories.get(c.id);
|
|
751
|
+
return state.total ? [{
|
|
752
|
+
id: c.id, role: c.role, shareEligible: c.shareEligible, total: state.total, messages: state.messages,
|
|
753
|
+
sessions: state.sessions.size, byHour: state.byHour, byMonth: state.byMonth,
|
|
754
|
+
topTerms: topLexicon(state.terms, c.censor),
|
|
755
|
+
...(HEADLINE_TERMS[c.id] ? { headline: Object.fromEntries(HEADLINE_TERMS[c.id].map(term => [term, state.terms.get(term)?.count ?? 0])) } : {}),
|
|
756
|
+
}] : [];
|
|
757
|
+
});
|
|
758
|
+
const cat = (id) => this.categories.get(id);
|
|
759
|
+
const withPrompts = this.sessionInfo.filter(s => Number.isFinite(s.lastPromptTs));
|
|
760
|
+
if (join) {
|
|
761
|
+
for (const [id, index] of this.sessionIndex) {
|
|
762
|
+
const metadata = join.data.sessionMap.get(id);
|
|
763
|
+
const session = this.sessionInfo[index];
|
|
764
|
+
if (!metadata)
|
|
765
|
+
continue;
|
|
766
|
+
session.start = Math.min(session.start, metadata.startTsMs);
|
|
767
|
+
session.end = Math.max(session.end, metadata.endTsMs);
|
|
768
|
+
}
|
|
769
|
+
}
|
|
770
|
+
const long = withPrompts.filter(s => s.end - s.start >= 2 * 3_600_000);
|
|
771
|
+
const short = withPrompts.filter(s => s.end - s.start < 30 * 60_000);
|
|
772
|
+
const rate = (sessions) => sessions.length >= 10 ? round(sessions.filter(s => s.lastPromptThanks).length / sessions.length) : null;
|
|
773
|
+
const peak = (hours) => hours.reduce((best, n, h) => n > hours[best] ? h : best, 0);
|
|
774
|
+
const swearHours = cat('swear-strong').byHour.map((n, h) => n + cat('swear-mild').byHour[h]);
|
|
775
|
+
const swearTotal = swearHours.reduce((a, b) => a + b, 0);
|
|
776
|
+
const swearPeak = peak(swearHours);
|
|
777
|
+
const whyPeak = peak(cat('why').byHour);
|
|
778
|
+
const redactions = (hits) => {
|
|
779
|
+
const counts = { secret: 0, pii: 0, identifier: 0 };
|
|
780
|
+
for (const [rule, n] of Object.entries(hits))
|
|
781
|
+
counts[RULE_CLASS[rule]] += n;
|
|
782
|
+
return counts;
|
|
783
|
+
};
|
|
784
|
+
const safety = redactions(this.redactions);
|
|
785
|
+
const sketch = (s) => ({ capacity: s.capacity * 2, evictions: s.evictions, errorFloor: s.floor });
|
|
786
|
+
const [winner] = [...this.oneWords].sort((a, b) => b[1] - a[1]);
|
|
787
|
+
const phrases = this.phraseCandidates(20);
|
|
788
|
+
// Openers are a prompt's first two words, so only the article-plus-one-word rule applies ("the quiet").
|
|
789
|
+
const openers = this.prompt.count >= 50 ? this.candidates(this.openers, 10)
|
|
790
|
+
.filter(({ term }) => { const words = term.split(' '); return !(words.length === 2 && ARTICLES.has(words[0])); }) : [];
|
|
791
|
+
const emoji = (s) => s.top(10, (term, e) => e.count - e.error >= 3 && validEmoji(term))
|
|
792
|
+
.map(([emoji, e]) => ({ emoji, name: EMOJI_NAMES[emoji], count: e.count - e.error }));
|
|
793
|
+
let goOnStreak = 0;
|
|
794
|
+
let goOnStreakTerm = null;
|
|
795
|
+
for (const session of this.sessionInfo) {
|
|
796
|
+
let streak = 0;
|
|
797
|
+
let sameTerm = null;
|
|
798
|
+
if (session.turnsOutOfOrder) {
|
|
799
|
+
const order = session.turnTimes.map((_, i) => i).sort((a, b) => session.turnTimes[a] - session.turnTimes[b]);
|
|
800
|
+
session.turnTimes = order.map(i => session.turnTimes[i]);
|
|
801
|
+
session.turnFlags = order.map(i => session.turnFlags[i]);
|
|
802
|
+
session.turnsOutOfOrder = false;
|
|
803
|
+
}
|
|
804
|
+
for (const flags of session.turnFlags) {
|
|
805
|
+
if (!(flags & USER_TURN))
|
|
806
|
+
continue;
|
|
807
|
+
const goOn = this.goOnWords[(flags >> GO_ON_SHIFT) - 1];
|
|
808
|
+
if (!goOn) {
|
|
809
|
+
streak = 0;
|
|
810
|
+
sameTerm = null;
|
|
811
|
+
continue;
|
|
812
|
+
}
|
|
813
|
+
if (!streak)
|
|
814
|
+
sameTerm = goOn;
|
|
815
|
+
else if (sameTerm !== goOn)
|
|
816
|
+
sameTerm = null;
|
|
817
|
+
streak++;
|
|
818
|
+
if (streak > goOnStreak || (streak === goOnStreak && sameTerm && !goOnStreakTerm)) {
|
|
819
|
+
goOnStreak = streak;
|
|
820
|
+
goOnStreakTerm = sameTerm;
|
|
821
|
+
}
|
|
822
|
+
}
|
|
823
|
+
}
|
|
824
|
+
return {
|
|
825
|
+
lexiconVersion, lexicon,
|
|
826
|
+
style: {
|
|
827
|
+
prompts: this.prompt.count, words: this.prompt.words, oneWord: this.prompt.oneWord,
|
|
828
|
+
oneWordTop: winner ? { term: winner[0], display: displayLexiconTerm(winner[0]), count: winner[1] } : null,
|
|
829
|
+
promptsWithLetters: this.letterPrompts, lengthBuckets: this.prompt.lengthBuckets,
|
|
830
|
+
longestWords: this.prompt.longestWords, longestMonth: this.prompt.longestMonth < 0 ? null : this.prompt.longestMonth + 1,
|
|
831
|
+
lowercaseShare: round(this.prompt.lowercaseOnly / Math.max(this.letterPrompts, 1)),
|
|
832
|
+
questionShare: round(this.prompt.questions / Math.max(this.prompt.count, 1)),
|
|
833
|
+
capsPrompts: this.prompt.shouting, userExclaimPrompts: this.prompt.exclaims, agentExclaimReplies: this.agent.exclaims,
|
|
834
|
+
codeShareEstimate: round(this.userOther / Math.max(this.userOther + this.userProse, 1)),
|
|
835
|
+
stackLines: this.stackLines, scripts: this.scripts,
|
|
836
|
+
},
|
|
837
|
+
emoji: { user: emoji(this.userEmoji), agent: emoji(this.agentEmoji), total: this.userEmojiTotal + this.agentEmojiTotal },
|
|
838
|
+
combos: {
|
|
839
|
+
swearPeakHour: swearHours[swearPeak] >= 10 && this.swearSessions.size >= 3 ? swearPeak : null,
|
|
840
|
+
swearSessions: this.swearSessions.size,
|
|
841
|
+
whyPeakHour: cat('why').total >= 25 && cat('why').byHour[whyPeak] >= 10 ? whyPeak : null,
|
|
842
|
+
pleasePer100ByMonth: cat('please').byMonth.map((n, m) => this.prompt.byMonth[m] >= 20 ? round(n / this.prompt.byMonth[m] * 100) : null),
|
|
843
|
+
thanksLastPromptLong: long.length >= 10 && short.length >= 10 ? rate(long) : null,
|
|
844
|
+
thanksLastPromptShort: long.length >= 10 && short.length >= 10 ? rate(short) : null,
|
|
845
|
+
apologies: { agent: cat('agent-sorry').total, user: cat('sorry-user').total },
|
|
846
|
+
agentOpener: topLexicon(new Map([...this.agentOpeners].filter(([, row]) => row.count >= 20 && row.sessions.size >= 5)))[0] ?? null,
|
|
847
|
+
goOnStreak, goOnStreakTerm, thanksByLanguage: this.thanksByLanguage, catchphrasesByHarness: this.catchphrasesByHarness,
|
|
848
|
+
swearAtRhythmPeak: join?.rhythmHour != null && swearTotal >= 10 && this.swearSessions.size >= 3
|
|
849
|
+
? swearHours[join.rhythmHour] : null,
|
|
850
|
+
...this.metadataCombos(join),
|
|
851
|
+
},
|
|
852
|
+
safety,
|
|
853
|
+
...((phrases.length || words.length || openers.length) ? { private: { localOnly: true, reviewRequired: true, phrases, words, openers } } : {}),
|
|
854
|
+
receipt: {
|
|
855
|
+
mode: 'content-opt-in', fieldsRead: CONTENT_FIELDS, fieldsNeverRead: CONTENT_EXCLUDED,
|
|
856
|
+
...(this.identifierSourcesRead ? { vetoOnlyFields: CONTENT_VETO_ONLY } : {}),
|
|
857
|
+
categoriesDerived: lexicon.map(c => c.id), lexiconHash: LEXICON_HASHES[lexiconVersion], rawBytesPersisted: 0,
|
|
858
|
+
recordsSeen: this.recordsSeen, charsSeen: this.charsSeen, oversizedMessagesSkipped: this.oversizedMessagesSkipped + this.deferredMessagesSkipped,
|
|
859
|
+
duplicateMessagesSkipped: this.duplicateMessagesSkipped,
|
|
860
|
+
...(this.timeBudgetMessagesSkipped ? { timeBudgetMessagesSkipped: this.timeBudgetMessagesSkipped } : {}),
|
|
861
|
+
...(this.tokenLimitMessagesSkipped ? { tokenLimitMessagesSkipped: this.tokenLimitMessagesSkipped } : {}),
|
|
862
|
+
...(this.injectedMessagesSkipped ? { injectedMessagesSkipped: this.injectedMessagesSkipped } : {}),
|
|
863
|
+
...(this.suppressCandidates ? { phraseCandidatesSuppressed: true } : {}),
|
|
864
|
+
proseShare: round(this.proseChars / Math.max(this.proseChars + this.otherChars, 1)),
|
|
865
|
+
droppedLinesByKind: Object.fromEntries(Object.entries(this.lineKinds).filter(([k]) => k !== 'prose' && k !== 'blank')),
|
|
866
|
+
harnessWrapperBlocksDropped: this.wrapperBlocks, redactions: { user: safety, agent: redactions(this.agentRedactions) },
|
|
867
|
+
sketches: { userWords: sketch(this.userWords), agentWords: sketch(this.agentWords), phrases: sketch(this.userPhrases),
|
|
868
|
+
openers: sketch(this.openers), userEmoji: sketch(this.userEmoji), agentEmoji: sketch(this.agentEmoji) },
|
|
869
|
+
gates: CONTENT_GATES,
|
|
870
|
+
},
|
|
871
|
+
};
|
|
872
|
+
}
|
|
873
|
+
metadataCombos(join) {
|
|
874
|
+
let whyDuringLongestNight = null;
|
|
875
|
+
let mainEventLastPromptThanks = null;
|
|
876
|
+
let oneWordLeashMaxToolCalls = null;
|
|
877
|
+
let apologiesAfterError = null;
|
|
878
|
+
if (join) {
|
|
879
|
+
const { data, night, mainSession } = join;
|
|
880
|
+
const sessionFor = (id) => {
|
|
881
|
+
const index = this.sessionIndex.get(id);
|
|
882
|
+
return index === undefined ? undefined : this.sessionInfo[index];
|
|
883
|
+
};
|
|
884
|
+
const prompts = groupBy(data.humanPrompts, p => p.sessionId);
|
|
885
|
+
const tools = groupBy(data.toolCalls.filter(t => data.capability(t.sessionId, 'toolNames') !== 'absent'), t => data.rootId(t.sessionId));
|
|
886
|
+
let errorsWithReply = 0, apologies = 0;
|
|
887
|
+
for (const t of data.toolCalls) {
|
|
888
|
+
if (t.isError !== true || data.capability(t.sessionId, 'toolErrors') === 'absent')
|
|
889
|
+
continue;
|
|
890
|
+
const session = sessionFor(t.sessionId);
|
|
891
|
+
if (!session)
|
|
892
|
+
continue;
|
|
893
|
+
const i = lowerBound(session.turnTimes, t.tsMs + 1, ts => ts);
|
|
894
|
+
const reply = session.turnFlags.slice(i, i + 2).find(flags => !(flags & USER_TURN));
|
|
895
|
+
if (reply === undefined)
|
|
896
|
+
continue;
|
|
897
|
+
errorsWithReply++;
|
|
898
|
+
if (reply & SORRY_TURN)
|
|
899
|
+
apologies++;
|
|
900
|
+
}
|
|
901
|
+
if (errorsWithReply)
|
|
902
|
+
apologiesAfterError = { errorsWithReply, apologies };
|
|
903
|
+
if (mainSession) {
|
|
904
|
+
const session = sessionFor(mainSession);
|
|
905
|
+
const last = prompts.get(mainSession)?.at(-1);
|
|
906
|
+
if (last && last.tsMs === session?.lastPromptTs)
|
|
907
|
+
mainEventLastPromptThanks = session.lastPromptThanks;
|
|
908
|
+
}
|
|
909
|
+
if (night && night.start <= night.end) {
|
|
910
|
+
for (const { turnTimes, turnFlags } of this.sessionInfo) {
|
|
911
|
+
const first = lowerBound(turnTimes, night.start, ts => ts);
|
|
912
|
+
for (let i = first; i < turnTimes.length && turnTimes[i] <= night.end; i++) {
|
|
913
|
+
if (turnFlags[i] & USER_TURN) {
|
|
914
|
+
whyDuringLongestNight = (whyDuringLongestNight ?? 0) + Number(Boolean(turnFlags[i] & WHY_TURN));
|
|
915
|
+
}
|
|
916
|
+
}
|
|
917
|
+
}
|
|
918
|
+
}
|
|
919
|
+
for (const [id, rows] of prompts) {
|
|
920
|
+
const calls = tools.get(id);
|
|
921
|
+
const session = sessionFor(id);
|
|
922
|
+
if (!calls || !session)
|
|
923
|
+
continue;
|
|
924
|
+
const { turnTimes, turnFlags } = session;
|
|
925
|
+
for (const [i, prompt] of rows.entries()) {
|
|
926
|
+
const match = lowerBound(turnTimes, prompt.tsMs, ts => ts);
|
|
927
|
+
const flags = turnFlags[match] ?? 0;
|
|
928
|
+
if (turnTimes[match] !== prompt.tsMs || !(flags & USER_TURN) || !(flags & ONE_WORD_TURN) || turnTimes[match + 1] === prompt.tsMs ||
|
|
929
|
+
rows[i + 1]?.tsMs === prompt.tsMs || rows[i - 1]?.tsMs === prompt.tsMs)
|
|
930
|
+
continue;
|
|
931
|
+
const until = rows[i + 1]?.tsMs ?? Infinity;
|
|
932
|
+
const from = lowerBound(calls, prompt.tsMs, t => t.tsMs);
|
|
933
|
+
const to = lowerBound(calls, until, t => t.tsMs);
|
|
934
|
+
oneWordLeashMaxToolCalls = Math.max(oneWordLeashMaxToolCalls ?? 0, to - from);
|
|
935
|
+
}
|
|
936
|
+
}
|
|
937
|
+
}
|
|
938
|
+
return { whyDuringLongestNight, mainEventLastPromptThanks, oneWordLeashMaxToolCalls, apologiesAfterError };
|
|
939
|
+
}
|
|
940
|
+
}
|
|
941
|
+
const encoder = new TextEncoder();
|
|
942
|
+
function round(n) { return Math.round(n * 1000) / 1000; }
|
|
943
|
+
export function buildContentChapter(analyzer, join) {
|
|
944
|
+
return analyzer.finish(join);
|
|
945
|
+
}
|