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
- Normalize text → split lines.
preprocessLines routes to JSON / code / log tidy (structure only).
- Tokenize → build per-token features →
forwardModel (tiny MLP).
- Aggregate to lines/blocks →
scoreCompilerBlocks (+ optional neural boost).
selectCompilerLines keeps a budgeted subset; verifiers check entity recall.
- Return compressed text + stats via
compressAdaptive / compressContext.
Domain preprocessors
routeContentType(lines)
Preprocessor · returns "json" | "code" | "log" | "text"
LaymanSkims the first chunk of lines and guesses whether you mostly pasted JSON, code, logs, or plain text.
TechnicalSamples 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
LaymanFinds JSON blobs in the text and shrinks them: empty junk out, huge blobs truncated, big same-shaped arrays sampled.
TechnicalBrace-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
LaymanRecursively cleans one JSON value so it takes less space without inventing new meaning.
TechnicalDrops 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
LaymanTidies code whitespace and tags the language. It does not delete comments or “boring” lines by keyword — that is the ML engine’s job.
TechnicalCalls 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
LaymanLooks at the top of the file and names the programming language (Python, Rust, SQL, …) or unknown.
TechnicalOrdered 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
LaymanCollapses giant stack traces and repeated identical log lines. It no longer throws away DEBUG lines just because the question didn’t say “debug”.
TechnicalAccumulates 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
LaymanPicks the right tidy-up for the paste (JSON, code, log, or none).
TechnicalDispatches 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)
LaymanBreaks each line into word-like pieces the model can score.
TechnicalRegex /[A-Za-z_][A-Za-z0-9_]*|[^\s]/g per line; returns flat token list (and parallel line indices elsewhere in the pipeline).
looksLikeCodePrefix(q)
LaymanGuesses if the question is about code (so we can focus the query).
TechnicalKeyword/syntax cues for coding tasks.
focusCodeQuery(q)
LaymanShortens a code-ish question to the useful part.
TechnicalStrips boilerplate instruction wrappers when looksLikeCodePrefix is true.
normalizeQuestion(question)
LaymanCleans the question text so matching is consistent.
TechnicalWhitespace/Unicode normalize; optional code-query focusing.
questionForContent(question, lines)
LaymanChooses the best question form for this particular paste.
TechnicalMay adapt normalization based on content shape (code vs prose).
normalizeContextText(text)
LaymanStandardizes newlines and odd characters before compression.
TechnicalLine-ending unify, soft wrapping of runaway lines, light cleanup without semantic rewrite.
foldKey(s)
LaymanMakes two spellings of the same thing compare equal.
TechnicalLowercases / folds punctuation for soft matching keys.
softIncludes(text, entity)
LaymanChecks if an entity appears in text even if spacing/case differ a bit.
TechnicalExact + folded containment; used for entity/term hit counting.
distinctiveEntitiesInCorpus(entities, corpusText)
LaymanKeeps entities that actually appear and aren’t everywhere (so they’re useful signals).
TechnicalFilters to corpus-present, down-weights ultra-common tokens via document frequency style checks.
specificQuestionEntities(question, blocks)
LaymanFinds question entities that are rare across blocks — the good “needles.”
TechnicalEntity list filtered by block DF for multi-hop protection.
normalizeEvidenceLine(line)
LaymanNormalizes a line before comparing “did we keep the important evidence?”
TechnicalWhitespace/fingerprint style normalize for retention metrics.
measureCriticalRetention(original, compressed, question)
LaymanScores whether the compressed text still has the lines that look critical for answering.
TechnicalRanks original lines by entity overlap; reports kept vs dropped critical previews. Measurement only — not an eviction policy.
questionTerms(question)
LaymanSplits the question into searchable words.
TechnicalTokenizes / filters stop-ish short terms for overlap features.
ML features & forward pass
classifyTokenSemantic(tok, lineContext)
LaymanTags a token as code-ish, comment-ish, chat-ish, or boilerplate-ish.
TechnicalMaps into SEM enum used as a categorical feature.
deterministicAttention(…)
LaymanA hand-crafted “attention” score when no neural boost is present — still a feature, not a keyword blacklist.
TechnicalCombines semantic class, entity match, and recency into a bounded prior for the MLP / fallback.
buildInferenceRecords(lines, question)
LaymanBuilds one feature row per token for the model.
TechnicalTokenizes, attaches line context, entity flags, entropy/fingerprint/ngram features, position encoding.
buildFeatureTensor(records, seqLen)
LaymanPacks those rows into a dense matrix the network expects.
TechnicalPads/truncates to seqLen; returns Float32-style flat or 2D feature array.
gelu(x)
LaymanSmooth activation used inside the tiny network.
TechnicalGaussian Error Linear Unit approximation.
layerNormRow(x, weight, bias, dim)
LaymanRescales a feature vector so training stays stable.
TechnicalPer-row mean/var normalize + affine.
linearRow(x, weight, bias, inDim, outDim)
LaymanOne dense layer: multiply, add bias.
TechnicalRow-vector × weight matrix + bias.
forwardModel(model, feats, n)
LaymanRuns the keep/drop neural net on every token and returns scores.
TechnicalStacked linear + GELU + LayerNorm from model.json weights; outputs per-token keep probabilities/logits.
linesFromKeptTokens(…)
LaymanTurns “which tokens survived” back into whole lines, always keeping a bit of the start and end.
TechnicalUnion of token→line indices plus sink/recency line sets.
markOracleImportant(tokens, lines, question)
LaymanLabels tokens that look like they must survive for the question (for training/eval style checks).
TechnicalEntity/term overlap oracle flags on tokens.
lineQuestionRelevance(line, question, modelLineScore)
No hardcoded drop phrases
LaymanHow relevant is this line to the question? Starts from the model score and bumps when question words appear.
TechnicalmodelLineScore * 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)
LaymanA fuzzy ID for a line so duplicates can be spotted.
TechnicalLowercase, digits→#, whitespace collapse.
duplicateLinePenalty(lines)
LaymanSlightly downranks lines that appear over and over.
TechnicalFingerprint histogram → per-line penalty vector (structural, not lexical blacklist).
textFromKeptLines(lines, keptLineSet)
LaymanJoins the kept line numbers back into a string.
TechnicalSorted indices → join("\n").
countTokensInLines(lineForToken, keptLineSet)
LaymanCounts how many tokens sit on kept lines.
TechnicalIterates token→line map; increments when line is kept.
entityRecallOk(original, compressed, question)
LaymanDid we keep the rare names from the question?
TechnicalDistinctive entity hit ratio gate (strict for ≤3 entities, ≥0.9 otherwise).
lineScoresFromModel(records, scores, lineForToken, numLines)
LaymanTurns token scores into one score per line (best token on that line).
TechnicalMax-pool over tokens belonging to each line index.
sinkLineIndices(numLines)
LaymanAlways protect the very start and a bit of the end of the document.
TechnicalSet containing index 0 and the last few lines (attention-sink style).
questionRecallOk(original, compressed, question, minRatio)
LaymanBroader check: entities plus question words still show up enough.
TechnicalRequires entityRecallOk then term-hit ratio ≥ minRatio (default 0.66).
lineTokenCounts(lineForToken, numLines)
LaymanHow many tokens does each line cost?
TechnicalHistogram of token→line assignments.
Compiler / block selection
classifyLine(line)
LaymanLabels a line: heading, code, log, blank, etc.
TechnicalRegex typology used by routing and block segmentation.
shouldStartBlock(prevType, type, prevLine, line)
LaymanDecides when a new “paragraph/block” should begin.
TechnicalType transitions + structural cues (headings, fences).
segmentContext(lines, tokenCounts)
LaymanCuts the document into scored chunks.
TechnicalEmits blocks with start/end, type, text, token mass.
blockFingerprint(block)
LaymanFuzzy ID for a whole block to detect copies.
TechnicalNormalized text fingerprint for DF / duplicate penalties.
scoreCompilerBlocks(blocks, …, neuralBoost)
ML-primary when neuralBoost present
LaymanRanks each chunk by how useful it looks for the question. When the hosted neural scores exist, they mostly decide.
TechnicalIDF-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)
LaymanExpands kept blocks into the set of line numbers.
TechnicalUnion of inclusive [start, end] ranges.
addBlockWithDependencies(kept, blocks, block)
LaymanWhen keeping a chunk, also keep its nearby heading so context stays readable.
TechnicalAdds block id; walks back a few blocks for a heading dependency.
fenceMarkerCount(text)
LaymanCounts markdown code fences so we don’t leave one hanging open.
TechnicalCounts ``` markers (parity check).
closeStructuralBlocks(kept, blocks)
LaymanFixes odd open fences after selection.
TechnicalMay add closing fence blocks when parity is odd.
verifierStats(original, compressed, question, …)
LaymanPackage of quality numbers for dashboards/benchmarks.
TechnicalEntity/keyword recall, important-line retention, token ratios.
selectCompilerLines(…)
Largest internal routine — budgeted keep set
LaymanThe compiler: given scores and a token budget, picks which lines survive, protecting answer-critical bridges and sinks.
TechnicalSegments → 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)
LaymanPrepares block text for the hosted neural reranker.
TechnicalNormalize/preprocess/segment; returns block payloads for cross-encoder scoring.
compressAdaptive(text, question, model, options)
LaymanMain “smart compress” entry: runs the full pipeline and returns compressed text + metrics.
TechnicalPreprocess → features → forward → compiler selection → optional neural blend → stats object.
compressContext(text, question, budgetRatio, policyName, model)
LaymanSimpler wrapper: compress toward a fraction of the original size under a named policy.
TechnicalDelegates to adaptive path with budgetRatio (default 0.35).
comparePolicies(text, question, budgetRatio, model)
LaymanRuns a few strategies side-by-side for demos/benchmarks.
TechnicalReturns per-policy compressed outputs and quality metrics.
answerQualityScore(original, compressed, question)
LaymanRough 0–1 score of how answerable the compressed text still is.
TechnicalCombines entity/term recall and critical retention signals.
sustainabilityFromTokensSaved(tokensSaved, assumptions)
LaymanTurns “tokens not sent” into a CO₂ / energy estimate for the site.
TechnicalLinear model over energy-per-token assumptions.
middleTruncationFailureCase()
LaymanDemo fixture showing why dumb middle truncation fails.
TechnicalReturns a canned {context, question, answer} style object.
async loadModel(url)
LaymanDownloads the tiny browser weights file.
Technicalfetch → JSON parse of assets/data/model.json by default.
Precision, CCR, cache wrap
forwardVerifier(verifierModel, features)
LaymanSecond tiny net that checks if a compression looks safe.
TechnicalMLP over hand-built verifier features → accept/reject style score.
buildVerifierFeatures(…)
LaymanBuilds the checklist numbers the verifier reads.
TechnicalCompression ratio, entity recall, kept-token stats, etc.
async loadPrecisionModel(url)
LaymanLoads the higher-precision weight file.
TechnicalFetch model_precision.json.
async loadVerifier(url)
LaymanLoads verifier weights.
TechnicalFetch verifier.json.
ccrStore(original)
LaymanRemembers the full original under a short hash so you can fetch it later.
TechnicalIn-memory map keyed by simpleHash; reversible compression companion.
ccrRetrieve(hash)
LaymanLooks up the original by hash.
TechnicalMap get; returns null if missing.
ccrGetStats()
LaymanHow many originals are cached right now.
TechnicalSize / byte estimates of the CCR store.
simpleHash(str)
LaymanQuick fingerprint string for CCR keys (not crypto security).
TechnicalNon-cryptographic rolling hash → hex-ish string.
compressCCR(text, question, model, options)
LaymanCompress and stash the original so decompression/retrieval is possible.
TechnicalStore original → compressAdaptive → return compressed + retrieval hash.
compressPrecision(text, question, precisionModel, verifierModel)
LaymanMore cautious compress: try a cut, ask the verifier if it’s safe, back off if not.
TechnicalPrecision weights + verifier loop until accept or budget floor.
cacheWrap(compressedText, query)
LaymanOptional 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.
TechnicalCacheAligner: deterministic XML preamble/postamble for provider prompt caching (OpenAI/Anthropic/vLLM). Not in-model KV eviction.
Feature helpers
computeTokenEntropy(tok, allTokens)
LaymanRare tokens score higher than tokens that spam the file.
Technical1 - freq*3 clamped to [0,1].
computeSemanticFingerprint(lineText, questionText)
LaymanHow similar do the line and question “feel” at character-pair level?
TechnicalCharacter bigram Jaccard.
computeCrossContextSimilarity(tok, entities)
LaymanDoes this token look like any question entity?
TechnicalMax character-set overlap vs entity set.
computeContextDivergence(tok, allTokens)
LaymanAnother rarity signal for tokens.
TechnicalSame family as entropy; frequency-based divergence.
sinusoidalPositionEncoding(position, seqLen)
LaymanTells the model where in the document a token sits.
TechnicalSinusoids of position ratio (Transformer-style scalar feature).
computeNgramSim(lineText, questionText)
LaymanOverlapping 3-character chunks between line and question.
TechnicalTrigram Jaccard.
estimateIndentDepth(line)
LaymanHow nested is this line (spaces/tabs)?
TechnicalLeading 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.