Files
OmniRoute/open-sse/services/compression/resultMemo.ts
Diego Rodrigues de Sa e Souza fd7e4c10e5 feat(compression): omniglyph engine (context-as-image, Fable 5 direct) — stack + single mode (#6556)
* feat(compression): dependência omniglyph (file:) + smoke de import

* feat(compression): engine omniglyph — contexto-como-imagem com gates fail-closed

* fix(compression): omniglyph adapter fail-open no transform (try/catch)

* feat(compression): registra omniglyph no registry e catálogo (single mode, stackPriority 90)

* feat(compression): modo único omniglyph (async), selecionar o modo é o enable

* feat(compression): plumbing supportsVision + providerTransport até os engines

* feat(compression): estimador de tokens image-aware — modo stacked mantém a saída do omniglyph

* docs(compression): corrige comentário do prefixo base64 no decode PNG (64 chars)

* feat(compression): registra omniglyph nas listas de modo/engine (db, combo, deriveDefaultPlan, mcp)

* feat(dashboard): dedicated OmniGlyph engine screen (context-as-image)

Adds a per-engine detail page at /dashboard/context/omniglyph, alongside the
other compression engines in the sidebar. Four sections: the economics (measured
savings), a REAL before→after (dense text vs the rendered PNG page, not a mockup),
the fail-closed gate flow, and the enable control wired to /api/settings/compression
(preview engine, off by default). Sidebar entry + i18n label across all locales.

* chore(compression): consume published omniglyph@^1.0.0 from the npm registry

Replaces the local file: dependency used during the preview phase — npm ci
now resolves omniglyph from the registry with integrity, unblocking CI.

* fix(compression): satisfy v3.8.47 quality gates for the omniglyph engine

- dependency-allowlist: approve omniglyph (own package, published from
  diegosouzapw/OmniGlyph; supply-chain review done by the maintainer)
- ladder maps (#6533 guard): rank omniglyph 80 (stackPriority 90, runs after
  every text engine) with expectedReductionFactor 0.35 (measured 0.23-0.33)
- drop the two explicit any casts in omniglyph tests (no-explicit-any is
  error-level in tests since #6218)

* chore(compression): rebaseline strategySelector for the omniglyph mode dispatch

+18 lines of cohesive dispatch/type wiring at the existing mode chokepoints
(sync no-op + async single-mode branch + providerTransport on the options
types) — not extractable without hiding the dispatch boundary, mirroring the
prior compression rebaselines. Also drops an unused eslint-disable directive
in image-aware-tokens.test.ts (warning-level red under --max-warnings 0).

* chore(quality): register inherited base tests in stryker tap.testFiles

masked-200-exhaustion-fallback-6427 and headroom-codex-quota-snapshot-6379
arrived via the base merge without their stryker registration —
check:mutation-test-coverage --strict requires covering tests to be listed.

* refactor(compression): keep omniglyph wiring under the complexity gate

- extract the async single-mode resolution to engines/omniglyphSingleMode.ts
  (runCompressionAsync was at complexity 17 after the mode branch; back <=15)
- split OmniglyphContextPageClient into section components (was 161 lines in
  one function; every function now under the 80-line cap)
- complexity baseline 2052->2053: the +1 is inherited base drift (the ratchet
  does not run on fast-path merges — same pattern as the v3.8.44/46
  rebaselines); this PR's own code is measured complexity-net-zero

* chore(quality): register 3 more inherited base tests in stryker tap.testFiles

route-guard-middleware-local-only, combo-diagnostics-trace and
idempotency-fusion-collision arrived via the latest base merge without their
stryker registration (fast-path merges skip check:mutation-test-coverage).

* chore(quality): cognitive-complexity baseline 883->884 (inherited base drift)

check:cognitive-complexity measures 884 identically on the pristine
origin/release/v3.8.47 tip and on this HEAD — the PR itself is
cognitive-net-zero (single-mode resolution extracted to its own module,
page client split into section components). Same inherited-drift pattern
as the v3.8.4x release rebaselines.

---------

Co-authored-by: diegosouzapw <diegosouzapw@devbox.local>
2026-07-08 07:56:44 -03:00

88 lines
3.5 KiB
TypeScript

import crypto from "node:crypto";
import type { CompressionConfig, CompressionMode, CompressionResult } from "./types.ts";
export const MEMO_CAP = 5_000;
const memoMap = new Map<string, CompressionResult>();
// Opt-IN whitelist (NOT opt-out): cache only engines proven pure + STATELESS across
// requests. Excluded on purpose: `ccr` and `session-dedup` write to the cross-request
// CCR store (`ccr/index.ts` ccrStore; session-dedup imports storeBlock), so their output
// depends on prior state → not safe to memoize; `ultra`/`aggressive`/`llmlingua` are
// model-backed/non-deterministic. Any NEW engine is excluded until explicitly vetted.
// "omniglyph" is intentionally excluded too (P2 registry-consistency pass): it renders
// context as an image via a model-backed pipeline, so it is not yet proven deterministic
// across requests — conservative default (never-wrong) until explicitly vetted.
const DETERMINISTIC_ENGINES = new Set(["lite", "caveman", "rtk"]);
/** Top-level modes safe to cache (whitelist — any unknown/new mode defaults to false).
* "omniglyph" intentionally omitted — see comment on DETERMINISTIC_ENGINES above. */
const DETERMINISTIC_MODES = new Set<CompressionMode>(["lite", "standard", "rtk"]);
export function isDeterministicMode(mode: CompressionMode, config?: CompressionConfig): boolean {
if (mode === "stacked") {
const pipeline = config?.stackedPipeline;
if (!pipeline || pipeline.length === 0) return false;
return pipeline.every((step) => DETERMINISTIC_ENGINES.has(step.engine));
}
return DETERMINISTIC_MODES.has(mode);
}
function sha256hex(text: string): string {
return crypto.createHash("sha256").update(text).digest("hex");
}
export function makeMemoKey(
body: Record<string, unknown>,
mode: CompressionMode,
config: CompressionConfig,
principalId?: string,
model?: string,
supportsVision?: boolean | null
): string {
const bodyHash = sha256hex(JSON.stringify(body));
// model + supportsVision MUST be part of the key: the `lite` engine strips data:image
// URLs only when vision is unsupported (replaceImageUrls / modelSupportsVision), so the
// same (body, config) yields a DIFFERENT result per target — omitting them returns a
// wrong (image-stripped or image-kept) cached body across vision/non-vision targets.
return sha256hex(
JSON.stringify({
bodyHash,
mode,
config,
principalId: principalId ?? null,
model: model ?? null,
supportsVision: supportsVision ?? null,
})
);
}
function boundedSet(key: string, value: CompressionResult): void {
if (!memoMap.has(key) && memoMap.size >= MEMO_CAP) {
const firstKey = memoMap.keys().next().value;
if (firstKey !== undefined) {
memoMap.delete(firstKey);
}
}
memoMap.set(key, value);
}
export function memoLookup(key: string): CompressionResult | null {
const hit = memoMap.get(key);
if (!hit) return null;
// Return a clone so downstream mutation cannot corrupt the cached value.
return JSON.parse(JSON.stringify(hit)) as CompressionResult;
}
export function memoStore(key: string, result: CompressionResult): void {
// Clone on STORE too (memoLookup already clones on read). Storing the caller's live
// object would let a later mutation of it (e.g. an async engine holding a sub-ref)
// corrupt the cached entry. Both ends isolated ⇒ the cache is immutable once stored.
boundedSet(key, JSON.parse(JSON.stringify(result)) as CompressionResult);
}
/** For tests only — clears the in-process memo store. */
export function clearMemoStore(): void {
memoMap.clear();
}