Compress engine reference

Every function in web/assets/js/compress-engine.js — what it does in plain English, and how it works technically. Source of truth for the browser playground and the proxy package copy.

Eviction policy. Domain preprocessors may tidy structure (blank-line collapse, JSON shape crushing, log dedupe, stack-frame collapse). They must not drop content because a hardcoded phrase matched. Keep/drop decisions belong to the ML path: token MLP scores, compiler block ranking, and optional neural (neuralBoost) reranking.

End-to-end flow

  1. Normalize text → split lines.
  2. preprocessLines routes to JSON / code / log tidy (structure only).
  3. Tokenize → build per-token features → forwardModel (tiny MLP).
  4. Aggregate to lines/blocks → scoreCompilerBlocks (+ optional neural boost).
  5. selectCompilerLines keeps a budgeted subset; verifiers check entity recall.
  6. Return compressed text + stats via compressAdaptive / compressContext.

Domain preprocessors

routeContentType(lines)

Preprocessor · returns "json" | "code" | "log" | "text"
Layman

Skims the first chunk of lines and guesses whether you mostly pasted JSON, code, logs, or plain text.

Technical

Samples up to 50 lines, tallies classifyLine types. Prefers code when import/definition/fence/comment dominate; log/trace when those counts are high; JSON when config/table dominate or the sample looks like a keyed object/array. Avoids treating C#/Java null literals as JSON.

crushJSONLines(lines)

Preprocessor · structural JSON reduction
Layman

Finds JSON blobs in the text and shrinks them: empty junk out, huge blobs truncated, big same-shaped arrays sampled.

Technical

Brace-walks for top-level {…}/[…], JSON.parses, then crushValue. Replaces each successful span with compacted JSON. Non-JSON text outside spans is preserved.

crushValue(val, depth)

Preprocessor helper
Layman

Recursively cleans one JSON value so it takes less space without inventing new meaning.

Technical

Drops null/empty arrays; truncates long non-whitespace strings; samples homogeneous arrays; strips some high-cardinality id-like keys when values are long; depth-caps nesting.

compressCodeLines(lines)

Preprocessor · no keyword eviction
Layman

Tidies code whitespace and tags the language. It does not delete comments or “boring” lines by keyword — that is the ML engine’s job.

Technical

Calls detectLanguage, collapses runs of blank lines to at most one, returns { lines, preprocessor: "code", language }. Comment/docstring/license stripping and fixture phrase blacklists were removed.

detectLanguage(lines)

Preprocessor · language id string
Layman

Looks at the top of the file and names the programming language (Python, Rust, SQL, …) or unknown.

Technical

Ordered regex heuristics on the first ~80 lines, then markdown fence aliases (```ts, ```py, …). Specific patterns run before greedy ones so e.g. Python import os is not mislabeled as JavaScript.

compressLogLines(lines, question)

Preprocessor · no level-keyword eviction
Layman

Collapses giant stack traces and repeated identical log lines. It no longer throws away DEBUG lines just because the question didn’t say “debug”.

Technical

Accumulates stack frames → keep first/last + count; fingerprints timestamp/number-normalized messages and caps duplicates; collapses blank runs. Question arg is unused (kept for API stability). Level-based drops removed.

preprocessLines(lines, question)

Orchestrator
Layman

Picks the right tidy-up for the paste (JSON, code, log, or none).

Technical

Dispatches on routeContentType to crushJSONLines / compressCodeLines / compressLogLines, else pass-through.

Language detection coverage

Detection is for metadata and routing hints — the compressor still works on any text. Recognized ids include:

  • c / cpp (via fence)
  • csharp
  • kotlin
  • swift
  • elixir
  • rust
  • go
  • java
  • python
  • typescript
  • javascript
  • ruby
  • php
  • sql
  • shell
  • powershell
  • scala
  • r
  • lua
  • dart
  • matlab
  • yaml / toml (fence)
  • html
  • css
  • vue
  • unknown

Query & entity helpers

tokenizeContextLines(lines)

Layman

Breaks each line into word-like pieces the model can score.

Technical

Regex /[A-Za-z_][A-Za-z0-9_]*|[^\s]/g per line; returns flat token list (and parallel line indices elsewhere in the pipeline).

extractQuestionEntities(question)

Layman

Pulls out the “proper nouns” of the question: names, paths, IDs, code-ish tokens.

Technical

Heuristic extractors for CamelCase, paths, dotted ids, quoted spans, ALL_CAPS, numerics — used as soft overlap features, not hard drop rules.

looksLikeCodePrefix(q)

Layman

Guesses if the question is about code (so we can focus the query).

Technical

Keyword/syntax cues for coding tasks.

focusCodeQuery(q)

Layman

Shortens a code-ish question to the useful part.

Technical

Strips boilerplate instruction wrappers when looksLikeCodePrefix is true.

normalizeQuestion(question)

Layman

Cleans the question text so matching is consistent.

Technical

Whitespace/Unicode normalize; optional code-query focusing.

questionForContent(question, lines)

Layman

Chooses the best question form for this particular paste.

Technical

May adapt normalization based on content shape (code vs prose).

normalizeContextText(text)

Layman

Standardizes newlines and odd characters before compression.

Technical

Line-ending unify, soft wrapping of runaway lines, light cleanup without semantic rewrite.

foldKey(s)

Layman

Makes two spellings of the same thing compare equal.

Technical

Lowercases / folds punctuation for soft matching keys.

softIncludes(text, entity)

Layman

Checks if an entity appears in text even if spacing/case differ a bit.

Technical

Exact + folded containment; used for entity/term hit counting.

distinctiveEntitiesInCorpus(entities, corpusText)

Layman

Keeps entities that actually appear and aren’t everywhere (so they’re useful signals).

Technical

Filters to corpus-present, down-weights ultra-common tokens via document frequency style checks.

specificQuestionEntities(question, blocks)

Layman

Finds question entities that are rare across blocks — the good “needles.”

Technical

Entity list filtered by block DF for multi-hop protection.

normalizeEvidenceLine(line)

Layman

Normalizes a line before comparing “did we keep the important evidence?”

Technical

Whitespace/fingerprint style normalize for retention metrics.

measureCriticalRetention(original, compressed, question)

Layman

Scores whether the compressed text still has the lines that look critical for answering.

Technical

Ranks original lines by entity overlap; reports kept vs dropped critical previews. Measurement only — not an eviction policy.

questionTerms(question)

Layman

Splits the question into searchable words.

Technical

Tokenizes / filters stop-ish short terms for overlap features.

ML features & forward pass

classifyTokenSemantic(tok, lineContext)

Layman

Tags a token as code-ish, comment-ish, chat-ish, or boilerplate-ish.

Technical

Maps into SEM enum used as a categorical feature.

deterministicAttention(…)

Layman

A hand-crafted “attention” score when no neural boost is present — still a feature, not a keyword blacklist.

Technical

Combines semantic class, entity match, and recency into a bounded prior for the MLP / fallback.

buildInferenceRecords(lines, question)

Layman

Builds one feature row per token for the model.

Technical

Tokenizes, attaches line context, entity flags, entropy/fingerprint/ngram features, position encoding.

buildFeatureTensor(records, seqLen)

Layman

Packs those rows into a dense matrix the network expects.

Technical

Pads/truncates to seqLen; returns Float32-style flat or 2D feature array.

gelu(x)

Layman

Smooth activation used inside the tiny network.

Technical

Gaussian Error Linear Unit approximation.

layerNormRow(x, weight, bias, dim)

Layman

Rescales a feature vector so training stays stable.

Technical

Per-row mean/var normalize + affine.

linearRow(x, weight, bias, inDim, outDim)

Layman

One dense layer: multiply, add bias.

Technical

Row-vector × weight matrix + bias.

forwardModel(model, feats, n)

Layman

Runs the keep/drop neural net on every token and returns scores.

Technical

Stacked linear + GELU + LayerNorm from model.json weights; outputs per-token keep probabilities/logits.

linesFromKeptTokens(…)

Layman

Turns “which tokens survived” back into whole lines, always keeping a bit of the start and end.

Technical

Union of token→line indices plus sink/recency line sets.

markOracleImportant(tokens, lines, question)

Layman

Labels tokens that look like they must survive for the question (for training/eval style checks).

Technical

Entity/term overlap oracle flags on tokens.

lineQuestionRelevance(line, question, modelLineScore)

No hardcoded drop phrases
Layman

How relevant is this line to the question? Starts from the model score and bumps when question words appear.

Technical

modelLineScore * 2 + term/entity soft hits. Fixture penalties (e.g. Maycomb, Region CPU eviction, Appendix notes) removed — negatives are not applied from keyword lists.

lineFingerprint(line)

Layman

A fuzzy ID for a line so duplicates can be spotted.

Technical

Lowercase, digits→#, whitespace collapse.

duplicateLinePenalty(lines)

Layman

Slightly downranks lines that appear over and over.

Technical

Fingerprint histogram → per-line penalty vector (structural, not lexical blacklist).

textFromKeptLines(lines, keptLineSet)

Layman

Joins the kept line numbers back into a string.

Technical

Sorted indices → join("\n").

countTokensInLines(lineForToken, keptLineSet)

Layman

Counts how many tokens sit on kept lines.

Technical

Iterates token→line map; increments when line is kept.

entityRecallOk(original, compressed, question)

Layman

Did we keep the rare names from the question?

Technical

Distinctive entity hit ratio gate (strict for ≤3 entities, ≥0.9 otherwise).

lineScoresFromModel(records, scores, lineForToken, numLines)

Layman

Turns token scores into one score per line (best token on that line).

Technical

Max-pool over tokens belonging to each line index.

sinkLineIndices(numLines)

Layman

Always protect the very start and a bit of the end of the document.

Technical

Set containing index 0 and the last few lines (attention-sink style).

questionRecallOk(original, compressed, question, minRatio)

Layman

Broader check: entities plus question words still show up enough.

Technical

Requires entityRecallOk then term-hit ratio ≥ minRatio (default 0.66).

lineTokenCounts(lineForToken, numLines)

Layman

How many tokens does each line cost?

Technical

Histogram of token→line assignments.

Compiler / block selection

classifyLine(line)

Layman

Labels a line: heading, code, log, blank, etc.

Technical

Regex typology used by routing and block segmentation.

shouldStartBlock(prevType, type, prevLine, line)

Layman

Decides when a new “paragraph/block” should begin.

Technical

Type transitions + structural cues (headings, fences).

segmentContext(lines, tokenCounts)

Layman

Cuts the document into scored chunks.

Technical

Emits blocks with start/end, type, text, token mass.

blockFingerprint(block)

Layman

Fuzzy ID for a whole block to detect copies.

Technical

Normalized text fingerprint for DF / duplicate penalties.

scoreCompilerBlocks(blocks, …, neuralBoost)

ML-primary when neuralBoost present
Layman

Ranks each chunk by how useful it looks for the question. When the hosted neural scores exist, they mostly decide.

Technical

IDF-weighted entity/term soft hits + light type priors + duplicate soft penalty. No copyright/Passage/“see also” keyword dumps. With neuralBoost: score = 0.1 * heuristic + 0.9 * neural.

blockToLineSet(blocks)

Layman

Expands kept blocks into the set of line numbers.

Technical

Union of inclusive [start, end] ranges.

addBlockWithDependencies(kept, blocks, block)

Layman

When keeping a chunk, also keep its nearby heading so context stays readable.

Technical

Adds block id; walks back a few blocks for a heading dependency.

fenceMarkerCount(text)

Layman

Counts markdown code fences so we don’t leave one hanging open.

Technical

Counts ``` markers (parity check).

closeStructuralBlocks(kept, blocks)

Layman

Fixes odd open fences after selection.

Technical

May add closing fence blocks when parity is odd.

verifierStats(original, compressed, question, …)

Layman

Package of quality numbers for dashboards/benchmarks.

Technical

Entity/keyword recall, important-line retention, token ratios.

selectCompilerLines(…)

Largest internal routine — budgeted keep set
Layman

The compiler: given scores and a token budget, picks which lines survive, protecting answer-critical bridges and sinks.

Technical

Segments → scores → greedy/protected keep with neural seed protection, multi-hop bridge harvest, fence closing, and verifier loops. This is where eviction happens — driven by relative scores / neural ranks, not phrase blacklists.

Public API entry points

prepareNeuralBlocks(text, question, model)

Layman

Prepares block text for the hosted neural reranker.

Technical

Normalize/preprocess/segment; returns block payloads for cross-encoder scoring.

compressAdaptive(text, question, model, options)

Layman

Main “smart compress” entry: runs the full pipeline and returns compressed text + metrics.

Technical

Preprocess → features → forward → compiler selection → optional neural blend → stats object.

compressContext(text, question, budgetRatio, policyName, model)

Layman

Simpler wrapper: compress toward a fraction of the original size under a named policy.

Technical

Delegates to adaptive path with budgetRatio (default 0.35).

comparePolicies(text, question, budgetRatio, model)

Layman

Runs a few strategies side-by-side for demos/benchmarks.

Technical

Returns per-policy compressed outputs and quality metrics.

answerQualityScore(original, compressed, question)

Layman

Rough 0–1 score of how answerable the compressed text still is.

Technical

Combines entity/term recall and critical retention signals.

sustainabilityFromTokensSaved(tokensSaved, assumptions)

Layman

Turns “tokens not sent” into a CO₂ / energy estimate for the site.

Technical

Linear model over energy-per-token assumptions.

middleTruncationFailureCase()

Layman

Demo fixture showing why dumb middle truncation fails.

Technical

Returns a canned {context, question, answer} style object.

async loadModel(url)

Layman

Downloads the tiny browser weights file.

Technical

fetch → JSON parse of assets/data/model.json by default.

Precision, CCR, cache wrap

forwardVerifier(verifierModel, features)

Layman

Second tiny net that checks if a compression looks safe.

Technical

MLP over hand-built verifier features → accept/reject style score.

buildVerifierFeatures(…)

Layman

Builds the checklist numbers the verifier reads.

Technical

Compression ratio, entity recall, kept-token stats, etc.

async loadPrecisionModel(url)

Layman

Loads the higher-precision weight file.

Technical

Fetch model_precision.json.

async loadVerifier(url)

Layman

Loads verifier weights.

Technical

Fetch verifier.json.

ccrStore(original)

Layman

Remembers the full original under a short hash so you can fetch it later.

Technical

In-memory map keyed by simpleHash; reversible compression companion.

ccrRetrieve(hash)

Layman

Looks up the original by hash.

Technical

Map get; returns null if missing.

ccrGetStats()

Layman

How many originals are cached right now.

Technical

Size / byte estimates of the CCR store.

simpleHash(str)

Layman

Quick fingerprint string for CCR keys (not crypto security).

Technical

Non-cryptographic rolling hash → hex-ish string.

compressCCR(text, question, model, options)

Layman

Compress and stash the original so decompression/retrieval is possible.

Technical

Store original → compressAdaptive → return compressed + retrieval hash.

compressPrecision(text, question, precisionModel, verifierModel)

Layman

More cautious compress: try a cut, ask the verifier if it’s safe, back off if not.

Technical

Precision weights + verifier loop until accept or budget floor.

cacheWrap(compressedText, query)

Layman

Optional wrapper that puts a fixed header around compressed text so providers can reuse prompt/prefix cache. We never touch the model’s KV cache — we only change the string we send.

Technical

CacheAligner: deterministic XML preamble/postamble for provider prompt caching (OpenAI/Anthropic/vLLM). Not in-model KV eviction.

Feature helpers

computeTokenEntropy(tok, allTokens)

Layman

Rare tokens score higher than tokens that spam the file.

Technical

1 - freq*3 clamped to [0,1].

computeSemanticFingerprint(lineText, questionText)

Layman

How similar do the line and question “feel” at character-pair level?

Technical

Character bigram Jaccard.

computeCrossContextSimilarity(tok, entities)

Layman

Does this token look like any question entity?

Technical

Max character-set overlap vs entity set.

computeContextDivergence(tok, allTokens)

Layman

Another rarity signal for tokens.

Technical

Same family as entropy; frequency-based divergence.

sinusoidalPositionEncoding(position, seqLen)

Layman

Tells the model where in the document a token sits.

Technical

Sinusoids of position ratio (Transformer-style scalar feature).

computeNgramSim(lineText, questionText)

Layman

Overlapping 3-character chunks between line and question.

Technical

Trigram Jaccard.

estimateIndentDepth(line)

Layman

How nested is this line (spaces/tabs)?

Technical

Leading whitespace / 40, capped at 1.0.

Exported surface

Attached to global.SuperCompressEngine:

compressContext, compressAdaptive, prepareNeuralBlocks, comparePolicies,
answerQualityScore, sustainabilityFromTokensSaved, middleTruncationFailureCase,
loadModel, extractQuestionEntities, normalizeQuestion, normalizeContextText,
routeContentType, preprocessLines, crushJSONLines, compressCodeLines, compressLogLines,
compressPrecision, loadPrecisionModel, loadVerifier, forwardVerifier,
compressCCR, ccrRetrieve, ccrGetStats, simpleHash, cacheWrap

Many helpers above are internal closures (not exported) but documented because they define behavior.