SLOPSHOPPER

inline-headroom

Headroom-style levers inside Claude Code as a mod: clamp-only effort routing after successful tool results, a detector-only CacheAligner that logs cache-hit…

paneguardcommandtooltimer
★ 1v0.8.2MITupdated 2026-10-24kwitsch/claude-plugins/plugins/inline-headroom
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · inline-headroom
│ ┃ Headroom ✕ › fix the failing auth test and add an audit log call │ ┃ effort routing steps clamped │ ┃ session 0 0 ⏺ Read(src/auth.ts) │ ┃ subagents 0 0 ⎿ Read 6 lines │ ┃ today – – ⏺ Update(src/auth.ts) │ ┃ 7 days – – ⎿ Added 2 lines, removed 1 line │ ┃ 30 days – – ⏺ Bash(bun test) │ ┃ ⎿ 3 pass, 1 fail │ ┃ cache aligner hit drops │ ┃ session – 0 ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ today – – │ ┃ 7 days – – ✻ Worked for 42s · done 4:20 PM │ ┃ 30 days – – │ ┃ › /headroom │ ┃ smart crusher dropped saved │ ┃ session 0 0 │ ┃ │ ┃ dedup spans saved │ ┃ session 0 0 │ ┃ │ ┃ line elider lines saved │ ┃ session 0 0 │ ┃ │ ┃ compaction arrays saved │ ┃ session 0 0 │ ┃ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · Headroom
effort routing steps clamped session 0 0 subagents 0 0 today – – 7 days – – 30 days – – cache aligner hit drops session – 0 today – – 7 days – – 30 days – – smart crusher dropped saved session 0 0 dedup spans saved session 0 0 line elider lines saved session 0 0 compaction arrays saved session 0 0 config texts saved session 0 0 html extractor pages saved session 0 0 logs texts saved session 0 0 search texts saved session 0 0 diff texts saved session 0 0 text crusher texts saved session 0 0 relevance split texts saved session 0 0 storage unavailable:
README

inline-headroom

Headroom-style levers inside Claude Code as a mod: clamp-only effort routing after successful tool results, a detector-only CacheAligner that logs cache-hit drops, and a SmartCrusher with lossless compaction, cross-turn dedup, a dense line elider, a config compressor, an HTML extractor, log, search and diff compressors, a text crusher and a relevance split that shrink tool results before the model reads them (originals retrievable, custom workflow tags kept whole). Ports thirteen levers and the tag protector of headroom faithfully to upstream semantics.

Install

/plugin install inline-headroom@kwitsch-plugins

What it does

LeverUpstream mappingBehavior
Effort routingheadroom effort routing (structural success-vs-error rule)On a main-loop model step after index 0 whose preceding tool results were all successful, lowers thinking effort to low; with subagent_effort_routing_enabled on, each subagent and Workflow agent gets the same rule on its own steps, tracked per agent. Clamp-only: never raises effort, never injects one, leaves numeric or absent effort alone. Any tool error or deny since that loop's last step keeps full effort.
CacheAlignerheadroom CacheAligner (detector only)Logs a line whenever the prompt-cache hit ratio drops from at least 60% to below 60% between steps. Never rewrites or reorders the prompt.
SmartCrusherheadroom SmartCrusher (lossy array paths)Rewrites a successful tool result of any tool whose text (a string or text block) is one JSON document longer than 800 characters, before the model first reads it: in the main loop, and in subagent and Workflow-agent results while subagent_compression_enabled is on. Read results never qualify (their line numbers stop the text from parsing). An array of 5 or more objects keeps at most an adaptive K (3 to 15) rows plus every error row, outlier and anomaly (first and last rows, change points, top search results, log clusters, rows matching the conversation); unique entities with no such signal stay whole. Arrays of 9 or more strings, numbers or mixed values keep their errors, outliers and first and last items. A shortened array ends with a <<ccr:HASH N_rows_offloaded>> (or N_items_offloaded) marker that headroom_retrieve resolves. Error results are never rewritten.
Compactionheadroom SmartCrusher lossless compaction (csv-schema)Before the SmartCrusher drops a row, an array of 5 or more objects longer than its adaptive K is rendered as one typed schema line plus CSV rows ([N]{id:int,name:string,…} then 1,alice), heterogeneous arrays split into buckets by a shared string field; when that saves at least 15% of the array's JSON the table replaces the array (as a JSON string), and nothing is dropped, so nothing needs retrieving. Runs while smart_crusher_enabled is off too (then an array whose table loses keeps every row). Error results are never rewritten.
Cross-turn dedupheadroom cross_turn_dedup.pyReplaces each run of 3 or more lines (40+ characters) in a tool result that already appeared in an earlier tool result of the same conversation (the main loop, or one subagent), verbatim or with every line number shifted by one constant, with a one-line pointer: [↑nL same as result K: "anchor" hash=H], or [↑nL same as result K +dL: "anchor" hash=H] for a shifted re-read. K counts that conversation's tool results from 1, the earliest copy is never rewritten, and headroom_retrieve with the hash returns the run's exact text. A result that repeats an earlier one in full becomes a single pointer. Error results and Read results are never rewritten but count as originals, so a re-Read always shows the file verbatim for the next Edit.
Dense line eliderheadroom dense_line_elider.pyShortens each line of 300+ characters with under 6% spaces, no tab and no JSON in it (minified JS/CSS, base64, RSC payloads) to its first 160 and last 80 characters around ...[N chars of dense machine-generated content elided]..., once such lines add up to 2000+ characters in one result, and ends that result with [N dense machine-generated line(s) elided. Retrieve original: hash=H]; headroom_retrieve with the hash returns the whole original. It skips text the SmartCrusher rewrote, and error results.
Config compressorheadroom ConfigCompressor (Tier 1 and 2)Shortens a YAML, TOML or INI tool result of 300+ characters: whole-line comments and blank lines (INI: column-0 #/; comments only) are dropped behind [N comment/blank lines elided. Retrieve original: hash=H], then repeated lines and repeated multi-line blocks (Kubernetes container stanzas, CI jobs) fold behind exact ... (repeated N times) and ... (repeats K lines from D lines back) markers, kept only when they expand back to the same text; when no comment line was elided, the result ends with [Repeated config lines folded. Retrieve original: hash=H]. Comments that may be data (a YAML block scalar, a multi-line string) are kept. headroom_retrieve with the hash returns the original. Error results are never rewritten.
HTML extractorheadroom HTMLExtractor (bounded stand-in, no trafilatura)Turns an HTML tool result (a web page) of 300+ characters into markdown-like text: scripts, styles, the head, navigation, footers, form controls, embedded media and comments are dropped (the text inside a form or dialog is kept); headings become # lines, list items - lines, links text, table rows pipe-separated lines; <pre> keeps its whitespace and entities are decoded. The text ends with [HTML extracted to text: N characters of markup removed. Retrieve original: hash=H], and headroom_retrieve with the hash returns the page. The dense line elider then runs on the extracted text. A page that extracts to nothing, or to nothing shorter, is left to the elider as it is. Error results are never rewritten.
Log compressorheadroom LogCompressor (Rust log_compressor.rs)Shortens a build or test log of 50+ lines: keeps errors and failures (the first, the last and the most important, 10 of each), 5 deduplicated warnings, the first 3 stack traces (a long trace's runtime frames collapsed behind [... N frames collapsed]), summary lines such as pytest's totals and short test summary, and 3 lines of context around each, up to an adaptive 10 to 100 lines, then [N lines omitted: … ERROR, … WARN, …] and [N lines compressed to M: …. Retrieve original: hash=H]; headroom_retrieve with the hash returns the log. When dropping ANSI colour and collapsing repeated lines shrinks the log nearly as much (within 5%), that lossless fold is used instead. Error results, Read output and line-numbered text are never rewritten.
Search compressorheadroom SearchCompressor (Rust search_compressor.rs)Shortens grep and ripgrep output (matches and -C context lines, Unix and Windows paths): per file the first, the last and the most relevant matches (error words and words from the conversation's recent requests rank higher), at most 5 per file, 15 files and an adaptive 5 to 30 in all, with [... and N more matches in FILE], then [N matches compressed to M. Retrieve original: hash=H]. Lines that are not grep rows are dropped (they stay retrievable). When one heading per repeated file or directory shrinks the output nearly as much (within 5%), that lossless fold is used instead. Error results, Read output and line-numbered text are never rewritten.
Diff compressorheadroom DiffCompressor (Rust diff_compressor.rs)Shortens a git diff of 50+ lines: at most 20 files (the most-changed), at most 10 hunks per file (the first, the last and the most relevant), 2 context lines around each change; \ No newline markers, rename lines and commit headers are kept, mode lines normalised to 100644 and binary lines to Binary files differ, then [N files changed, +A -D lines, H hunks omitted] and [N lines compressed to M. Retrieve original: hash=H]. When dropping git's index lines alone shrinks it nearly as much (within 5%), only those are dropped. A compressed diff no longer applies with git apply; the original is retrievable. The dense line elider does not run on a compressed diff. Error results, Read output and line-numbered text are never rewritten.
Text crusherheadroom TextCrusher (standing in for its ML Kompress)Shortens prose of 6+ sentences (a WebFetch summary, markdown output; never an Agent or Task report, and never a line-per-entry listing such as Glob, find or git log --oneline) to about half its characters: sentences are scored by position (later ranks higher), relevance to the conversation's recent requests and fact density (numbers, ALLCAPS, dotted names, error words), near-duplicates are skipped, and the kept sentences, one per line, end with [Text crushed: K of N segments kept. Retrieve original: hash=H]. Line breaks and indentation are not kept. When collapsing repeated lines shrinks it nearly as much (within 5%), that lossless fold is used instead. Text holding CJK characters, error results, Read output and line-numbered text are left alone.
Relevance splitheadroom relevance split (BM25, CCR mode)Before the text crusher, splits prose (never an Agent or Task report or a listing) into records (paragraphs, groups of up to 8 lines) and scores each against the conversation's recent requests; records below an adaptive cut become ...[N low-relevance lines elided]..., and the result ends with [N low-relevance lines in R runs elided. Retrieve original: hash=H]. A group of records holding an error word (error, failed, timeout, …) is always kept, and when nothing would be kept the text is left to the text crusher. Runs only with a request to match against, only on prose (never on logs or grep output), and never on error results, Read output or line-numbered text.
Tag protectorheadroom tag protector (block mode, mask-free)Keeps custom workflow tags (any non-HTML5 tag such as <system-reminder>, <tool_call> or <thinking>, with everything between its open and close tag) whole in tool results: a JSON document holding one drops no row or item, a line holding one is never elided, a repeated run of lines touching one is never folded, and YAML, TOML, INI, HTML, build logs, grep output, diffs and prose holding one are left to the elider and dedup. A result too tag-dense to scan within its budget is left untouched. It saves nothing itself, so it has no /headroom table, and it only matters while a compression lever is on.

A content router (a light port of headroom's content detector) labels each tool-result text as JSON, diff, HTML, git status, search results, build/log output, YAML/TOML/INI config, source code or plain text, and runs only the levers that fit: the SmartCrusher and lossless compaction see only JSON, the config compressor only config, the HTML extractor only HTML, the log compressor only build/log output, the search compressor only search results, the diff compressor only diffs, and the relevance split and the text crusher only plain text, while the dense line elider and cross-turn dedup see every type. A lossy log, search, diff or text compressor is used only when it saves at least 5% more than its type's lossless fold; the dense line elider then runs on what the log, search and text compressors leave, but not after a diff, a fold or a relevance split. It has no option of its own; each lever keeps its toggle.

Configuration options

All seventeen options are on by default. For the lever toggles only a literal false disables one; storage_enabled is fail-closed, so anything but a literal true turns storage off. Set them via /plugin -> installed -> inline-headroom -> Configure options, or in settings.json:

{
  "pluginConfigs": {
    "inline-headroom": {
      "options": {
        "effort_routing_enabled": true,
        "subagent_effort_routing_enabled": true,
        "cache_aligner_enabled": true,
        "smart_crusher_enabled": true,
        "lossless_compaction_enabled": true,
        "cross_turn_dedup_enabled": true,
        "dense_line_elider_enabled": true,
        "config_compressor_enabled": true,
        "html_extractor_enabled": true,
        "log_compressor_enabled": true,
        "search_compressor_enabled": true,
        "diff_compressor_enabled": true,
        "text_crusher_enabled": true,
        "relevance_split_enabled": true,
        "tag_protector_enabled": true,
        "subagent_compression_enabled": true,
        "storage_enabled": true
      }
    }
  }
}
OptionDefaultEffect / Value
effort_routing_enabledtrueLower effort to low on main-loop steps that only resume after successful tool results.
subagent_effort_routing_enabledtrueApply the same clamp to each subagent and Workflow agent, per agent. Only active while effort_routing_enabled is on. Overrides effort set on purpose (agent frontmatter, Agent tool, Workflow); see Notes & limitations.
cache_aligner_enabledtrueLog prompt-cache hit-ratio drops per main-loop step.
smart_crusher_enabledtrueCompress large JSON arrays in successful tool results of any tool (Read results never qualify); dropped rows stay retrievable with headroom_retrieve while the mod is loaded (see Notes & limitations).
lossless_compaction_enabledtrueBefore the SmartCrusher drops rows, rewrite a large JSON array of objects as a schema line plus CSV rows when that saves at least 15%; nothing is dropped. Also runs while smart_crusher_enabled is off.
cross_turn_dedup_enabledtrueReplace a run of 3 or more lines (40+ characters) that repeats an earlier tool result of the same conversation with a one-line pointer; the run stays retrievable with headroom_retrieve while the mod is loaded.
dense_line_elider_enabledtrueShorten long, nearly space-free lines (minified bundles, base64, RSC payloads) in tool results to their head and tail; the original stays retrievable with headroom_retrieve while the mod is loaded.
config_compressor_enabledtrueShorten YAML, TOML and INI tool results: fold repeated lines and blocks losslessly and drop comments and blank lines behind a retrieval marker; the original stays retrievable with headroom_retrieve while the mod is loaded.
html_extractor_enabledtrueTurn HTML tool results into markdown-like text without scripts, styles, navigation and other boilerplate; the page stays retrievable with headroom_retrieve while the mod is loaded.
log_compressor_enabledtrueShorten build and test logs of 50+ lines to their errors, failures, warnings, stack traces, summaries and context, or fold their colour codes and repeated lines losslessly when that saves nearly as much; the original stays retrievable with headroom_retrieve while the mod is loaded.
search_compressor_enabledtrueShorten grep and ripgrep output to the first, last and most relevant matches per file, or fold repeated paths into headings losslessly when that saves nearly as much; the original stays retrievable with headroom_retrieve while the mod is loaded.
diff_compressor_enabledtrueShorten git diffs of 50+ lines to at most 20 files and 10 hunks per file with 2 context lines, or drop only their index lines when that saves nearly as much; the original stays retrievable with headroom_retrieve while the mod is loaded.

| text_crusher_enabled | true | Shorten prose of 6+ sentences (Agent reports, WebFetch summaries, markdown output) to about half its characters, or collapse its repeated lines losslessly when that saves nearly as much; the original stays retrievable with headroom_retrieve while the mod is loaded. Also owns the fold the relevance sp

Source 2 files
hooks/register.ts 573 lines
1import type { EngineInterface, Register, Timer } from "claude-code";
2import {
3  CELL_WIDTHS,
4  RETAIN_DAYS,
5  RETRIEVE_NAME,
6  RETRIEVE_TOOL,
7  ROWS,
8  cacheHitRatio,
9  crushQuery,
10  dayKey,
11  foldPending,
12  isCacheDrop,
13  isOwnStorageCall,
14  isToolError,
15  pct,
16  resetCorpus,
17  retrieveKey,
18  rewriteToolResults,
19  statsTables,
20  stepEffort,
21  storeOffloaded,
22  tableText,
23  toCount,
24  wantsQuery,
25  windowStart,
26  zeroCounters,
27} from "./policy.mjs";
28import type { Counters, DedupState } from "./policy.mjs";
29
30// Module state resets on hot reload and on an options change (the engine reloads the module).
31// Persisted totals survive: each load writes its own rows under a new WRITER.
32let toolErrored = false; // any main-loop tool error since the last main-loop step
33const agentErrored = new Set<string>(); // subagents with a tool error since their own last step; an entry ends with that agent's turn
34const subagents = { steps: 0, clamped: 0 }; // this session's subagent steps: its own row in memory; the persisted day rows count them with the main loop's
35const crush = { dropped: 0, saved: 0 }; // this session's SmartCrusher savings: in memory only, never persisted (the stats schema has no columns for them)
36const dedup = { spans: 0, saved: 0 }; // this session's cross-turn dedup savings: in memory only, never persisted
37const elide = { lines: 0, saved: 0 }; // this session's dense line elider savings: in memory only, never persisted
38const compact = { arrays: 0, saved: 0 }; // this session's lossless compaction savings: in memory only, never persisted
39const config = { texts: 0, saved: 0 }; // this session's config compressor savings: in memory only, never persisted
40const extract = { pages: 0, saved: 0 }; // this session's HTML extractor savings: in memory only, never persisted
41const log = { texts: 0, saved: 0 }; // this session's log compressor savings: in memory only, never persisted
42const search = { texts: 0, saved: 0 }; // this session's search compressor savings: in memory only, never persisted
43const diff = { texts: 0, saved: 0 }; // this session's diff compressor savings: in memory only, never persisted
44const textcrush = { texts: 0, saved: 0 }; // this session's text crusher savings: in memory only, never persisted
45const split = { texts: 0, saved: 0 }; // this session's relevance split savings: in memory only, never persisted
46const dedupStates = new Map<string, DedupState>(); // conversation ("" main, else agentId) → its dedup corpus; reset on session.end
47// Starts one conversation's dedup corpus over (its ordinals keep counting): what it indexes left the model's context.
48const dropCorpus = (key: string): void => {
49  const st = dedupStates.get(key);
50  if (st) resetCorpus(st);
51};
52let retrieveReady = false; // session.start registered headroom_retrieve under its expected name in this module load
53const offloaded = new Map<string, string>(); // CCR hash → original text (crushed array JSON, elided block): the only copy, oldest first (storeOffloaded evicts)
54// A second store, so dedup churn never evicts a sole copy above: a folded run's earlier copy is still in the transcript until a compaction.
55const folded = new Map<string, string>(); // CCR hash → a folded dedup run's text, oldest first
56// The session row: this session's counters, in memory.
57const session: Counters = zeroCounters();
58let lastHit: number | undefined; // the last main-loop step's cache-hit ratio
59const WRITER = Math.random().toString(36).slice(2).padEnd(8, "0"); // this module instance's stats rows
60const pending: Counters = zeroCounters(); // counter deltas since the last fold
61const days: Record<string, Counters> = {}; // this writer's per-day totals that may still need writing
62let flushing: Promise<void> = Promise.resolve(); // serializes stats_put: a newer snapshot always lands after an older one
63let sums: { data?: Counters[]; error?: string } | undefined; // the today / 7 days / 30 days totals (ROWS order after session), fetched outside render
64let loading: Promise<void> | undefined; // the fetch in flight: a tick never stacks on a slow stats_sum (a cold service start takes up to 3 s)
65let poll: Timer | undefined; // the open pane's 10 s refresh
66let stale = false; // the refresh ticked: the pane's next render fetches the storage rows
67let paneOpen = false; // the /headroom pane has rendered and not closed since: subagent steps redraw only then
68
69const PANE = "headroom"; // the /headroom pane's id (1-64 of letters, digits, _ and -)
70const message = (err: unknown): string => (err instanceof Error ? err.message : String(err));
71const RETRIEVE_SPEC = {
72  name: RETRIEVE_NAME,
73  description:
74    "Retrieve original uncompressed content that was compressed to save tokens. Use this when you need more data than what's shown in compressed tool results. The hash is in compression markers like <<ccr:abc123def456 40_rows_offloaded>> or hash=abc123def456.",
75  inputSchema: {
76    type: "object",
77    properties: {
78      hash: {
79        type: "string",
80        description: "Hash key from the compression marker (e.g. 'abc123def456' from <<ccr:abc123def456 40_rows_offloaded>> or hash=abc123def456)",
81      },
82    },
83    required: ["hash"],
84  },
85};
86// headroom_retrieve's answer: the original text, or a deny the model reads as a failed call.
87const retrieve = (hash: unknown) => {
88  const key = retrieveKey(hash);
89  const original = key === undefined ? undefined : (offloaded.get(key) ?? folded.get(key));
90  return original === undefined ? { deny: `headroom_retrieve: no stored content under hash ${String(hash)} (evicted, or the mod reloaded)` } : { result: original };
91};
92
93// Moves one counter in the session row and in the deltas still to persist.
94const count = (k: keyof Counters, n = 1): void => {
95  session[k] += n;
96  pending[k] += n;
97};
98
99// The engine refuses $.<noun> as a bare value, so same-file helpers take the whole $.
100// Resolves the op's result; rejects with the server's message on a refusal or an error result.
101const callStorage = async ($: EngineInterface, tool: string, args: Record<string, unknown>): Promise<unknown> => {
102  const c = await $.mcp.connect("storage"); // the key in this plugin's .mcp.json; the engine namespaces it and returns the namespaced `server` that `call` takes
103  if (!c.isConnected) throw new Error(c.message);
104  const r = await $.mcp.call(c.server, tool, args);
105  if (r.isError) throw new Error(r.content[0]?.text ?? "storage call failed");
106  // structuredContent is documented only for tools with an outputSchema; the text block carries the same JSON.
107  return r.structuredContent ?? JSON.parse(r.content[0]?.text ?? "null");
108};
109
110// Reads the storage rows into `sums` and redraws the pane. Never rejects.
111// Every storage call is awaited by a running hook: core checks $.mcp.call like a tool call, and this mod's tool.check
112// sees, and allows, only calls raised while one of its hooks runs. A call made after its hook returned (a clock
113// callback, an unawaited chain) skips the mod's own hooks, so a session in default mode asks and a headless one denies.
114const loadSums = async ($: EngineInterface): Promise<void> => {
115  let fetched: typeof sums;
116  try {
117    const today = dayKey(await $.clock.now()); // read per fetch, so the rows roll over at midnight
118    // The session row (days 0) is kept in memory; the rest are storage windows.
119    const totals = await Promise.all(ROWS.filter((r) => r.days > 0).map((r) => callStorage($, "stats_sum", { since: windowStart(today, r.days) })));
120    fetched = { data: totals as Counters[] }; // a refresh keeps the old numbers on screen until this lands
121  } catch (err) {
122    // The clock or storage failed: keep the last good numbers under the note, say why instead of "…" forever.
123    fetched = { data: sums?.data, error: message(err) };
124  }
125  const same = JSON.stringify(fetched) === JSON.stringify(sums);
126  sums = fetched;
127  if (same) return; // an idle session's totals repeat every tick: no redraw for them
128  try {
129    $.ui.invalidate("ui.render");
130  } catch {
131    // $ itself is refused: nothing is left to redraw with
132  }
133};
134
135// A call made while a fetch runs joins it instead of starting another: the engine re-arms every period at callback start, so a slow fetch would overlap the next tick.
136const refresh = ($: EngineInterface): Promise<void> => (loading ??= loadSums($).finally(() => (loading = undefined)));
137
138// Starts the open pane's 10 s refresh unless one runs: the command and the first redraw after a hot reload both call it.
139// A tick only marks the rows stale and redraws; the render hook fetches them (see loadSums).
140const arm = ($: EngineInterface): void => {
141  if (poll !== undefined) return;
142  poll = $.clock.every(10_000, () => {
143    stale = true;
144    $.ui.invalidate("ui.render");
145  });
146};
147
148export const register: Register = (on, options) => {
149  const effortOn = options.effort_routing_enabled !== false;
150  // Subagent and Workflow-agent steps: their own toggle, active only while effort routing is on.
151  const subOn = effortOn && options.subagent_effort_routing_enabled !== false;
152  const cacheOn = options.cache_aligner_enabled !== false;
153  const crusherOn = options.smart_crusher_enabled !== false;
154  // Lossless compaction runs inside the crusher's step, also with the crusher off (upstream lossless_only).
155  const compactOn = options.lossless_compaction_enabled !== false;
156  const dedupOn = options.cross_turn_dedup_enabled !== false;
157  const elideOn = options.dense_line_elider_enabled !== false;
158  const configOn = options.config_compressor_enabled !== false;
159  const htmlOn = options.html_extractor_enabled !== false;
160  // The router compressors: each owns its content type's lossy step and lossless fold.
161  const logOn = options.log_compressor_enabled !== false;
162  const searchOn = options.search_compressor_enabled !== false;
163  const diffOn = options.diff_compressor_enabled !== false;
164  const textOn = options.text_crusher_enabled !== false;
165  const splitOn = options.relevance_split_enabled !== false;
166  // The tag protector only narrows what the levers above rewrite: no compressOn term, no table.
167  const tagsOn = options.tag_protector_enabled !== false;
168  const compressOn = crusherOn || compactOn || dedupOn || elideOn || configOn || htmlOn || logOn || searchOn || diffOn || textOn || splitOn;
169  // Subagent and Workflow-agent tool results: their own toggle, active only while a compression lever is on.
170  const subCompressOn = compressOn && options.subagent_compression_enabled !== false;
171  // Unset means the manifest default (true), like the sibling toggles; the server stays fail-closed.
172  const storageOn = options.storage_enabled !== false;
173
174  on("session.start", async ($, e, next) => {
175    await $.command.register({
176      name: "headroom",
177      description: "inline-headroom stats: effort clamps, cache-hit drops, compression savings",
178    });
179    if (compressOn) {
180      try {
181        // Sticky within a module load: a later session.start that fails or answers another name leaves an earlier registration usable.
182        retrieveReady ||= (await $.tool.register(RETRIEVE_SPEC)).tool === RETRIEVE_TOOL;
183      } catch {
184        // no registration in this module load → retrieveReady stays false and no row is rewritten
185      }
186    }
187    return next(e);
188  });
189
190  // Storage backs only the effort routing and cache aligner tables.
191  const storageTables = effortOn || cacheOn;
192  const rowsShown = storageOn && storageTables;
193  // The storage rows' state when they hold no numbers: off, or the last fetch's error. None without a storage-backed table.
194  const note = (): string | undefined =>
195    !storageTables
196      ? undefined
197      : !storageOn
198        ? "storage is off (storage_enabled is not true): only the session row is kept"
199        : sums?.error === undefined
200          ? undefined
201          : `storage unavailable: ${sums.error}`;
202  // No note means the numbers are still loading ("…"); a note means they never will come ("–").
203  // The session row shows its last step's hit ratio; the storage rows are token-weighted over their windows.
204  // Each table is shown only while the lever it counts is on; the storage rows sit in both.
205  // The subagents row and the compression counts are session-only: persisting them needs new stats columns and a storage PROTOCOL bump (deferred).
206  // Subagent steps and clamps still reach the storage rows, inside the main loop's steps and clamped columns.
207  const tables = (): string[][][] => {
208    const [effort, cache, crusher, deduper, elider, compactor, configs, extractor, logs, searches, diffs, crushedTexts, splits] = statsTables(
209      [{ ...session, hit: lastHit }, ...(sums?.data ?? [])],
210      note() === undefined ? "…" : "–",
211      {
212        subagents: subOn ? subagents : undefined,
213        crush,
214        dedup,
215        elide,
216        compact,
217        config,
218        extract,
219        log,
220        search,
221        diff,
222        textcrush,
223        split,
224      },
225    );
226    return [
227      ...(effortOn ? [effort] : []),
228      ...(cacheOn ? [cache] : []),
229      ...(crusherOn ? [crusher] : []),
230      ...(dedupOn ? [deduper] : []),
231      ...(elideOn ? [elider] : []),
232      ...(compactOn ? [compactor] : []),
233      ...(configOn ? [configs] : []),
234      ...(htmlOn ? [extractor] : []),
235      ...(logOn ? [logs] : []),
236      ...(searchOn ? [searches] : []),
237      ...(diffOn ? [diffs] : []),
238      ...(textOn ? [crushedTexts] : []),
239      ...(splitOn ? [splits] : []),
240    ];
241  };
242  // With every lever off there is nothing to show, so nothing is read from storage either.
243  const idle = (): string | undefined =>
244    effortOn || cacheOn || compressOn
245      ? undefined
246      : "effort routing, cache aligner, smart crusher, lossless compaction, cross-turn dedup, dense line elider, config compressor, HTML extractor, log compressor, search compressor, diff compressor, text crusher and relevance split are off: nothing to show";
247  // Body height asked for when seated inline, mirroring the render: every table, a line for the storage note
248  // wherever one can show, and a gap between each.
249  const paneRows = (): number => {
250    if (idle() !== undefined) return 1; // the one "nothing to show" line
251    const blocks = [...tables().map((t) => t.length), ...(storageTables ? [1] : [])];
252    return blocks.reduce((a, b) => a + b, 0) + blocks.length - 1;
253  };
254
255  on("command.run", { command: "headroom" }, async ($) => {
256    const r = await $.ui.open({ id: PANE, title: "Headroom", focus: true, closeOnEscape: true, rows: paneRows() });
257    if (r.isPlaced) {
258      // Pane placed: print nothing (no transcript line, nothing in the model's context).
259      if (rowsShown) {
260        poll?.cancel(); // re-opening an open pane restarts its refresh instead of stacking a second one
261        poll = undefined;
262        arm($);
263        await refresh($); // the first numbers now, inside this hook (see loadSums)
264      }
265      return {};
266    }
267    // Not placed (headless/SDK, narrow terminal): the same tables as text, read from storage once.
268    const off = idle();
269    if (off !== undefined) return { text: off };
270    if (rowsShown) await refresh($);
271    const n = note();
272    return { text: [tables().map(tableText).join("\n\n"), ...(n === undefined ? [] : [n])].join("\n") };
273  });
274
275  on("ui.render", { component: "Pane", requestId: PANE }, async ($, e) => {
276    paneOpen = true;
277    if (rowsShown) {
278      arm($); // a hot reload leaves the pane open with no timer: its first redraw re-arms the refresh
279      if (stale || sums === undefined) {
280        stale = false;
281        await refresh($); // a tick or a reloaded pane: fetch inside this hook (see loadSums)
282      }
283    }
284    const { Box, Text } = $.ui.resolve(e);
285    // Box cells, not padded text: the columns line up on every surface, proportional fonts included.
286    const table = (rows: string[][]) =>
287      Box({
288        flexDirection: "column",
289        children: rows.map((row, j) =>
290          Box({
291            flexDirection: "row",
292            children: row.map((s, i) =>
293              Box({
294                width: CELL_WIDTHS[i],
295                justifyContent: i ? "flex-end" : "flex-start",
296                children: [Text({ bold: j === 0, children: [s] })],
297              }),
298            ),
299          }),
300        ),
301      });
302    const off = idle();
303    if (off !== undefined) return Box({ flexDirection: "column", children: [Text({ dimColor: true, children: [off] })] });
304    const n = note();
305    return Box({
306      flexDirection: "column",
307      gap: 1,
308      children: [
309        ...tables().map((t) => table(t)),
310        ...(n === undefined ? [] : [Text({ dimColor: true, children: [n] })]),
311      ],
312    });
313  });
314
315  // The refresh runs only while the pane is open: Esc, Ctrl+X X and $.ui.close all raise ui.close (an unload close skips the opener's hooks).
316  on("ui.close", { id: PANE }, async (_$, e, next) => {
317    const r = await next(e);
318    // { deny }: a hook beneath kept the pane open, so its refresh keeps running too.
319    if (r.deny === undefined) {
320      paneOpen = false;
321      poll?.cancel();
322      poll = undefined;
323      sums = undefined; // a reopened pane shows "…" until fresh numbers land, not the last session's
324    }
325    return r;
326  });
327
328  // One tool.call hook without a matcher for every job: the engine refuses a second one in one module (see CLAUDE.md).
329  // It observes failures for effort routing and answers headroom_retrieve.
330  if (effortOn || compressOn) {
331    // Observe AFTER the tool ran. A failure keeps full effort on the next step of the loop that made the call:
332    // the main loop's flag, or that subagent's entry. Under parallel calls the flag is sticky.
333    const failed = (agentId: string | undefined): void => {
334      if (!effortOn) return;
335      if (!agentId) toolErrored = true;
336      else if (subOn) agentErrored.add(agentId);
337    };
338    on("tool.call", async (_$, e, next) => {
339      let r: Awaited<ReturnType<typeof next>>;
340      try {
341        // headroom_retrieve is answered here (a call no hook answers fails); every other call runs beneath.
342        r = e.tool === RETRIEVE_TOOL ? retrieve((e as Record<string, unknown>).hash) : await next(e);
343      } catch (err) {
344        failed(e.agentId); // a tool that throws instead of returning an error result is still a failure
345        throw err;
346      }
347      if (isToolError(r)) failed(e.agentId);
348      return r; // results are rewritten at session.append, never here
349    });
350  }
351
352  if (compressOn) {
353    // One session.append hook, on tool results only: crushes, elides and folds a result before it is first stored and sent,
354    // so the model, the transcript file and every later request read one form (prompt-cache safe). The screen's tool row
355    // (toolUseResult) keeps the original. Every throw before next passes the row through unchanged (fail open).
356    on("session.append", { door: "tool-result" }, async ($, e, next) => {
357      // No marker may name a missing retrieve tool; rows no tool made and subagent rows with subagent compression off pass.
358      if (!retrieveReady || e.origin.kind !== "tool" || (e.agentId && !subCompressOn)) return next(e);
359      const tool = e.origin.tool;
360      let rw: ReturnType<typeof rewriteToolResults>;
361      try {
362        const levers = {
363          crush: crusherOn,
364          compact: compactOn,
365          elide: elideOn,
366          config: configOn,
367          extract: htmlOn,
368          log: logOn,
369          search: searchOn,
370          diff: diffOn,
371          textcrush: textOn,
372          split: splitOn,
373          tags: tagsOn,
374          dedup: dedupOn ? { states: dedupStates, key: e.agentId ?? "" } : undefined,
375        };
376        let query = "";
377        // levers.crush carries crusherOn: the two-argument call's SmartCrusher check is one term of the levers form.
378        if (wantsQuery(e.message.content, tool, levers)) {
379          try {
380            // A subagent row's query comes from that agent's own conversation; a { deny } leaves it empty.
381            const m = e.agentId ? await $.session.messages({ agentId: e.agentId }) : await $.session.messages();
382            if (Array.isArray(m)) query = crushQuery(m);
383          } catch {
384            // crush without query signals, as upstream does with no context
385          }
386        }
387        rw = rewriteToolResults(e.message.content, tool, levers, query);
388      } catch {
389        rw = undefined; // fail open: the row is stored as made (rewriteToolResults has already started a half-indexed corpus over)
390      }
391      if (!rw) return next(e);
392      storeOffloaded(offloaded, rw.offloaded);
393      storeOffloaded(folded, rw.folded);
394      crush.dropped += rw.crush.dropped;
395      crush.saved += rw.crush.saved;
396      dedup.spans += rw.dedup.spans;
397      dedup.saved += rw.dedup.saved;
398      elide.lines += rw.elide.lines;
399      elide.saved += rw.elide.saved;
400      compact.arrays += rw.compact.arrays;
401      compact.saved += rw.compact.saved;
402      config.texts += rw.config.texts;
403      config.saved += rw.config.saved;
404      extract.pages += rw.extract.pages;
405      extract.saved += rw.extract.saved;
406      log.texts += rw.log.texts;
407      log.saved += rw.log.saved;
408      search.texts += rw.search.texts;
409      search.saved += rw.search.saved;
410      diff.texts += rw.diff.texts;
411      diff.saved += rw.diff.saved;
412      textcrush.texts += rw.textcrush.texts;
413      textcrush.saved += rw.textcrush.saved;
414      split.texts += rw.split.texts;
415      split.saved += rw.split.saved;
416      if (paneOpen) {
417        try {
418          $.ui.invalidate("ui.render"); // redraw an open /headroom pane's compression rows now
419        } catch {
420          // a refused $ never costs the rewrite
421        }
422      }
423      // next exactly once, its answer relayed unchanged: the engine skips a hook that answers another row.
424      try {
425        return await next({ ...e, message: { ...e.message, content: rw.content } });
426      } catch (err) {
427        dropCorpus(e.agentId ?? ""); // the row was never stored: what this call indexed names a result the model never got
428        throw err;
429      }
430    });
431  }
432
433  if (dedupOn) {
434    // A compaction swaps the transcript for a summary, so the results the corpus indexes are no longer in the model's context
435    // and a pointer to one would name nothing it can read. A skipped compaction and a `precompute` (nothing installed) keep the corpus.
436    on("session.compact", async (_$, e, next) => {
437      const r = await next(e);
438      if (r.skip === undefined && e.trigger !== "precompute") dropCorpus(e.agentId ?? "");
439      return r;
440    });
441  }
442
443  on("turn.step", async function* ($, e, next) {
444    const id = e.agentId;
445    if (id) {
446      if (!subOn) return yield* next(e); // today's behaviour: subagent steps untouched
447      subagents.steps++;
448      pending.steps++; // the today / 7 days / 30 days rows count every step; the session row stays main-loop
449      // Same rule as the main loop, per agent: index 0 is the agent's own prompt step.
450      const to = stepEffort(e.index, agentErrored.has(id), e.effort);
451      if (to !== undefined) {
452        subagents.clamped++;
453        pending.clamped++;
454      }
455      agentErrored.delete(id); // consumed per step, like the main-loop flag
456      // Both counters moved before the step runs, so the redraw needs no finally. Only an open pane redraws:
457      // a Workflow fan-out would otherwise pay an invalidate per step.
458      if (paneOpen) {
459        try {
460          $.ui.invalidate("ui.render");
461        } catch {
462          // a refused $ never replaces the step's result: subagent steps passed straight through before this feature
463        }
464      }
465      // No cache-aligner accounting: a subagent's prompt cache is not the main loop's.
466      return yield* next(to === undefined ? e : { ...e, effort: to });
467    }
468    count("steps");
469    try {
470      let ev = e;
471      // ponytail: mid-turn user input (a queued command) arriving at index > 0 is
472      // still treated as mechanical; detect it via a prompt/queue event if that matters.
473      const to = effortOn ? stepEffort(e.index, toolErrored, e.effort) : undefined;
474      if (to !== undefined) {
475        ev = { ...e, effort: to };
476        count("clamped");
477      }
478      toolErrored = false; // consumed per step; index 0 resets it too
479      const result = yield* next(ev);
480      if (cacheOn && result?.usage) {
481        const u = result.usage;
482        count("input_tokens", toCount(u.input_tokens));
483        count("cache_read_input_tokens", toCount(u.cache_read_input_tokens));
484        count("cache_creation_input_tokens", toCount(u.cache_creation_input_tokens));
485        const hit = cacheHitRatio(result.usage);
486        if (hit !== undefined) {
487          if (isCacheDrop(lastHit, hit)) {
488            count("cache_drops");
489            $.ui.log(`cache drop ${pct(lastHit)} → ${pct(hit)} (wrote ${result.usage.cache_creation_input_tokens} tok)`);
490          }
491          lastHit = hit;
492        }
493      }
494      return result;
495    } finally {
496      // also on a failed or aborted step: steps/clamped moved before it
497      $.ui.invalidate("ui.render"); // redraw an open /headroom pane with the new stats
498    }
499  });
500
501  if (storageOn) {
502    // The mod's own storage calls need no permission rule: core checks $.mcp.call like a tool call (see isOwnStorageCall).
503    // 2.1.310 reports this hook as skipped once per session (the allow still stands); unavoidable, see CLAUDE.md.
504    on("tool.check", async (_$, e, next) => (isOwnStorageCall(next.origin.plugin, e.tool) ? { decision: "allow" as const, reason: "inline-headroom's own /headroom storage call" } : next(e)));
505  }
506
507  // One turn.complete hook for all three jobs: the engine refuses a second turn.complete without a matcher in one module.
508  if (storageOn || subOn || dedupOn) {
509    on("turn.complete", async ($, e, next) => {
510      // An agent's error entry and dedup corpus end with its turn, also with storage off or a throwing chain, so a finished
511      // agent's corpus never counts toward the cap that would evict the main loop's. No-ops while the lever is off: the Set stays empty.
512      if (e.agentId) {
513        agentErrored.delete(e.agentId);
514        dropCorpus(e.agentId);
515      }
516      const r = await next(e);
517      if (!storageOn) return r; // an agent's turn writes too: a background agent's steps would otherwise wait for the next main-loop turn
518      let today: string;
519      let purgeBefore: string;
520      let rows: ReturnType<typeof foldPending>;
521      try {
522        today = dayKey(await $.clock.now());
523        purgeBefore = windowStart(today, RETAIN_DAYS);
524        rows = foldPending(days, pending, today, purgeBefore);
525      } catch {
526        return r; // stats are a side feature: a bad clock never costs the turn's result
527      }
528      // Awaited below, so the storage calls run inside this hook (see loadSums); a cold service start (up to 3 s) delays the turn's end.
529      flushing = flushing
530        .then(async () => {
531          try {
532            await callStorage($, "stats_put", { writer: WRITER, rows, purgeBefore });
533          } catch {
534            return; // days keeps every total: the next turn rewrites them
535          }
536          for (const d of Object.keys(days)) if (d < today) delete days[d]; // final rows, written
537          if (poll !== undefined) await refresh($); // an open pane shows the rows just written, not at its next tick
538        })
539        // The chain must never reject: a rejected `flushing` would skip every later flush for the module's life.
540        .catch(() => {});
541      await flushing;
542      return r;
543    });
544  }
545
546  // /clear and resume go on in this process under a new session id: the session row starts over.
547  // Persisted totals and pending deltas are session-agnostic and carry on.
548  on("session.end", async ($, e, next) => {
549    Object.assign(session, zeroCounters());
550    Object.assign(subagents, { steps: 0, clamped: 0 });
551    Object.assign(crush, { dropped: 0, saved: 0 });
552    Object.assign(dedup, { spans: 0, saved: 0 });
553    Object.assign(elide, { lines: 0, saved: 0 });
554    Object.assign(compact, { arrays: 0, saved: 0 });
555    Object.assign(config, { texts: 0, saved: 0 });
556    Object.assign(extract, { pages: 0, saved: 0 });
557    Object.assign(log, { texts: 0, saved: 0 });
558    Object.assign(search, { texts: 0, saved: 0 });
559    Object.assign(diff, { texts: 0, saved: 0 });
560    Object.assign(textcrush, { texts: 0, saved: 0 });
561    Object.assign(split, { texts: 0, saved: 0 });
562    dedupStates.clear(); // the next session's results get their own corpus and ordinals
563    agentErrored.clear(); // an aborted agent whose turn.complete never came
564    lastHit = undefined;
565    $.ui.invalidate("ui.render");
566    const r = await next(e);
567    // A turn cut off before its turn.complete hook finished may leave a stats_put running: let it finish.
568    // `flushing` never rejects, and the engine's ~1.5 s end bound cuts the wait; core's end step already ran.
569    await flushing;
570    return r;
571  });
572};
573
hooks/policy.mjs 5559 lines
1// Pure policy for inline-headroom. Never reference the mods `$` here: the
2// engine's validation rejects passing the mods API into functions imported
3// from another file. All `$` use lives inside hooks in register.ts. No clock
4// reads either: time comes in as arguments.
5
6/** @typedef {'low'|'medium'|'high'|'xhigh'|'max'} Effort */
7/** @typedef {{steps: number, clamped: number, cache_drops: number, input_tokens: number, cache_read_input_tokens: number, cache_creation_input_tokens: number}} Counters */
8/** @typedef {Counters & {hit?: number}} Row hit: the ratio to show in place of the token-weighted one (the session row shows its last step's) */
9/** @typedef {{ role: 'user'|'assistant', text: string, toolUses: readonly { input: Record<string, unknown> }[] }} QueryMessage the SessionMessage fields crushQuery reads */
10/**
11 * A crushed document: compact text, rows and items lost, arrays rendered losslessly and the characters those tables saved,
12 * [hash, original text (a crushed array's JSON, an elided block, a folded span)] per crushed array.
13 * @typedef {{ text: string, rowsDropped: number, compacted: number, compactSaved: number, offloaded: [string, string][] }} CrushOutcome
14 */
15/** @typedef {{ rowsDropped: number, compacted: number, compactSaved: number, offloaded: [string, string][] }} CrushAcc processValue's running totals, mutated */
16/** @typedef {{ lossy: boolean, lossless: boolean }} CrushModes which SmartCrusher stages run: the lossy row drop, the lossless table */
17/** @typedef {{ name: string, type: string, nullable: boolean }} FieldSpec one compaction column (upstream FieldSpec) */
18/**
19 * One compaction cell (upstream CellValue without OpaqueRef): a scalar (any JSON value), a missing key, or a nested compaction.
20 * @typedef {{ s: unknown } | { m: true } | { n: Compaction }} Cell
21 */
22/** @typedef {{ key: string, fields: FieldSpec[], rows: Cell[][] }} Bucket one bucket of a heterogeneous array: its discriminator value and its table */
23/**
24 * The compaction IR (upstream Compaction without OpaqueRef): a table, buckets split by a discriminator, or the items untouched.
25 * @typedef {{ kind: "table", fields: FieldSpec[], rows: Cell[][] } | { kind: "buckets", disc: string, buckets: Bucket[] } | { kind: "untouched", value: unknown }} Compaction
26 */
27/** @typedef {{ left: number }} WorkBudget a scan's remaining work units, mutated; below 0 means exhausted */
28/** @typedef {{ text: string, lines: number, offloaded: [string, string][] }} Elision a dense-line-elided text: the shortened text, the lines elided, [hash, original text] */
29/**
30 * One conversation's dedup corpus: the last ordinal handed out, each indexed block's verbatim lines (null where folded) by
31 * ordinal, the anchor index (match key → [ordinal, line] first-seen, at most 16), and the indexed characters.
32 * @typedef {{ turn: number, corpus: Map<number, (string|null)[]>, index: Map<string, [number, number][]>, chars: number }} DedupState
33 */
34/** @typedef {{ text: string, spans: number, offloaded: [string, string][] }} Fold a deduplicated text: the text with pointers, the runs folded, [hash, run text] per run */
35/** @typedef {{ type: string } & Record<string, unknown>} ContentBlock one Messages-API content block, as session.append hands it */
36/**
37 * Upstream ContentType tags (as_str); 'tabular' is git status here, 'structured_config' is Python's (Rust has no such tag).
38 * @typedef {'json_array'|'diff'|'html'|'tabular'|'search'|'build'|'structured_config'|'source_code'|'text'} ContentType
39 */
40/**
41 * A compression step a content type's route may run: a lever, or (logfold, searchfold, difffold, textfold) a compressor's
42 * lossless fold, which belongs to that compressor's lever.
43 * @typedef {'crush'|'config'|'extract'|'elide'|'split'|'logfold'|'log'|'searchfold'|'search'|'difffold'|'diff'|'textfold'|'textcrush'} RouteStep
44 */
45/** @typedef {{ close: boolean, nameEnd: number, end: number, selfClosing: boolean }} TagToken one `<name …>` or `</name>` tag: its kind, where its name ends, where it ends */
46/** @typedef {'yaml'|'toml'|'ini'} ConfigFlavor a structured config's dialect */
47/**
48 * Which levers rewrite this row; dedup names the conversations map and this row's key ("" main, else agentId).
49 * The log, search and diff compressors, the text crusher and the relevance split are off when omitted.
50 * @typedef {{
51 *   crush: boolean, compact?: boolean, elide: boolean, config?: boolean, extract?: boolean,
52 *   log?: boolean, search?: boolean, diff?: boolean, textcrush?: boolean, split?: boolean,
53 *   tags?: boolean, dedup?: { states: Map<string, DedupState>, key: string }
54 * }} Levers
55 */
56/**
57 * A rewritten tool-result row: its blocks, the originals for the CCR store (`offloaded`: the crusher's and the elider's sole copies;
58 * `folded`: dedup runs, which a pointer's earlier result still holds), and each lever's savings.
59 * @typedef {object} RowRewrite
60 * @property {ContentBlock[]} content
61 * @property {[string, string][]} offloaded
62 * @property {[string, string][]} folded
63 * @property {{ dropped: number, saved: number }} crush
64 * @property {{ arrays: number, saved: number }} compact
65 * @property {{ texts: number, saved: number }} config
66 * @property {{ pages: number, saved: number }} extract
67 * @property {{ lines: number, saved: number }} elide
68 * @property {{ spans: number, saved: number }} dedup
69 * @property {{ texts: number, saved: number }} log the log compressor's rewrites, its lossless fold's included
70 * @property {{ texts: number, saved: number }} search the search compressor's rewrites, its lossless fold's included
71 * @property {{ texts: number, saved: number }} diff the diff compressor's rewrites, its index-line strip's included
72 * @property {{ texts: number, saved: number }} textcrush the text crusher's rewrites, its lossless fold's included
73 * @property {{ texts: number, saved: number }} split the relevance split's rewrites
74 */
75/**
76 * The in-memory, session-only /headroom counters (statsTables' `memory`).
77 * @typedef {object} StatsMemory
78 * @property {{ steps: number, clamped: number }} [subagents]
79 * @property {{ dropped: number, saved: number }} [crush]
80 * @property {{ spans: number, saved: number }} [dedup]
81 * @property {{ lines: number, saved: number }} [elide]
82 * @property {{ arrays: number, saved: number }} [compact]
83 * @property {{ texts: number, saved: number }} [config]
84 * @property {{ pages: number, saved: number }} [extract]
85 * @property {{ texts: number, saved: number }} [log]
86 * @property {{ texts: number, saved: number }} [search]
87 * @property {{ texts: number, saved: number }} [diff]
88 * @property {{ texts: number, saved: number }} [textcrush]
89 * @property {{ texts: number, saved: number }} [split]
90 */
91/**
92 * One dict-array field (upstream FieldStats); the numeric statistics are absent when not finite.
93 * @typedef {{ name: string, type: string, unique: number, ratio: number, min?: number, max?: number, mean?: number, variance?: number, changePoints: number[], avgLen?: number }} FieldStats
94 */
95/**
96 * A dict array's analysis: fields sorted by name, the planner (or skip), and the rows no plan drops.
97 * @typedef {{ fields: FieldStats[], strategy: 'skip'|'time_series'|'cluster'|'top_n'|'smart_sample', errors: number[], outliers: Set<number>, anomalies: Set<number> }} Analysis
98 */
99/**
100 * One dict array's planning inputs: rows, their compact and sorted-key JSON, the analysis, the query and the row budget K.
101 * @typedef {{ items: Record<string, unknown>[], strings: string[], canon: string[], analysis: Analysis, query: string, max: number }} CrushPlan
102 */
103
104export const EFFORT_ORDER = /** @type {const} */ (["low", "medium", "high", "xhigh", "max"]);
105export const CACHE_DROP_THRESHOLD = 0.6;
106/** The /headroom table rows, top to bottom. `days`: the rolling window, today included; 0 = this session, in memory. */
107export const ROWS = /** @type {const} */ ([
108  { label: "session", days: 0 },
109  { label: "today", days: 1 },
110  { label: "7 days", days: 7 },
111  { label: "30 days", days: 30 },
112]);
113/** Table column widths in cells: the row label, then each value column. */
114export const CELL_WIDTHS = /** @type {const} */ ([16, 8, 8]);
115/** Persisted days kept: the longest row's window, never less. */
116export const RETAIN_DAYS = 30;
117/** The name register.ts registers the retrieval tool under. */
118export const RETRIEVE_NAME = "headroom_retrieve";
119/** This plugin's name, as `next.origin.plugin` reads it for the mod's own `$` calls. */
120export const PLUGIN = "inline-headroom";
121/** headroom_retrieve's full name: the tool.register op serves a mod tool as `mcp__<plugin>__<name>`. */
122export const RETRIEVE_TOOL = `mcp__${PLUGIN}__${RETRIEVE_NAME}`;
123/** A JSON document is crushed only above this many characters (upstream min_tokens_to_crush 200 × 4 chars per token: the mod has no tokenizer). */
124export const CRUSH_MIN_CHARS = 800;
125/** Characters of assistant tool-call input JSON the crusher's query keeps in all, newest first (a deviation: upstream has no cap). */
126export const CRUSH_QUERY_INPUT_CHARS = 16_384;
127/** Offloaded originals kept for headroom_retrieve, oldest evicted first (upstream CCR DEFAULT_CAPACITY). */
128export const CCR_CAPACITY = 1000;
129/** Characters of offloaded originals kept in all (about 32 MB as UTF-16), oldest evicted first. Deviation: upstream caps by count only. */
130export const CCR_MAX_CHARS = 16_000_000;
131/** Upstream ERROR_KEYWORDS: a row whose lowercased JSON holds one is never dropped. */
132export const ERROR_KEYWORDS = /** @type {const} */ (["error", "exception", "failed", "failure", "critical", "fatal", "crash", "panic", "abort", "timeout", "denied", "rejected"]);
133
134const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
135// The persisted counters in mcp/server.mjs STATS_KEYS order. That file stays import-free, so the list is
136// repeated on purpose; test/inline-headroom/storage.test.mjs pins both orders.
137const COUNTER_KEYS = /** @type {const} */ (["steps", "clamped", "cache_drops", "input_tokens", "cache_read_input_tokens", "cache_creation_input_tokens"]);
138const DAY_MS = 86400000;
139// SmartCrusher defaults: upstream SmartCrusherConfig::default() and compute_optimal_k's min_k.
140const MAX_ITEMS_AFTER_CRUSH = 15;
141const MIN_K = 3;
142// CJK code point ranges (kana, ideographs, Hangul), as upstream's is_cjk_char.
143const CJK_RANGES = [
144  [0x3040, 0x30ff],
145  [0x3400, 0x4dbf],
146  [0x4e00, 0x9fff],
147  [0xac00, 0xd7af],
148  [0xf900, 0xfaff],
149];
150const MIN_ITEMS_TO_ANALYZE = 5;
151const VARIANCE_THRESHOLD = 2.0;
152const RELEVANCE_THRESHOLD = 0.3;
153const MAX_PROCESS_DEPTH = 50;
154// Lossless compaction: upstream SmartCrusherConfig::default() (lossless_min_savings_ratio) and CompactConfig::default().
155const LOSSLESS_MIN_SAVINGS = 0.15;
156const COMPACT_MIN_ITEMS = 2;
157const COMPACT_CORE_FIELD_FRACTION = 0.8;
158const COMPACT_HETEROGENEOUS_CORE_RATIO = 0.6;
159const COMPACT_MAX_FLATTEN_INNER_KEYS = 6;
160const COMPACT_MIN_BUCKETS = 2;
161const COMPACT_MAX_BUCKETS = 8;
162const COMPACT_MAX_DISCRIMINATOR_RATIO = 0.7;
163// Deviation: a column name holding one of these would make the `[N]{name:type,…}` header undecodable (upstream leaves names unescaped).
164const COMPACT_BAD_NAME_RE = /[,:{}?\n\r]/;
165// String, number and mixed-array crushers: upstream SmartCrusherConfig::default() first_fraction and last_fraction.
166const K_FIRST_FRACTION = 0.3;
167const K_LAST_FRACTION = 0.15;
168const ISO_DATETIME_RE = /^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}/;
169const ISO_DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
170// shortcut: Python int() also takes `_` digit separators; add them if a payload needs it.
171const PY_INT_RE = /^\s*[+-]?\d+\s*$/;
172// Anchor weights (front, middle, back) per planner, from upstream AnchorConfig::default(). The search pattern's
173// weights are left out: the top_n planner selects no anchors.
174const ANCHOR_WEIGHTS = {
175  smart_sample: [0.5, 0.1, 0.4],
176  cluster: [0.15, 1 - 0.15 - 0.75, 0.75],
177  time_series: [0.45, 0.1, 0.45],
178};
179const RECENCY_WORDS = ["latest", "recent", "last", "newest", "current", "now"];
180const HISTORICAL_WORDS = ["first", "oldest", "earliest", "original", "initial", "beginning"];
181// Query anchors (upstream anchors.rs); JS \b is ASCII-only where Rust's is Unicode.
182const ANCHOR_UUID_RE = /\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\b/g;
183const ANCHOR_NUMBER_RE = /\b\d{4,}\b/g;
184const ANCHOR_HOST_RE = /\b[a-zA-Z0-9][-a-zA-Z0-9]*\.[a-zA-Z0-9][-a-zA-Z0-9]*(?:\.[a-zA-Z]{2,})?\b/g;
185const ANCHOR_QUOTED_RE = /['"]([^'"]{1,50})['"]/g;
186const ANCHOR_EMAIL_RE = /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/g;
187const BM25_TOKEN_RE = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|\b\d{4,}\b|[a-z0-9_]+/g;
188// The mod's own storage tools are never crushed: a kv_get → edit → kv_set would write the row loss back to storage.db.
189const OWN_STORAGE_PREFIX = `mcp__plugin_${PLUGIN}_storage__`;
190const RETRIEVE_SUFFIX = `__${RETRIEVE_NAME}`;
191// Dense line elider: upstream dense_line_elider.py.
192const DENSE_MIN_LINE_CHARS = 300;
193const DENSE_MAX_SPACE_RATIO = 0.06;
194const DENSE_MIN_TOTAL_CHARS = 2000;
195const DENSE_HEAD_CHARS = 160;
196const DENSE_TAIL_CHARS = 80;
197// JSON span scan work budget: upstream recursive_json.py.
198const SCAN_BUDGET_PER_CHAR = 4;
199const SCAN_BUDGET_FLOOR = 4096;
200// Cross-turn dedup: upstream cross_turn_dedup.py.
201const DEDUP_MIN_LINES = 3;
202const DEDUP_MIN_CHARS = 40;
203const DEDUP_MAX_ANCHOR_CANDIDATES = 16;
204// Deviation: a `:` separator must not be followed by a digit (`10:15:03`, `8080:80`), where the leading integer is a time or port, not a line number.
205const DEDUP_LINENO_RE = /^([1-9]\d*)(:(?!\d)|\t)([\s\S]*)$/;
206const DEDUP_TRIVIAL = new Set(["return", "pass", "else:", "try:", "except:", "finally:", "break", "continue", "});", "})", "],", "),", '"""', "'''", "..."]);
207// shortcut: about a 1M-token context at 4 chars per token; older content has left the model's window. Raise it if long sessions stop folding.
208/** Indexed dedup characters kept across all conversations, least recently appended conversation dropped first. Deviation: upstream rebuilds per request and needs no cap. */
209export const DEDUP_MAX_CHARS = 4_000_000;
210// Content detector: upstream content_detector.py, branch order of content_detector.rs (read 2026-10-11 at 976aa71).
211const JSON_MIN_BULK_FRACTION = 0.6;
212const DETECT_MAX_LINE_CHARS = 1000;
213const DIFF_HEADER_RE = /^(?:diff --git|diff --combined |diff --cc |--- a\/|@@\s+-\d+,\d+\s+\+\d+,\d+\s+@@|@@@+\s+-\d+(?:,\d+)?\s+(?:-\d+(?:,\d+)?\s+)+\+\d+(?:,\d+)?\s+@@@+)/;
214const DIFF_CHANGE_RE = /^[+-][^+-]/;
215const HTML_DOCTYPE_RE = /^\s*<!doctype\s+html/i;
216const HTML_TAG_RE = /<html[\s>]/i;
217const HTML_HEAD_RE = /<head[\s>]/i;
218const HTML_BODY_RE = /<body[\s>]/i;
219// Global, so only ever used through String.prototype.match, which resets lastIndex.
220const HTML_STRUCTURAL_RE = /<(?:div|span|script|style|link|meta|nav|header|footer|aside|article|section|main)[\s>]/gi;
221const GIT_STATUS_HEADERS = new Set(["Changes to be committed:", "Changes not staged for commit:", "Untracked files:", "Unmerged paths:"]);
222const GIT_STATUS_ENTRY_RE = /^\s+(?:new file|modified|deleted|renamed|copied|typechange|both modified|both added|both deleted|added by us|deleted by us|added by them|deleted by them):\s+\S/;
223// The separators of Python's str.splitlines(), used by git status only.
224// eslint-disable-next-line no-control-regex -- \x1c-\x1e are splitlines() separators, matched on purpose
225const LINE_BREAK_RE = /\r\n|[\n\r\v\f\x1c-\x1e\x85\u{2028}\u{2029}]/u;
226// Upstream lossless_compaction.py _TIMESTAMP_ROW_RE: a timestamped log row is never a grep line.
227const TIMESTAMP_ROW_RE = /^\s*\[?(?:\d{4}-\d{2}-\d{2}[ T]\d{1,2}:\d{2}|\d{2}\/\d{2}\/\d{2,4}[ T]\d{1,2}:\d{2}|[A-Z][a-z]{2}\s+\d{1,2}\s+\d{1,2}:\d{2}|\d{1,2}:\d{2}:\d{2}(?:[.,]\d+)?(?:\s|\]|$))/;
228const SEARCH_LINE_RE = /^[^\s:]+:\d+:/;
229// Compiler and linter diagnostics (`f.c:3:5: error:`, `f.py:3: warning:`, `f.py:3:1: F401 `, `f.py:3:0: C0114:`) share grep's
230// `path:N:` shape; compressSearch declines them, as its selection would drop errors and every code-frame line.
231const DIAGNOSTIC_ROW_RE = /^[^\s:]+:\d+(?::\d+)?:\s+(?:(?:fatal error|error|warning|note)\b|[A-Z]{1,4}\d{2,5}\b)/;
232const GREP_COLON_DASH_RE = /^[^\s:]+:\d+-/;
233const GREP_CONTEXT_RE = /^([^\s:]+?)-\d+-/;
234// Structured config: upstream content_detector.py _CONFIG_*/_TOML_*/_YAML_* patterns (_INI_ASSIGN_RE is the isIniAssign scanner).
235const CONFIG_SECTION_RE = /^\s*\[\[?[\w.\-"' ]+\]\]?\s*$/;
236const TOML_ASSIGN_RE = /^\s*(?:[\w.-]+|"[^"]+"|'[^']+')\s*=\s*\S/;
237const TOML_KEY_RE = /^\s*(?:[\w.-]+|"[^"]+"|'[^']+')\s*=/;
238const YAML_KEY_RE = /^\s*(?:-\s+)?(?:[\w./-]+|"[^"]+"|'[^']+')\s*:(?:\s|$)/;
239const YAML_LIST_RE = /^\s*-\s+\S/;
240const YAML_DOC_RE = /^---\s*$|^\.\.\.\s*$/;
241const CONFIG_COMMENT_RE = /^\s*[#;]/;
242const MARKDOWN_HEADING_RE = /^#{2,6}\s+\S/;
243const INI_KEY_CHAR_RE = /[\w.\-@ ]/;
244// What the TOML flavor check accepts as a value (it stands in for tomllib): strings, numbers, booleans, dates/times, arrays, tables.
245const TOML_STRING_RE = /^(?:"(?:[^"\\]|\\.)*"|'[^']*')\s*(?:#.*)?$/;
246const TOML_NUMBER_RE = /^[+-]?(?:\d[\d_]*(?:\.\d[\d_]*)?(?:[eE][+-]?\d[\d_]*)?|0x[\dA-Fa-f_]+|0o[0-7_]+|0b[01_]+|inf|nan)$/;
247const TOML_DATETIME_RE = /^\d{4}-\d{2}-\d{2}(?:[Tt ]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:[Zz]|[+-]\d{2}:\d{2})?)?$|^\d{2}:\d{2}:\d{2}(?:\.\d+)?$/;
248const LINE_NUMBERED_RE = /^\s*[1-9]\d*\t/;
249const CONFIG_MAX_CHARS = 1_000_000;
250// Config compressor: upstream config_compressor.py and lossless_compaction.py (collapse_runs, fold_repeated_blocks).
251const YAML_BLOCK_SCALAR_RE = /(?::\s*|^\s*-\s+)[|>][+-]?\d*\s*$/m; // `key: |` or a sequence item `- |`
252const TOML_MULTILINE_RE = /"""|'''/;
253const RUN_MARKER_RE = /^\.\.\. \(repeated (\d+) times\)$/;
254const BLOCK_MARKER_RE = /^\.\.\. \(repeats (\d+) lines from (\d+) lines back\)$/;
255const FOLD_MIN_BLOCK = 3;
256const FOLD_MAX_BLOCK = 64;
257const FOLD_MAX_CANDIDATES = 8;
258const FOLD_MAX_LINES = 20_000;
259// HTML extractor: a bounded stand-in for upstream html_extractor.py (trafilatura, images and comments off).
260// Skipped whole, open tag to close tag: boilerplate and non-text content.
261const HTML_DROP = new Set("head script style noscript template svg math iframe object embed canvas audio video picture nav footer aside button select textarea".split(" "));
262// A new line at open and close.
263const HTML_BLOCK = new Set("p div section article main header ul ol dl dt dd table thead tbody tfoot tr blockquote pre figure figcaption address details summary hgroup search hr".split(" "));
264const HTML_HEADING_RE = /^h([1-6])$/;
265const HTML_HREF_RE = /\shref\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i;
266const HTML_ENTITY_RE = /&(?:#(\d{1,7})|#[xX]([\da-fA-F]{1,6})|(amp|lt|gt|quot|apos|nbsp));/g;
267/** @type {Record<string, string>} */
268const HTML_ENTITIES = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " " };
269// One cached `</name\s*>` search per dropped element name (global, so a search starts at lastIndex).
270/** @type {Map<string, RegExp>} */
271const HTML_CLOSE_RES = new Map();
272// Tag protector: upstream tag_protector.rs HTML5_TAGS, element for element; every other tag name is a custom (workflow) tag.
273const HTML5_TAGS = new Set(
274  (
275    "html base head link meta style title body address article aside footer h1 h2 h3 h4 h5 h6 header hgroup main nav section search " +
276    "blockquote dd div dl dt figcaption figure hr li menu ol p pre ul a abbr b bdi bdo br cite code data dfn em i kbd mark q rp rt ruby " +
277    "s samp small span strong sub sup time u var wbr area audio img map track video embed iframe object param picture portal source svg " +
278    "math canvas noscript script del ins caption col colgroup table tbody td tfoot th thead tr button datalist fieldset form input label " +
279    "legend meter optgroup option output progress select textarea details dialog summary slot template"
280  ).split(" "),
281);
282// Upstream _LOG_PATTERNS in order, each tried with search(); indexes 0 and 1 are the error / warn patterns.
283const LOG_PATTERNS = [
284  /\b(?:ERROR|FAIL|FAILED|FATAL|CRITICAL)\b/i,
285  /\b(?:WARN|WARNING)\b/i,
286  /\b(?:INFO|DEBUG|TRACE)\b/i,
287  /^\s*\d{4}-\d{2}-\d{2}/,
288  /^\s*\[\d{2}:\d{2}:\d{2}\]/,
289  /^={3,}|^-{3,}/,
290  /^\s*PASSED|^\s*FAILED|^\s*SKIPPED/,
291  /^npm ERR!|^yarn error|^cargo error/,
292  /Traceback \(most recent call last\)/,
293  /^\w*(?:Error|Exception):/,
294  /^\s*at\s+[\w.$/]+\(/,
295  /^\s*at async \S/,
296  /^(?:panic|fatal error): /,
297  /^goroutine \d+ \[/,
298  /^\t\S+\.go:\d+ \+0x/,
299  /^thread '[^']*' panicked at/,
300  /^stack backtrace:/,
301  /^\s+\d+: \S/,
302  /^\s+at \S+:\d+:\d+$/,
303  /^Unhandled exception\./,
304  /^\s*at [\s\S]+\) in [\s\S]+:line \d+/,
305  /^Caused by: /,
306  /^\s*\.\.\. \d+ more$/,
307  /^<!\[LOG\[/,
308];
309// Upstream _CODE_PATTERNS in dict order. Python calls pattern.match(line), so every pattern is anchored with ^.
310/** @type {[string, RegExp[]][]} */
311const CODE_PATTERNS = [
312  ["python", [/^\s*(?:def|class|import|from|async def)\s+\w+/, /^\s*@\w+/, /^\s*"""/, /^\s*if __name__\s*==/]],
313  ["javascript", [/^\s*(?:function|const|let|var|class|import|export)\s+/, /^\s*(?:async\s+function|=>\s*\{)/, /^\s*module\.exports/]],
314  ["typescript", [/^\s*(?:interface|type|enum|namespace)\s+\w+/, /^:\s*(?:string|number|boolean|any|void)\b/]],
315  ["go", [/^\s*(?:func|type|package|import)\s+/, /^\s*func\s+\([^)]+\)\s+\w+/]],
316  ["rust", [/^\s*(?:fn|struct|enum|impl|mod|use|pub)\s+/, /^\s*#\[/]],
317  ["java", [/^\s*(?:public|private|protected)\s+(?:class|interface|enum)/, /^\s*@\w+/, /^\s*package\s+[\w.]+;/]],
318  [
319    "csharp",
320    [
321      /^\s*using\s+[\w.]+\s*;/,
322      /^\s*namespace\s+[\w.]+/,
323      /^\s*(?:public|private|protected|internal|sealed|static|abstract|partial)\s+(?:class|struct|record|interface|enum)\b/,
324      /^[\s\S]*\b(?:get|set|init);/,
325    ],
326  ],
327  ["php", [/^<\?php\b/, /^\s*namespace\s+[\w\\]+\s*;/, /^\s*use\s+[\w\\]+(?:\s+as\s+\w+)?\s*;/, /^\s*(?:public|private|protected|static|abstract|final)?\s*function\s+\w+\s*\(/, /^\$this->/]],
328];
329
330/**
331 * Whether a tool.check decides this mod's own storage call: the mods API's `mcp.call` reaches core's permission step as a
332 * `tool.call` (live on 2.1.296, although the typings promise no prompt), so without an allow rule a headless
333 * session denies every `/headroom` write and an interactive one asks. The model's own storage calls are not covered.
334 * @param {string} originPlugin `next.origin.plugin`
335 * @param {string} tool
336 * @returns {boolean}
337 */
338export function isOwnStorageCall(originPlugin, tool) {
339  return originPlugin === PLUGIN && tool.startsWith(OWN_STORAGE_PREFIX);
340}
341
342/**
343 * Clamp-only: returns `target` only when `current` is a known effort level
344 * strictly above it; otherwise undefined (absent, numeric, unknown, at/below).
345 * @param {unknown} current
346 * @param {Effort} [target='low']
347 * @returns {Effort|undefined}
348 */
349export function clampEffort(current, target = "low") {
350  if (typeof current !== "string") return undefined;
351  const c = EFFORT_ORDER.indexOf(/** @type {Effort} */ (current));
352  return c > EFFORT_ORDER.indexOf(target) ? target : undefined;
353}
354
355/**
356 * The routing rule shared by the main loop and every subagent: a mechanical
357 * step (after index 0, no tool error since the loop's last step) is clamped.
358 * @param {number} index the step's index in its loop (0 = the ask step)
359 * @param {boolean} errored a tool error since that loop's last step
360 * @param {unknown} effort the step's current effort
361 * @returns {Effort|undefined} the lowered effort, or undefined to leave it
362 */
363export function stepEffort(index, errored, effort) {
364  return index > 0 && !errored ? clampEffort(effort) : undefined;
365}
366
367/**
368 * A tool.call result is a failure when it is errored or denied.
369 * @param {Record<string, unknown>} result
370 * @returns {boolean}
371 */
372export function isToolError(result) {
373  return result.isError === true || typeof result.deny === "string";
374}
375
376/**
377 * @param {{input_tokens: number, cache_read_input_tokens: number, cache_creation_input_tokens: number}} usage
378 * @returns {number|undefined}
379 */
380export function cacheHitRatio(usage) {
381  const read = usage.cache_read_input_tokens;
382  const total = usage.input_tokens + read + usage.cache_creation_input_tokens;
383  return total > 0 ? read / total : undefined;
384}
385
386/**
387 * A ratio as a whole percentage, "–" when there is none.
388 * @param {number|undefined} n
389 * @returns {string}
390 */
391export function pct(n) {
392  return n === undefined ? "–" : `${Math.round(n * 100)}%`;
393}
394
395/**
396 * @param {number|undefined} prev
397 * @param {number} hit
398 * @returns {boolean}
399 */
400export function isCacheDrop(prev, hit) {
401  return prev !== undefined && prev >= CACHE_DROP_THRESHOLD && hit < CACHE_DROP_THRESHOLD;
402}
403
404/**
405 * A usage field as a persistable counter delta: a non-negative safe integer, else 0. One missing or
406 * odd field (undefined, NaN, a fraction) must not poison the running totals, because the server
407 * rejects every stats_put that carries such a row.
408 * @param {unknown} n
409 * @returns {number}
410 */
411export function toCount(n) {
412  return typeof n === "number" && Number.isSafeInteger(n) && n >= 0 ? n : 0;
413}
414
415/** @returns {Counters} all six counters at 0 */
416export function zeroCounters() {
417  return /** @type {Counters} */ (Object.fromEntries(COUNTER_KEYS.map((k) => [k, 0])));
418}
419
420/**
421 * Local calendar day of an epoch-ms instant as YYYY-MM-DD.
422 * @param {number} ms
423 * @param {number} [offsetMin] minutes UTC minus local (Date#getTimezoneOffset); defaults to this runtime's offset at `ms`
424 * @returns {string}
425 */
426export function dayKey(ms, offsetMin = new Date(ms).getTimezoneOffset()) {
427  return new Date(ms - offsetMin * 60000).toISOString().slice(0, 10);
428}
429
430/**
431 * First day of a rolling window of `days` calendar days ending with (and including) `day`.
432 * Calendar arithmetic in UTC, so DST never shifts it.
433 * @param {string} day YYYY-MM-DD
434 * @param {number} days >= 1
435 * @returns {string}
436 */
437export function windowStart(day, days) {
438  return new Date(Date.parse(`${day}T00:00:00Z`) - (days - 1) * DAY_MS).toISOString().slice(0, 10);
439}
440
441/**
442 * Adds `pending` to `days[today]` (creating it), zeroes `pending` in place, drops every day outside
443 * [purgeBefore, today], and returns each remaining day as a stats_put row (copies, so later folds
444 * never change a queued write). Mutates `days` and `pending`.
445 * @param {Record<string, Counters>} days
446 * @param {Counters} pending
447 * @param {string} today YYYY-MM-DD
448 * @param {string} purgeBefore YYYY-MM-DD
449 * @returns {(Counters & {day: string})[]}
450 */
451export function foldPending(days, pending, today, purgeBefore) {
452  const total = (days[today] ??= zeroCounters());
453  for (const k of COUNTER_KEYS) {
454    total[k] += pending[k];
455    pending[k] = 0; // in place: register.ts holds pending in a const
456  }
457  // Days after today go too, so a clock moved backwards never grows a stats_put past the window.
458  for (const day of Object.keys(days)) if (day < purgeBefore || day > today) delete days[day];
459  return Object.entries(days).map(([day, c]) => ({ day, ...c }));
460}
461
462/**
463 * The /headroom tables as rows of cells. Each table starts with its header row (heading, then the column names), then one row per ROWS entry.
464 * A row without counters (still loading, storage off or failing) shows `blank` in every value cell. The in-memory session-only
465 * counters add a `subagents` row under effort routing's session row, and the smart crusher, dedup, line elider, compaction,
466 * config, html extractor, logs, search, diff, text crusher and relevance split tables, which have only a session row.
467 * @param {readonly (Row|undefined)[]} counters one per ROWS entry, in ROWS order
468 * @param {string} blank
469 * @param {StatsMemory} [memory]
470 * @returns {string[][][]} effort routing, cache aligner, smart crusher, dedup, line elider, compaction, config, html extractor,
471 *   logs, search, diff, text crusher, relevance split
472 */
473export function statsTables(counters, blank, memory = {}) {
474  const {
475    subagents,
476    crush = { dropped: 0, saved: 0 },
477    dedup = { spans: 0, saved: 0 },
478    elide = { lines: 0, saved: 0 },
479    compact = { arrays: 0, saved: 0 },
480    config = { texts: 0, saved: 0 },
481    extract = { pages: 0, saved: 0 },
482    log = { texts: 0, saved: 0 },
483    search = { texts: 0, saved: 0 },
484    diff = { texts: 0, saved: 0 },
485    textcrush = { texts: 0, saved: 0 },
486    split = { texts: 0, saved: 0 },
487  } = memory;
488  /**
489   * @param {string} heading
490   * @param {string[]} columns
491   * @param {(c: Row) => string[]} cells
492   * @param {string[][]} [underSession] rows right under the session row
493   * @returns {string[][]}
494   */
495  const table = (heading, columns, cells, underSession = []) => [
496    [heading, ...columns],
497    ...ROWS.flatMap((v, i) => {
498      const c = counters[i];
499      const row = [v.label, ...(c ? cells(c) : columns.map(() => blank))];
500      return v.days === 0 ? [row, ...underSession] : [row];
501    }),
502  ];
503  const session = ROWS.find((v) => v.days === 0)?.label ?? "session";
504  return [
505    table("effort routing", ["steps", "clamped"], (c) => [String(c.steps), String(c.clamped)], subagents ? [["subagents", String(subagents.steps), String(subagents.clamped)]] : []),
506    table("cache aligner", ["hit", "drops"], (c) => [pct(c.hit ?? cacheHitRatio(c)), String(c.cache_drops)]),
507    [
508      ["smart crusher", "dropped", "saved"],
509      [session, String(crush.dropped), String(crush.saved)],
510    ],
511    [
512      ["dedup", "spans", "saved"],
513      [session, String(dedup.spans), String(dedup.saved)],
514    ],
515    [
516      ["line elider", "lines", "saved"],
517      [session, String(elide.lines), String(elide.saved)],
518    ],
519    [
520      ["compaction", "arrays", "saved"],
521      [session, String(compact.arrays), String(compact.saved)],
522    ],
523    [
524      ["config", "texts", "saved"],
525      [session, String(config.texts), String(config.saved)],
526    ],
527    [
528      ["html extractor", "pages", "saved"],
529      [session, String(extract.pages), String(extract.saved)],
530    ],
531    [
532      ["logs", "texts", "saved"],
533      [session, String(log.texts), String(log.saved)],
534    ],
535    [
536      ["search", "texts", "saved"],
537      [session, String(search.texts), String(search.saved)],
538    ],
539    [
540      ["diff", "texts", "saved"],
541      [session, String(diff.texts), String(diff.saved)],
542    ],
543    [
544      ["text crusher", "texts", "saved"],
545      [session, String(textcrush.texts), String(textcrush.saved)],
546    ],
547    [
548      ["relevance split", "texts", "saved"],
549      [session, String(split.texts), String(split.saved)],
550    ],
551  ];
552}
553
554/**
555 * One table as plain text: the label column padded on the right, the value columns right-aligned.
556 * @param {readonly (readonly string[])[]} rows
557 * @returns {string}
558 */
559export function tableText(rows) {
560  return rows.map((r) => r.map((s, i) => (i ? s.padStart(CELL_WIDTHS[i]) : s.padEnd(CELL_WIDTHS[i]))).join("")).join("\n");
561}
562
563// SmartCrusher: a port of headroom's dict-array lossy path (crates/headroom-core/src/transforms/smart_crusher).
564
565/**
566 * Two 32-bit lanes of a cyrb53-style hash over UTF-16 code units: the pure-JS stand-in for upstream's
567 * MD5 (simhash grams) and SHA-256 (CCR hash), since a mods module is not known to load node:crypto.
568 * @param {string} s
569 * @returns {[number, number]} two unsigned 32-bit lanes
570 */
571function hash64(s) {
572  let h1 = 0xdeadbeef;
573  let h2 = 0x41c6ce57;
574  for (let i = 0; i < s.length; i++) {
575    const ch = s.charCodeAt(i);
576    h1 = Math.imul(h1 ^ ch, 2654435761);
577    h2 = Math.imul(h2 ^ ch, 1597334677);
578  }
579  h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507);
580  h1 ^= Math.imul(h2 ^ (h2 >>> 13), 3266489909);
581  h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507);
582  h2 ^= Math.imul(h1 ^ (h1 >>> 13), 3266489909);
583  return [h1 >>> 0, h2 >>> 0];
584}
585
586/**
587 * @param {number} x a 32-bit integer
588 * @returns {number} its set bits
589 */
590function popcount(x) {
591  x -= (x >>> 1) & 0x55555555;
592  x = (x & 0x33333333) + ((x >>> 2) & 0x33333333);
593  return Math.imul((x + (x >>> 4)) & 0x0f0f0f0f, 0x01010101) >>> 24;
594}
595
596/**
597 * Upstream simhash: every lowercased 4-code-point gram (the whole string when it has 3 or fewer) votes ±1 per hash bit.
598 * @param {string} text
599 * @returns {[number, number]} the 64-bit fingerprint as two 32-bit halves
600 */
601function simhash(text) {
602  const cps = Array.from(text.toLowerCase());
603  const votes = new Array(64).fill(0);
604  const grams = cps.length <= 3 ? 1 : cps.length - 3;
605  for (let i = 0; i < grams; i++) {
606    const [a, b] = hash64(cps.slice(i, i + 4).join(""));
607    for (let j = 0; j < 32; j++) {
608      votes[j] += (a >>> j) & 1 ? 1 : -1;
609      votes[j + 32] += (b >>> j) & 1 ? 1 : -1;
610    }
611  }
612  let lo = 0;
613  let hi = 0;
614  for (let j = 0; j < 32; j++) {
615    if (votes[j] > 0) lo |= 1 << j;
616    if (votes[j + 32] > 0) hi |= 1 << j;
617  }
618  return [lo, hi];
619}
620
621/**
622 * Upstream count_unique_simhash: greedy clusters of fingerprints within Hamming distance 3.
623 * @param {readonly string[]} items
624 * @param {WorkBudget} [budget] charged 1 per fingerprint comparison
625 * @returns {number|undefined} undefined once the budget runs out
626 */
627function countUniqueSimhash(items, budget = { left: Infinity }) {
628  /** @type {[number, number][]} */
629  const reps = [];
630  for (const s of items) {
631    const [lo, hi] = simhash(s);
632    let dup = false;
633    for (const [a, b] of reps) {
634      if (--budget.left < 0) return undefined;
635      if (popcount(lo ^ a) + popcount(hi ^ b) <= 3) {
636        dup = true;
637        break;
638      }
639    }
640    if (!dup) reps.push([lo, hi]);
641  }
642  return reps.length;
643}
644
645/**
646 * Upstream compute_unique_bigram_curve: the running count of unique lowercased word bigrams
647 * (a lone word pairs with "", a spaceless CJK word yields character bigrams, an empty item counts once).
648 * @param {readonly string[]} items
649 * @returns {number[]}
650 */
651function bigramCurve(items) {
652  /** @type {Set<string>} */
653  const seen = new Set();
654  /** @param {readonly string[]} xs */
655  const pairs = (xs) => {
656    for (let j = 0; j < xs.length - 1; j++) seen.add(JSON.stringify([xs[j], xs[j + 1]]));
657  };
658  return items.map((item) => {
659    const words = item.toLowerCase().split(/\s+/).filter(Boolean);
660    if (words.length >= 2) pairs(words);
661    else if (words.length === 1) {
662      const cps = Array.from(words[0]);
663      const cjk = cps.some((c) => {
664        const x = c.codePointAt(0) ?? 0;
665        return CJK_RANGES.some(([lo, hi]) => x >= lo && x <= hi);
666      });
667      if (cps.length >= 2 && cjk) pairs(cps);
668      else seen.add(JSON.stringify([words[0], ""]));
669    } else seen.add(JSON.stringify(["", ""]));
670    return seen.size;
671  });
672}
673
674/**
675 * Upstream find_knee (Kneedle): 1 + the index farthest above the diagonal; undefined under 0.05 or below 3 points.
676 * @param {readonly number[]} curve
677 * @returns {number|undefined}
678 */
679function findKnee(curve) {
680  const n = curve.length;
681  if (n < 3) return undefined;
682  const yMin = curve[0];
683  const yRange = curve[n - 1] - yMin;
684  if (Math.abs(yRange) < Number.EPSILON) return 1;
685  let maxDiff = -1;
686  let knee = 0;
687  for (let i = 0; i < n; i++) {
688    const diff = (curve[i] - yMin) / yRange - i / (n - 1);
689    if (diff > maxDiff) {
690      maxDiff = diff;
691      knee = i;
692    }
693  }
694  return maxDiff < 0.05 ? undefined : knee + 1;
695}
696
697/**
698 * Upstream compute_optimal_k (bias 1; the crusher's min_k 3, max_k 15 by default): how many items to keep, from simhash
699 * diversity and the knee of the items' bigram coverage curve. As upstream, 8 or fewer items keep them all, even above maxK.
700 * @param {readonly string[]} itemStrings each item's text (a row's compact JSON, a log line, a search match)
701 * @param {number} [minK]
702 * @param {number} [maxK]
703 * @param {WorkBudget} [budget] charged 1 per simhash comparison; exhausted means maxK
704 * @returns {number}
705 */
706export function computeOptimalK(itemStrings, minK = MIN_K, maxK = MAX_ITEMS_AFTER_CRUSH, budget = undefined) {
707  const n = itemStrings.length;
708  if (n <= 8) return n;
709  const unique = countUniqueSimhash(itemStrings, budget);
710  // shortcut: an exhausted budget means many distinct fingerprints (high diversity), where upstream lands on maxK too; count them all if a caller ever needs the knee there.
711  if (unique === undefined) return maxK;
712  if (unique <= 3) return Math.min(Math.max(minK, unique), maxK);
713  const diversity = unique / n;
714  const floor = Math.max(minK, Math.floor(n * (0.3 + 0.7 * diversity)));
715  let knee = findKnee(bigramCurve(itemStrings));
716  if (knee === undefined) knee = floor;
717  else if (diversity > 0.7) knee = Math.max(knee, floor);
718  // shortcut: upstream's tier 3 (a zlib ratio check that can raise K by 20%) is skipped; add it once a node:zlib import is live-verified in a mods module.
719  return Math.max(minK, Math.min(Math.max(minK, knee), maxK));
720}
721
722/**
723 * Stores offloaded originals for headroom_retrieve: a re-put moves its hash to the newest position, and the
724 * oldest entries go while the store holds more than CCR_CAPACITY entries or CCR_MAX_CHARS characters. Never an entry
725 * of `entries` itself: the row that carries their markers is stored next, so a batch may leave the store over a cap until
726 * the next call with entries. Mutates `store`.
727 * shortcut: no idle TTL (upstream: 30 min); add one with a time argument from register.ts if memory becomes a concern.
728 * @param {Map<string, string>} store hash → original text (a crushed array's JSON, an elided block, a folded span), oldest first
729 * @param {readonly [string, string][]} entries
730 * @returns {void}
731 */
732export function storeOffloaded(store, entries) {
733  if (entries.length === 0) return; // nothing to add: skip the O(store) size pass, as most rows carry no entry for one of the two stores
734  for (const [hash, json] of entries) {
735    store.delete(hash);
736    store.set(hash, json);
737  }
738  let chars = 0;
739  for (const json of store.values()) chars += json.length;
740  const incoming = new Set(entries.map(([hash]) => hash));
741  for (const [hash, json] of store) {
742    // The batch is the newest tail of the store: stop there, so a marker this row just carried never names a hash it evicted itself.
743    if ((store.size <= CCR_CAPACITY && chars <= CCR_MAX_CHARS) || incoming.has(hash)) break;
744    store.delete(hash);
745    chars -= json.length;
746  }
747}
748
749/**
750 * The CCR key in what the model passed to headroom_retrieve: the bare hash, or one copied with its marker's `hash=` or
751 * `<<ccr:` prefix (the tool's description cites both forms) and, as a pointer or elider line ends in `]` and a CCR
752 * marker in `>>`, that closing bracket. Anything else is returned trimmed, as is.
753 * @param {unknown} hash
754 * @returns {string|undefined} undefined unless `hash` is a string
755 */
756export function retrieveKey(hash) {
757  return typeof hash === "string"
758    ? (hash
759        .trim()
760        .replace(/^(?:hash=|<<ccr:)/, "")
761        .split(/\s/)[0]
762        ?.replace(/[\]>]+$/, "") ?? "")
763    : undefined;
764}
765
766/**
767 * The crusher's query (upstream _extract_context_from_messages): newest first, the text of the last five
768 * user messages with text and each assistant tool call's input JSON. Deviation: upstream counts every user message,
769 * but a Claude Code tool result is a user message with empty text, so the real request would age out after five calls.
770 * Deviation: the tool-call inputs keep at most CRUSH_QUERY_INPUT_CHARS characters in all, newest first. A subagent has
771 * one user message, so the walk would otherwise stringify every input back to its start on each JSON result.
772 * @param {readonly QueryMessage[]} messages chronological, as the session.messages op returns them
773 * @returns {string}
774 */
775export function crushQuery(messages) {
776  /** @type {string[]} */
777  const parts = [];
778  let users = 0;
779  let budget = CRUSH_QUERY_INPUT_CHARS;
780  for (let i = messages.length - 1; i >= 0; i--) {
781    const m = messages[i];
782    if (m.role === "user") {
783      if (!m.text) continue;
784      parts.push(m.text);
785      if (++users >= 5) break;
786    } else
787      for (const u of m.toolUses) {
788        if (budget <= 0) break;
789        const input = JSON.stringify(u.input).slice(0, budget);
790        budget -= input.length;
791        parts.push(input);
792      }
793  }
794  return parts.join(" ");
795}
796
797/**
798 * @param {unknown} v
799 * @returns {v is Record<string, unknown>} a JSON object (not an array, not null)
800 */
801function isRecord(v) {
802  return typeof v === "object" && v !== null && !Array.isArray(v);
803}
804
805/**
806 * An own property only: a row without `constructor` must not read Object.prototype's.
807 * @param {Record<string, unknown>} o
808 * @param {string} k
809 * @returns {unknown}
810 */
811function own(o, k) {
812  return Object.hasOwn(o, k) ? o[k] : undefined;
813}
814
815/**
816 * Sorted-key compact JSON: the equality key upstream hashes (MD5 of sort_keys JSON) for dedup.
817 * @param {unknown} v
818 * @returns {string}
819 */
820function canonicalJson(v) {
821  if (Array.isArray(v)) return `[${v.map(canonicalJson).join(",")}]`;
822  if (isRecord(v))
823    return `{${Object.keys(v)
824      .sort()
825      .map((k) => `${JSON.stringify(k)}:${canonicalJson(v[k])}`)
826      .join(",")}}`;
827  return JSON.stringify(v);
828}
829
830/**
831 * The 12-hex CCR hash of an original array's compact JSON (upstream: a SHA-256 prefix).
832 * @param {string} s
833 * @returns {string}
834 */
835function contentHash(s) {
836  const [a, b] = hash64(s);
837  return (a.toString(16).padStart(8, "0") + b.toString(16).padStart(8, "0")).slice(0, 12);
838}
839
840/**
841 * Python str() as upstream's analyzer counts distinct values: None/True/False, bare strings, JSON for containers.
842 * @param {unknown} v
843 * @returns {string}
844 */
845function pyStr(v) {
846  if (v === null) return "None";
847  if (typeof v === "boolean") return v ? "True" : "False";
848  return typeof v === "string" ? v : typeof v === "number" ? String(v) : JSON.stringify(v);
849}
850
851/**
852 * Python repr as upstream's anchors.rs renders a row for query-anchor matching: single-quoted strings, ", " and ": ".
853 * @param {unknown} v
854 * @returns {string}
855 */
856function pythonRepr(v) {
857  if (v === null) return "None";
858  if (typeof v === "boolean") return v ? "True" : "False";
859  if (typeof v === "string") return `'${v}'`;
860  if (Array.isArray(v)) return `[${v.map(pythonRepr).join(", ")}]`;
861  if (isRecord(v))
862    return `{${Object.keys(v)
863      .map((k) => `'${k}': ${pythonRepr(v[k])}`)
864      .join(", ")}}`;
865  return String(v);
866}
867
868/**
869 * Upstream stats_math::mean: undefined when empty or not finite.
870 * @param {readonly number[]} xs
871 * @returns {number|undefined}
872 */
873function mean(xs) {
874  if (!xs.length) return undefined;
875  let sum = 0;
876  for (const x of xs) sum += x;
877  const m = sum / xs.length;
878  return Number.isFinite(m) ? m : undefined;
879}
880
881/**
882 * Upstream sample_variance (n − 1): undefined below two values or when not finite.
883 * @param {readonly number[]} xs
884 * @returns {number|undefined}
885 */
886function sampleVariance(xs) {
887  const m = xs.length < 2 ? undefined : mean(xs);
888  if (m === undefined) return undefined;
889  let sq = 0;
890  for (const x of xs) sq += (x - m) * (x - m);
891  const v = sq / (xs.length - 1);
892  return Number.isFinite(v) ? v : undefined;
893}
894
895/**
896 * Upstream detect_change_points (window 5): where the means of the 5 values before and after differ by more
897 * than 2σ, each kept point more than 5 past the previous one.
898 * @param {readonly number[]} xs
899 * @returns {number[]} indices into `xs`
900 */
901function changePoints(xs) {
902  const w = 5;
903  const v = xs.length < 2 * w ? undefined : sampleVariance(xs);
904  if (v === undefined || !(Math.sqrt(v) > 0)) return [];
905  const threshold = VARIANCE_THRESHOLD * Math.sqrt(v);
906  /** @type {number[]} */
907  const out = [];
908  for (let i = w; i < xs.length - w; i++) {
909    const shift = Math.abs((mean(xs.slice(i, i + w)) ?? 0) - (mean(xs.slice(i - w, i)) ?? 0));
910    if (shift > threshold && (!out.length || i - out[out.length - 1] > w)) out.push(i);
911  }
912  return out;
913}
914
915/**
916 * Upstream analyze_field: type from the first non-null value, distinct values over all rows (a missing key is
917 * null), numeric min/max/mean/variance/change points, and a string field's mean length in code points.
918 * @param {string} name
919 * @param {readonly Record<string, unknown>[]} items
920 * @returns {FieldStats}
921 */
922function analyzeField(name, items) {
923  const values = items.map((o) => own(o, name) ?? null);
924  const nonNull = values.filter((v) => v !== null);
925  /** @type {FieldStats} */
926  const f = { name, type: "null", unique: 0, ratio: 0, changePoints: [] };
927  if (!nonNull.length) return f;
928  const first = nonNull[0];
929  f.type = typeof first === "boolean" ? "boolean" : typeof first === "number" ? "numeric" : typeof first === "string" ? "string" : Array.isArray(first) ? "array" : "object";
930  f.unique = new Set(values.map(pyStr)).size;
931  f.ratio = f.unique / values.length;
932  if (f.type === "numeric") {
933    /** @type {number[]} */
934    const nums = [];
935    /** @type {number[]} */
936    const rows = [];
937    values.forEach((v, i) => {
938      if (typeof v === "number" && Number.isFinite(v)) {
939        nums.push(v);
940        rows.push(i);
941      }
942    });
943    let min = Infinity;
944    let max = -Infinity;
945    for (const x of nums) {
946      min = Math.min(min, x);
947      max = Math.max(max, x);
948    }
949    const m = mean(nums);
950    const variance = nums.length > 1 ? sampleVariance(nums) : 0;
951    // Upstream resets the whole numeric block when any statistic is not finite. Change points are mapped from
952    // `nums` (nulls and non-numbers skipped) back to row indices, which the planners index by.
953    if (m !== undefined && variance !== undefined && Number.isFinite(min) && Number.isFinite(max))
954      Object.assign(f, { min, max, mean: m, variance, changePoints: changePoints(nums).map((k) => rows[k]) });
955    else f.variance = 0;
956  } else if (f.type === "string") {
957    f.avgLen = mean(/** @type {string[]} */ (nonNull.filter((v) => typeof v === "string")).map((s) => Array.from(s).length));
958  }
959  return f;
960}
961
962/**
963 * Upstream detect_sequential_pattern with check_order (both callers pass true): at least 5 numbers (one a real
964 * JSON number, plain-integer strings count too) whose sorted gaps average 0.5..2 with over 80% in that range,
965 * and over 70% of neighbours ascending in the original order.
966 * @param {readonly unknown[]} values
967 * @returns {boolean}
968 */
969function isSequential(values) {
970  /** @type {number[]} */
971  const nums = [];
972  let real = false;
973  for (const v of values) {
974    if (typeof v === "number") {
975      nums.push(v);
976      real = true;
977    } else if (typeof v === "string" && PY_INT_RE.test(v)) nums.push(Number(v));
978  }
979  if (nums.length < 5 || !real) return false;
980  const sorted = [...nums].sort((a, b) => a - b);
981  const gaps = sorted.slice(1).map((x, i) => x - sorted[i]);
982  const avg = gaps.reduce((a, b) => a + b, 0) / gaps.length;
983  if (!(avg >= 0.5 && avg <= 2)) return false;
984  if (!(gaps.filter((d) => d >= 0.5 && d <= 2).length / gaps.length > 0.8)) return false;
985  return nums.slice(1).filter((x, i) => nums[i] <= x).length / (nums.length - 1) > 0.7;
986}
987
988/**
989 * Upstream calculate_string_entropy: Shannon entropy over code points, normalized to 0..1.
990 * @param {string} s
991 * @returns {number}
992 */
993function stringEntropy(s) {
994  const cps = Array.from(s);
995  if (cps.length < 2) return 0;
996  /** @type {Map<string, number>} */
997  const freq = new Map();
998  for (const c of cps) freq.set(c, (freq.get(c) ?? 0) + 1);
999  let e = 0;
1000  for (const n of freq.values()) e -= (n / cps.length) * Math.log2(n / cps.length);
1001  const maxE = Math.log2(Math.min(freq.size, cps.length));
1002  return maxE > 0 ? e / maxE : 0;
1003}
1004
1005/**
1006 * Upstream detect_id_field_statistically: the confidence that a field is a row id, 0 when it is not.
1007 * @param {FieldStats} f
1008 * @param {readonly unknown[]} values the field per row, a missing key as null
1009 * @returns {number}
1010 */
1011function idConfidence(f, values) {
1012  if (f.ratio < 0.9) return 0;
1013  if (f.type === "string") {
1014    const sample = /** @type {string[]} */ (values.slice(0, 20).filter((v) => typeof v === "string"));
1015    if (sample.length) {
1016      if (sample.filter((s) => UUID_RE.test(s)).length / sample.length > 0.8) return 0.95;
1017      if (sample.reduce((a, s) => a + stringEntropy(s), 0) / sample.length > 0.7 && f.ratio > 0.95) return 0.8;
1018    }
1019  }
1020  if (f.type === "numeric") {
1021    if (isSequential(values) && f.ratio > 0.95) return 0.9;
1022    if (f.min !== undefined && f.max !== undefined && f.max - f.min > 0 && f.ratio > 0.95) return 0.85;
1023  }
1024  return f.ratio > 0.98 ? 0.7 : 0;
1025}
1026
1027/**
1028 * Upstream detect_score_field_statistically: the confidence (capped at 0.95) that a bounded, non-sequential
1029 * numeric field ranks the rows, 0 when it is not a score (below 0.4).
1030 * @param {FieldStats} f
1031 * @param {readonly Record<string, unknown>[]} items
1032 * @returns {number}
1033 */
1034function scoreConfidence(f, items) {
1035  if (f.type !== "numeric" || f.min === undefined || f.max === undefined) return 0;
1036  const { min, max } = f;
1037  let c;
1038  if (min >= 0 && min <= 1 && max >= 0 && max <= 1) c = 0.4;
1039  else if (min >= 0 && min <= 10 && max >= 0 && max <= 10) c = 0.3;
1040  else if (min >= 0 && min <= 100 && max >= 0 && max <= 100) c = 0.25;
1041  else if (min >= -1 && max <= 1) c = 0.35;
1042  else return 0;
1043  if (
1044    isSequential(
1045      items
1046        .slice(0, 50)
1047        .filter((o) => Object.hasOwn(o, f.name))
1048        .map((o) => o[f.name]),
1049    )
1050  )
1051    return 0;
1052  const nums = /** @type {number[]} */ (items.map((o) => own(o, f.name)).filter((v) => typeof v === "number" && Number.isFinite(v)));
1053  if (nums.length >= 5 && nums.slice(1).filter((x, i) => nums[i] >= x).length / (nums.length - 1) > 0.7) c += 0.3;
1054  const first = nums.slice(0, 20);
1055  if (first.length && first.filter((x) => x !== Math.trunc(x)).length > first.length * 0.3) c += 0.1;
1056  return c >= 0.4 ? Math.min(c, 0.95) : 0;
1057}
1058
1059/**
1060 * Upstream detect_temporal_field: a string field mostly ISO dates in its first 10 rows, or a numeric field whose
1061 * minimum looks like epoch seconds or milliseconds.
1062 * @param {readonly FieldStats[]} fields
1063 * @param {readonly Record<string, unknown>[]} items
1064 * @returns {boolean}
1065 */
1066function hasTemporalField(fields, items) {
1067  for (const f of fields) {
1068    if (f.type === "string") {
1069      const sample = /** @type {string[]} */ (
1070        items
1071          .slice(0, 10)
1072          .map((o) => own(o, f.name))
1073          .filter((v) => typeof v === "string")
1074      );
1075      if (sample.length && sample.filter((s) => ISO_DATETIME_RE.test(s) || ISO_DATE_RE.test(s)).length / sample.length > 0.5) return true;
1076    } else if (f.type === "numeric" && f.min !== undefined && ((f.min >= 1e9 && f.min <= 2e9) || (f.min >= 1e12 && f.min <= 2e12))) return true;
1077  }
1078  return false;
1079}
1080
1081/**
1082 * Upstream detect_pattern: time_series, logs, search_results or generic.
1083 * @param {readonly FieldStats[]} fields
1084 * @param {readonly Record<string, unknown>[]} items
1085 * @returns {'time_series'|'logs'|'search_results'|'generic'}
1086 */
1087function detectPattern(fields, items) {
1088  if (fields.some((f) => f.type === "numeric" && (f.variance ?? 0) > 0) && hasTemporalField(fields, items)) return "time_series";
1089  let message = false;
1090  let level = false;
1091  for (const f of fields) {
1092    if (f.type !== "string") continue;
1093    if (f.ratio > 0.5 && (f.avgLen ?? 0) > 20) message = true;
1094    else if (f.ratio < 0.1 && f.unique >= 2 && f.unique <= 10) level = true;
1095  }
1096  if (message && level) return "logs";
1097  return fields.some((f) => scoreConfidence(f, items) >= 0.5) ? "search_results" : "generic";
1098}
1099
1100/**
1101 * Upstream detect_rare_status_values for one common field: with 2..50 distinct non-null values, the fewest most
1102 * frequent values covering 80% of the rows that hold the key; if at most 5 do, the rows holding any other value.
1103 * @param {readonly Record<string, unknown>[]} items
1104 * @param {string} name
1105 * @returns {number[]}
1106 */
1107function rareStatusRows(items, name) {
1108  /** @param {unknown} v */
1109  const key = (v) => (v === null ? "__none__" : typeof v === "string" ? v : JSON.stringify(v));
1110  const values = items.filter((o) => Object.hasOwn(o, name)).map((o) => o[name]);
1111  const distinct = new Set(values.filter((v) => v !== null).map(key)).size;
1112  if (distinct < 2 || distinct > 50) return [];
1113  /** @type {Map<string, number>} */
1114  const counts = new Map();
1115  for (const v of values) counts.set(key(v), (counts.get(key(v)) ?? 0) + 1);
1116  const ranked = [...counts].sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));
1117  const need = Math.ceil(values.length * 0.8);
1118  const top = new Set();
1119  let covered = 0;
1120  for (const [v, c] of ranked) {
1121    covered += c;
1122    top.add(v);
1123    if (covered >= need) break;
1124  }
1125  if (top.size > 5) return [];
1126  return items.flatMap((o, i) => (Object.hasOwn(o, name) && !top.has(key(o[name])) ? [i] : []));
1127}
1128
1129/**
1130 * Upstream detect_structural_outliers (5+ rows): rows holding a key present in under 20% of the rows, and rows
1131 * with a rare value in a key present in at least 80% of them.
1132 * @param {readonly Record<string, unknown>[]} items
1133 * @returns {Set<number>}
1134 */
1135function structuralOutliers(items) {
1136  const n = items.length;
1137  /** @type {Set<number>} */
1138  const out = new Set();
1139  if (n < 5) return out;
1140  /** @type {Map<string, number>} */
1141  const counts = new Map();
1142  for (const o of items) for (const k of Object.keys(o)) counts.set(k, (counts.get(k) ?? 0) + 1);
1143  const rare = new Set([...counts].filter(([, c]) => c < n * 0.2).map(([k]) => k));
1144  items.forEach((o, i) => {
1145    if (Object.keys(o).some((k) => rare.has(k))) out.add(i);
1146  });
1147  const common = [...counts].filter(([, c]) => c >= n * 0.8).map(([k]) => k);
1148  for (const k of common.sort()) for (const i of rareStatusRows(items, k)) out.add(i);
1149  return out;
1150}
1151
1152/**
1153 * Upstream numeric anomalies: rows more than 2σ from a numeric field's mean (fields with variance > 0).
1154 * @param {readonly FieldStats[]} fields
1155 * @param {readonly Record<string, unknown>[]} items
1156 * @returns {Set<number>}
1157 */
1158function anomalyRows(fields, items) {
1159  /** @type {Set<number>} */
1160  const out = new Set();
1161  for (const f of fields) {
1162    const m = f.mean;
1163    if (f.type !== "numeric" || m === undefined || !((f.variance ?? 0) > 0)) continue;
1164    const threshold = VARIANCE_THRESHOLD * Math.sqrt(f.variance ?? 0);
1165    items.forEach((o, i) => {
1166      const x = own(o, f.name);
1167      if (typeof x === "number" && Math.abs(x - m) > threshold) out.add(i);
1168    });
1169  }
1170  return out;
1171}
1172
1173/**
1174 * Upstream analyze_array: field stats, the crushability gate (analyze_crushability) and the strategy
1175 * (select_strategy). Errors, structural outliers and anomalies are kept for the planners, which recompute the same sets upstream.
1176 * @param {readonly Record<string, unknown>[]} items
1177 * @param {readonly string[]} strings each row's compact JSON
1178 * @returns {Analysis}
1179 */
1180function analyzeArray(items, strings) {
1181  const fields = [...new Set(items.flatMap((o) => Object.keys(o)))].sort().map((k) => analyzeField(k, items));
1182  const pattern = detectPattern(fields, items);
1183  const errors = strings.flatMap((s, i) => {
1184    const l = s.toLowerCase();
1185    return ERROR_KEYWORDS.some((k) => l.includes(k)) ? [i] : [];
1186  });
1187  const outliers = structuralOutliers(items);
1188  const anomalies = anomalyRows(fields, items);
1189  const hasChangePoints = fields.some((f) => f.changePoints.length > 0);
1190  // The best id field (strict >), whatever its confidence; has_id needs 0.7.
1191  /** @type {string|undefined} */
1192  let idName;
1193  let idRatio = 0;
1194  let idConf = 0;
1195  for (const f of fields) {
1196    const c = idConfidence(
1197      f,
1198      items.map((o) => own(o, f.name) ?? null),
1199    );
1200    if (c > idConf) [idName, idRatio, idConf] = [f.name, f.ratio, c];