@sriinnu/fiche 0.18.0-bootstrap.0 → 0.19.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +134 -0
- package/LICENSE +22 -0
- package/NOTICE +13 -0
- package/PRIVACY.md +41 -0
- package/README.md +289 -0
- package/SECURITY.md +53 -0
- package/assets/JETBRAINS_MONO_LICENSE.txt +89 -0
- package/assets/SPLEEN_LICENSE.txt +24 -0
- package/assets/UNIFONT_LICENSE.txt +476 -0
- package/assets/fiche-logo-dark.svg +61 -0
- package/assets/fiche-logo-light.svg +61 -0
- package/assets/fiche-logo.svg +71 -0
- package/assets/fiche-mark.svg +48 -0
- package/bin/cli.js +7 -0
- package/bin/mcp.js +8 -0
- package/dist/calibrate.d.ts +30 -0
- package/dist/calibrate.js +588 -0
- package/dist/core/anthropic-vision.d.ts +28 -0
- package/dist/core/anthropic-vision.js +34 -0
- package/dist/core/applicability.d.ts +63 -0
- package/dist/core/applicability.js +151 -0
- package/dist/core/atlas-gray-jbmono10.d.ts +26 -0
- package/dist/core/atlas-gray-jbmono10.js +64 -0
- package/dist/core/atlas-gray-jbmono12.d.ts +26 -0
- package/dist/core/atlas-gray-jbmono12.js +64 -0
- package/dist/core/atlas-gray-jbmono14.d.ts +26 -0
- package/dist/core/atlas-gray-jbmono14.js +64 -0
- package/dist/core/atlas-gray.d.ts +26 -0
- package/dist/core/atlas-gray.js +64 -0
- package/dist/core/atlas-jbmono10.d.ts +34 -0
- package/dist/core/atlas-jbmono10.js +71 -0
- package/dist/core/atlas-jbmono12.d.ts +34 -0
- package/dist/core/atlas-jbmono12.js +71 -0
- package/dist/core/atlas-jbmono14.d.ts +34 -0
- package/dist/core/atlas-jbmono14.js +71 -0
- package/dist/core/atlas.d.ts +34 -0
- package/dist/core/atlas.js +71 -0
- package/dist/core/baseline.d.ts +121 -0
- package/dist/core/baseline.js +200 -0
- package/dist/core/calibration.d.ts +86 -0
- package/dist/core/calibration.js +547 -0
- package/dist/core/casi-delta.d.ts +63 -0
- package/dist/core/casi-delta.js +1271 -0
- package/dist/core/claude-model-profiles.d.ts +53 -0
- package/dist/core/claude-model-profiles.js +160 -0
- package/dist/core/client-tool-round.d.ts +31 -0
- package/dist/core/client-tool-round.js +58 -0
- package/dist/core/codex-cache.d.ts +20 -0
- package/dist/core/codex-cache.js +59 -0
- package/dist/core/context-mmu.d.ts +350 -0
- package/dist/core/context-mmu.js +3028 -0
- package/dist/core/cpt-fit.d.ts +70 -0
- package/dist/core/cpt-fit.js +197 -0
- package/dist/core/env.d.ts +8 -0
- package/dist/core/env.js +15 -0
- package/dist/core/export.d.ts +127 -0
- package/dist/core/export.js +385 -0
- package/dist/core/factsheet.d.ts +77 -0
- package/dist/core/factsheet.js +494 -0
- package/dist/core/gemini-model-profiles.d.ts +20 -0
- package/dist/core/gemini-model-profiles.js +134 -0
- package/dist/core/google.d.ts +76 -0
- package/dist/core/google.js +1380 -0
- package/dist/core/gpt-model-profiles.d.ts +218 -0
- package/dist/core/gpt-model-profiles.js +570 -0
- package/dist/core/gpt-tokens.d.ts +14 -0
- package/dist/core/gpt-tokens.js +165 -0
- package/dist/core/history.d.ts +197 -0
- package/dist/core/history.js +1003 -0
- package/dist/core/index.d.ts +16 -0
- package/dist/core/index.js +16 -0
- package/dist/core/library.d.ts +80 -0
- package/dist/core/library.js +131 -0
- package/dist/core/measurement.d.ts +34 -0
- package/dist/core/measurement.js +280 -0
- package/dist/core/messages-chat-bridge.d.ts +23 -0
- package/dist/core/messages-chat-bridge.js +747 -0
- package/dist/core/messages-responses-bridge.d.ts +11 -0
- package/dist/core/messages-responses-bridge.js +893 -0
- package/dist/core/openai-history.d.ts +184 -0
- package/dist/core/openai-history.js +1279 -0
- package/dist/core/openai-savings.d.ts +57 -0
- package/dist/core/openai-savings.js +116 -0
- package/dist/core/openai.d.ts +68 -0
- package/dist/core/openai.js +2523 -0
- package/dist/core/pin.d.ts +199 -0
- package/dist/core/pin.js +1353 -0
- package/dist/core/png.d.ts +14 -0
- package/dist/core/png.js +188 -0
- package/dist/core/prefix-tape.d.ts +102 -0
- package/dist/core/prefix-tape.js +315 -0
- package/dist/core/price-id.d.ts +10 -0
- package/dist/core/price-id.js +26 -0
- package/dist/core/prices.generated.d.ts +36 -0
- package/dist/core/prices.generated.js +369 -0
- package/dist/core/pricing.d.ts +134 -0
- package/dist/core/pricing.js +335 -0
- package/dist/core/profile-base.d.ts +30 -0
- package/dist/core/profile-base.js +67 -0
- package/dist/core/provider-router.d.ts +51 -0
- package/dist/core/provider-router.js +121 -0
- package/dist/core/proxy.d.ts +252 -0
- package/dist/core/proxy.js +2929 -0
- package/dist/core/reader-tier.d.ts +24 -0
- package/dist/core/reader-tier.js +118 -0
- package/dist/core/render.d.ts +280 -0
- package/dist/core/render.js +1302 -0
- package/dist/core/request-guard.d.ts +31 -0
- package/dist/core/request-guard.js +126 -0
- package/dist/core/request-transform.d.ts +43 -0
- package/dist/core/request-transform.js +173 -0
- package/dist/core/schema-compiler.d.ts +64 -0
- package/dist/core/schema-compiler.js +1696 -0
- package/dist/core/schema-strip.d.ts +29 -0
- package/dist/core/schema-strip.js +173 -0
- package/dist/core/session-state.d.ts +219 -0
- package/dist/core/session-state.js +929 -0
- package/dist/core/stage-plugins.d.ts +45 -0
- package/dist/core/stage-plugins.js +205 -0
- package/dist/core/text-history.d.ts +74 -0
- package/dist/core/text-history.js +612 -0
- package/dist/core/text-hygiene.d.ts +160 -0
- package/dist/core/text-hygiene.js +2259 -0
- package/dist/core/toon.d.ts +29 -0
- package/dist/core/toon.js +425 -0
- package/dist/core/tracker.d.ts +223 -0
- package/dist/core/tracker.js +290 -0
- package/dist/core/transform.d.ts +589 -0
- package/dist/core/transform.js +3153 -0
- package/dist/core/types.d.ts +87 -0
- package/dist/core/types.js +8 -0
- package/dist/core/upstream-hosts.d.ts +127 -0
- package/dist/core/upstream-hosts.js +398 -0
- package/dist/core/vision-cost.d.ts +63 -0
- package/dist/core/vision-cost.js +137 -0
- package/dist/dashboard/fragments.d.ts +87 -0
- package/dist/dashboard/fragments.js +1515 -0
- package/dist/dashboard/types.d.ts +217 -0
- package/dist/dashboard/types.js +3 -0
- package/dist/dashboard/vendor.d.ts +3 -0
- package/dist/dashboard/vendor.js +6 -0
- package/dist/dashboard.d.ts +372 -0
- package/dist/dashboard.js +2731 -0
- package/dist/export-collect.d.ts +36 -0
- package/dist/export-collect.js +59 -0
- package/dist/file-tracker.d.ts +42 -0
- package/dist/file-tracker.js +234 -0
- package/dist/kosha-sync.d.ts +74 -0
- package/dist/kosha-sync.js +272 -0
- package/dist/launchd-socket.d.ts +22 -0
- package/dist/launchd-socket.js +210 -0
- package/dist/mcp/cli.d.ts +2 -0
- package/dist/mcp/cli.js +55 -0
- package/dist/mcp/server.d.ts +48 -0
- package/dist/mcp/server.js +987 -0
- package/dist/mmu-store.d.ts +31 -0
- package/dist/mmu-store.js +179 -0
- package/dist/node-fetch.d.ts +22 -0
- package/dist/node-fetch.js +489 -0
- package/dist/node.d.ts +9 -0
- package/dist/node.js +244396 -0
- package/dist/request-decoding.d.ts +30 -0
- package/dist/request-decoding.js +85 -0
- package/dist/sessions.d.ts +179 -0
- package/dist/sessions.js +837 -0
- package/dist/stats.d.ts +114 -0
- package/dist/stats.js +439 -0
- package/dist/turn-report.d.ts +65 -0
- package/dist/turn-report.js +724 -0
- package/dist/warp/app-launch.d.ts +26 -0
- package/dist/warp/app-launch.js +155 -0
- package/dist/warp/ca.d.ts +74 -0
- package/dist/warp/ca.js +416 -0
- package/dist/warp/connect.d.ts +42 -0
- package/dist/warp/connect.js +686 -0
- package/dist/warp/der.d.ts +57 -0
- package/dist/warp/der.js +151 -0
- package/dist/warp/index.d.ts +79 -0
- package/dist/warp/index.js +650 -0
- package/dist/warp/resolve.d.ts +12 -0
- package/dist/warp/resolve.js +49 -0
- package/dist/warp/route.d.ts +71 -0
- package/dist/warp/route.js +134 -0
- package/dist/worker.d.ts +71 -0
- package/dist/worker.js +174 -0
- package/docs/SECURITY_MODEL.md +84 -0
- package/package.json +115 -3
- package/plugins/fiche-companion/README.md +42 -0
- package/plugins/fiche-companion/assets/logo.svg +48 -0
- package/plugins/fiche-companion/hooks.json +11 -0
- package/plugins/fiche-companion/mcp_config.json +8 -0
- package/plugins/fiche-companion/plugin.json +18 -0
- package/plugins/fiche-companion/scripts/claude-statusline.mjs +35 -0
- package/plugins/fiche-companion/scripts/post-invocation.mjs +122 -0
- package/plugins/fiche-companion/scripts/resolve-turn-report.mjs +132 -0
- package/plugins/fiche-companion/skills/fiche/SKILL.md +61 -0
|
@@ -0,0 +1,612 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ACDC: Append-Only Frozen-Epoch Extractive History Compactor for Text-Only Models.
|
|
3
|
+
*
|
|
4
|
+
* Grounded in:
|
|
5
|
+
* - "Context Has a Price" (Yang et al., Nov 2026) & CAPC (July 2026):
|
|
6
|
+
* mutating recent/live turns causes re-search loops or breaks prefix caches.
|
|
7
|
+
* - "The Complexity Trap" (2025/2026) & SWE-Pruner (Jan 2026): deterministic
|
|
8
|
+
* structural skeleton + outcome extraction over *aged* completed epochs
|
|
9
|
+
* matches heavy LLM summarization at zero inference cost.
|
|
10
|
+
*
|
|
11
|
+
* Strictly groups aged blocks behind `keepTailMessages` into fixed frozen
|
|
12
|
+
* epochs (`>= epochTokenTarget` tokens). Trailing unsealed blocks are untouched
|
|
13
|
+
* until full, so sealed epochs stay bit-identical across subsequent turns.
|
|
14
|
+
* Every epoch passes a kosha cache-payback or cliff-avoidance gate.
|
|
15
|
+
*
|
|
16
|
+
* Workers-safe: zero `node:` imports.
|
|
17
|
+
*/
|
|
18
|
+
import { computeHorizonPaybackLimit, fnv64Hex } from './context-mmu.js';
|
|
19
|
+
import { factSheetText } from './factsheet.js';
|
|
20
|
+
import { gptTokenCount, hasLongUnbrokenBpeChunk } from './gpt-tokens.js';
|
|
21
|
+
import { resetGlobalPrefixTape } from './prefix-tape.js';
|
|
22
|
+
import { evaluateCliffAvoidance, isAutoCacheOpenAIModel, priceMode, resolvePriceRates } from './pricing.js';
|
|
23
|
+
import { hasSealedEpochKey, recordSealedEpochKey } from './session-state.js';
|
|
24
|
+
const TOKEN_EXACT_LIMIT = 32_000;
|
|
25
|
+
const DIGEST_CACHE_MAX_CHARS = 8 * 1024 * 1024;
|
|
26
|
+
const digestCache = new Map();
|
|
27
|
+
let digestCacheChars = 0;
|
|
28
|
+
const LINE_NUM_PREFIX_RE = /^(\s*\d{1,7}(?:\t|→|\s*[|\u2502](?:\s|$)))/;
|
|
29
|
+
const DIFF_HEADER_RE = /^(?:diff --git |@@ -\d+(?:,\d+)? \+\d+(?:,\d+)? @@|--- [^\n]+|\+\+\+ [^\n]+)/;
|
|
30
|
+
const LOG_CRITICAL_RE = /\b(?:error|err|warn|warning|fail|failed|failure|fatal|panic|exception|traceback|assertion|assert|denied|forbidden|timeout|timed out|refused|oom|killed|segfault|abort|aborted|passed|skipped|summary|exit[_ ]?code(?:[=:\s]+[1-9]\d*)?|returned [1-9]\d*|[A-Za-z_]\w*(?:Error|Exception|Fault|Failure)|ECONNREFUSED|ENOENT|ETIMEDOUT|EACCES|EPERM|EADDRINUSE|EPIPE|EISDIR|ENOSPC)\b|\b(?:status[=:\s]+|HTTP\/\d(?:\.\d)?["'\s]+)[45]\d\d\b|(?:^\s*(?:at\s+\S+\s*\(|Caused by:|File "|Traceback \(most recent call last\)))/i;
|
|
31
|
+
const CODE_DECL_RE = /^\s*(?:export\s+(?:default\s+)?(?:async\s+)?|pub(?:\([^)]*\))?\s+(?:async\s+)?|async\s+|static\s+|private\s+|protected\s+|public\s+)?(?:function|class|interface|type|enum|struct|trait|impl|fn|func|def|mod|namespace|module)\b|^\s*(?:export\s+)?(?:const|let|var)\s+\w+\s*=\s*(?:async\s+)?(?:\([^)]*\)|\w+)\s*=>|^\s*(?:import|from\s+\S+\s+import|package|use\s+|#include)\b/;
|
|
32
|
+
const TOKEN_CACHE_MAX = 2048;
|
|
33
|
+
const tokenCountCache = new Map();
|
|
34
|
+
function countTokensExactCached(s) {
|
|
35
|
+
const key = `${s.length}:${fnv64Hex(s)}`;
|
|
36
|
+
const hit = tokenCountCache.get(key);
|
|
37
|
+
if (hit !== undefined)
|
|
38
|
+
return hit;
|
|
39
|
+
const tok = gptTokenCount(s);
|
|
40
|
+
if (tokenCountCache.size >= TOKEN_CACHE_MAX) {
|
|
41
|
+
const oldest = tokenCountCache.keys().next().value;
|
|
42
|
+
if (oldest !== undefined)
|
|
43
|
+
tokenCountCache.delete(oldest);
|
|
44
|
+
}
|
|
45
|
+
tokenCountCache.set(key, tok);
|
|
46
|
+
return tok;
|
|
47
|
+
}
|
|
48
|
+
function countTokens(s) {
|
|
49
|
+
if (s.length <= TOKEN_EXACT_LIMIT && !hasLongUnbrokenBpeChunk(s))
|
|
50
|
+
return countTokensExactCached(s);
|
|
51
|
+
return Math.ceil(s.length / 3.5);
|
|
52
|
+
}
|
|
53
|
+
function estimateTokenPair(before, after) {
|
|
54
|
+
if (before.length <= TOKEN_EXACT_LIMIT &&
|
|
55
|
+
after.length <= TOKEN_EXACT_LIMIT &&
|
|
56
|
+
!hasLongUnbrokenBpeChunk(before) &&
|
|
57
|
+
!hasLongUnbrokenBpeChunk(after)) {
|
|
58
|
+
return [countTokensExactCached(before), countTokensExactCached(after)];
|
|
59
|
+
}
|
|
60
|
+
return [Math.ceil(before.length / 3.5), Math.ceil(after.length / 3.5)];
|
|
61
|
+
}
|
|
62
|
+
function isWsChar(c) {
|
|
63
|
+
return c === 32 || (c >= 9 && c <= 13) || c === 160;
|
|
64
|
+
}
|
|
65
|
+
function firstNonWsIndex(text, from = 0) {
|
|
66
|
+
for (let i = from; i < text.length; i++) {
|
|
67
|
+
if (!isWsChar(text.charCodeAt(i)))
|
|
68
|
+
return i;
|
|
69
|
+
}
|
|
70
|
+
return -1;
|
|
71
|
+
}
|
|
72
|
+
function lastNonWsCode(text) {
|
|
73
|
+
for (let i = text.length - 1; i >= 0; i--) {
|
|
74
|
+
const c = text.charCodeAt(i);
|
|
75
|
+
if (!isWsChar(c))
|
|
76
|
+
return c;
|
|
77
|
+
}
|
|
78
|
+
return -1;
|
|
79
|
+
}
|
|
80
|
+
const STICKY_EPOCH_MAX = 1024;
|
|
81
|
+
const stickySealedEpochs = new Set();
|
|
82
|
+
const stickyCliffEpochs = new Map();
|
|
83
|
+
/** Test seam: drop in-memory sticky epoch caches (e.g. to verify restart recovery via session-state). */
|
|
84
|
+
export function resetTextEpochStickyState() {
|
|
85
|
+
stickySealedEpochs.clear();
|
|
86
|
+
stickyCliffEpochs.clear();
|
|
87
|
+
tokenCountCache.clear();
|
|
88
|
+
resetGlobalPrefixTape();
|
|
89
|
+
}
|
|
90
|
+
const LOG_BRACKET_TS_RE = /^\[\s*(?:\d{4}-|\d{2}:)/;
|
|
91
|
+
/** Distinguish true JSON objects/arrays from log lines starting with `[2026-...]` or `[INFO]`. */
|
|
92
|
+
function looksLikeJsonPayload(text) {
|
|
93
|
+
const firstIdx = firstNonWsIndex(text);
|
|
94
|
+
if (firstIdx < 0)
|
|
95
|
+
return false;
|
|
96
|
+
const firstCh = text.charCodeAt(firstIdx);
|
|
97
|
+
const lastCh = lastNonWsCode(text);
|
|
98
|
+
if (firstCh === 123 && lastCh === 125) {
|
|
99
|
+
const secondIdx = firstNonWsIndex(text, firstIdx + 1);
|
|
100
|
+
if (secondIdx < 0)
|
|
101
|
+
return false;
|
|
102
|
+
const ch = text.charCodeAt(secondIdx);
|
|
103
|
+
return ch === 34 || ch === 125;
|
|
104
|
+
}
|
|
105
|
+
if (firstCh === 91 && lastCh === 93) {
|
|
106
|
+
if (LOG_BRACKET_TS_RE.test(text.slice(firstIdx, firstIdx + 16)))
|
|
107
|
+
return false;
|
|
108
|
+
const secondIdx = firstNonWsIndex(text, firstIdx + 1);
|
|
109
|
+
if (secondIdx < 0)
|
|
110
|
+
return false;
|
|
111
|
+
const ch = text.charCodeAt(secondIdx);
|
|
112
|
+
if (ch === 123 || ch === 91 || ch === 34 || ch === 93)
|
|
113
|
+
return true;
|
|
114
|
+
const head = text.slice(secondIdx, secondIdx + 128);
|
|
115
|
+
if (ch === 45 || (ch >= 48 && ch <= 57)) {
|
|
116
|
+
return /^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?(?:\s*[,\]])/.test(head);
|
|
117
|
+
}
|
|
118
|
+
if (ch === 116)
|
|
119
|
+
return /^true(?:\s*[,\]])/.test(head);
|
|
120
|
+
if (ch === 102)
|
|
121
|
+
return /^false(?:\s*[,\]])/.test(head);
|
|
122
|
+
if (ch === 110)
|
|
123
|
+
return /^null(?:\s*[,\]])/.test(head);
|
|
124
|
+
}
|
|
125
|
+
return false;
|
|
126
|
+
}
|
|
127
|
+
function stripLineNumPrefix(line) {
|
|
128
|
+
const m = line.match(LINE_NUM_PREFIX_RE);
|
|
129
|
+
return m ? line.slice(m[1].length) : line;
|
|
130
|
+
}
|
|
131
|
+
function looksLikeCodeOrLineNumbered(lines) {
|
|
132
|
+
let numHits = 0;
|
|
133
|
+
let declHits = 0;
|
|
134
|
+
const sample = Math.min(lines.length, 40);
|
|
135
|
+
for (let i = 0; i < sample; i++) {
|
|
136
|
+
const l = lines[i];
|
|
137
|
+
if (LINE_NUM_PREFIX_RE.test(l))
|
|
138
|
+
numHits++;
|
|
139
|
+
if (CODE_DECL_RE.test(stripLineNumPrefix(l)))
|
|
140
|
+
declHits++;
|
|
141
|
+
}
|
|
142
|
+
return numHits >= 5 || declHits >= 3;
|
|
143
|
+
}
|
|
144
|
+
function looksLikeDiff(text, lines) {
|
|
145
|
+
if (lines.some((l) => DIFF_HEADER_RE.test(l)))
|
|
146
|
+
return true;
|
|
147
|
+
let plusMinus = 0;
|
|
148
|
+
for (let i = 0; i < Math.min(lines.length, 30); i++) {
|
|
149
|
+
if (/^[+-][^+-]/.test(lines[i]))
|
|
150
|
+
plusMinus++;
|
|
151
|
+
}
|
|
152
|
+
return plusMinus >= 4 && text.includes('@@');
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Deterministic extractive structural digest for aged tool outputs.
|
|
156
|
+
*/
|
|
157
|
+
export function extractStructuralDigest(text, refId = 'prior') {
|
|
158
|
+
const cacheKey = `${refId}\0${text.length}:${fnv64Hex(text)}`;
|
|
159
|
+
const hit = digestCache.get(cacheKey);
|
|
160
|
+
if (hit !== undefined) {
|
|
161
|
+
digestCache.delete(cacheKey);
|
|
162
|
+
digestCache.set(cacheKey, hit);
|
|
163
|
+
return hit;
|
|
164
|
+
}
|
|
165
|
+
const store = (digest) => {
|
|
166
|
+
const cost = cacheKey.length + digest.length;
|
|
167
|
+
if (cost <= DIGEST_CACHE_MAX_CHARS) {
|
|
168
|
+
const existing = digestCache.get(cacheKey);
|
|
169
|
+
if (existing !== undefined) {
|
|
170
|
+
digestCacheChars -= cacheKey.length + existing.length;
|
|
171
|
+
digestCache.delete(cacheKey);
|
|
172
|
+
}
|
|
173
|
+
while (digestCacheChars + cost > DIGEST_CACHE_MAX_CHARS && digestCache.size > 0) {
|
|
174
|
+
const oldestKey = digestCache.keys().next().value;
|
|
175
|
+
if (oldestKey === undefined)
|
|
176
|
+
break;
|
|
177
|
+
const oldestVal = digestCache.get(oldestKey);
|
|
178
|
+
digestCache.delete(oldestKey);
|
|
179
|
+
if (oldestVal !== undefined)
|
|
180
|
+
digestCacheChars -= oldestKey.length + oldestVal.length;
|
|
181
|
+
}
|
|
182
|
+
digestCache.set(cacheKey, digest);
|
|
183
|
+
digestCacheChars += cost;
|
|
184
|
+
}
|
|
185
|
+
return digest;
|
|
186
|
+
};
|
|
187
|
+
const lines = text.split('\n');
|
|
188
|
+
const sheet = factSheetText(text, 'compact');
|
|
189
|
+
const appendSheet = (body) => store(sheet ? `${body}\n${sheet}` : body);
|
|
190
|
+
if (text.startsWith('@toon ') || looksLikeJsonPayload(text)) {
|
|
191
|
+
if (lines.length === 1 && text.length > 1000) {
|
|
192
|
+
const body = [
|
|
193
|
+
`[fiche epoch-digest ${refId}: structured data (1 line, ${text.length} chars); head/tail + identifiers preserved]`,
|
|
194
|
+
text.slice(0, 300),
|
|
195
|
+
`... (${text.length - 500} chars elided) ...`,
|
|
196
|
+
text.slice(-200),
|
|
197
|
+
].join('\n');
|
|
198
|
+
return appendSheet(body);
|
|
199
|
+
}
|
|
200
|
+
const head = lines.slice(0, Math.min(4, lines.length));
|
|
201
|
+
const tail = lines.length > 6 ? lines.slice(-2) : [];
|
|
202
|
+
const body = [
|
|
203
|
+
`[fiche epoch-digest ${refId}: structured data (${lines.length} lines, ${text.length} chars); head/tail + identifiers preserved]`,
|
|
204
|
+
...head,
|
|
205
|
+
...(tail.length > 0 ? [`... (${lines.length - head.length - tail.length} rows elided) ...`, ...tail] : []),
|
|
206
|
+
].join('\n');
|
|
207
|
+
return appendSheet(body);
|
|
208
|
+
}
|
|
209
|
+
if (looksLikeDiff(text, lines)) {
|
|
210
|
+
const kept = [];
|
|
211
|
+
let deltaCount = 0;
|
|
212
|
+
let omitted = 0;
|
|
213
|
+
for (const l of lines) {
|
|
214
|
+
if (DIFF_HEADER_RE.test(l)) {
|
|
215
|
+
kept.push(l);
|
|
216
|
+
}
|
|
217
|
+
else if (/^[+-]/.test(l)) {
|
|
218
|
+
if (deltaCount < 80) {
|
|
219
|
+
kept.push(l);
|
|
220
|
+
deltaCount++;
|
|
221
|
+
}
|
|
222
|
+
else {
|
|
223
|
+
omitted++;
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
const summary = `[fiche epoch-digest ${refId}: unified diff (${lines.length} lines${omitted > 0 ? `, ${omitted} extra +/- lines omitted` : ''})]`;
|
|
228
|
+
return appendSheet([summary, ...kept].join('\n'));
|
|
229
|
+
}
|
|
230
|
+
if (looksLikeCodeOrLineNumbered(lines)) {
|
|
231
|
+
const keepIdx = new Set();
|
|
232
|
+
for (let i = 0; i < Math.min(4, lines.length); i++)
|
|
233
|
+
keepIdx.add(i);
|
|
234
|
+
for (let i = Math.max(0, lines.length - 4); i < lines.length; i++)
|
|
235
|
+
keepIdx.add(i);
|
|
236
|
+
for (let i = 0; i < lines.length; i++) {
|
|
237
|
+
if (CODE_DECL_RE.test(stripLineNumPrefix(lines[i]))) {
|
|
238
|
+
keepIdx.add(i);
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
const sorted = [...keepIdx].sort((a, b) => a - b);
|
|
242
|
+
const bodyLines = [];
|
|
243
|
+
let prev = -1;
|
|
244
|
+
for (const idx of sorted) {
|
|
245
|
+
if (prev >= 0 && idx > prev + 1) {
|
|
246
|
+
bodyLines.push(` ... (${idx - prev - 1} lines omitted) ...`);
|
|
247
|
+
}
|
|
248
|
+
bodyLines.push(lines[idx]);
|
|
249
|
+
prev = idx;
|
|
250
|
+
}
|
|
251
|
+
const header = `[fiche epoch-digest ${refId}: code skeleton (${lines.length} lines -> ${sorted.length} signature/boundary lines); re-read if full body needed]`;
|
|
252
|
+
return appendSheet([header, ...bodyLines].join('\n'));
|
|
253
|
+
}
|
|
254
|
+
// Logs / CLI / search / prose
|
|
255
|
+
const keepIdx = new Set();
|
|
256
|
+
for (let i = 0; i < Math.min(5, lines.length); i++)
|
|
257
|
+
keepIdx.add(i);
|
|
258
|
+
for (let i = Math.max(0, lines.length - 8); i < lines.length; i++)
|
|
259
|
+
keepIdx.add(i);
|
|
260
|
+
for (let i = 0; i < lines.length; i++) {
|
|
261
|
+
if (LOG_CRITICAL_RE.test(lines[i]))
|
|
262
|
+
keepIdx.add(i);
|
|
263
|
+
}
|
|
264
|
+
const sorted = [...keepIdx].sort((a, b) => a - b);
|
|
265
|
+
const bodyLines = [];
|
|
266
|
+
let prev = -1;
|
|
267
|
+
for (const idx of sorted) {
|
|
268
|
+
if (prev >= 0 && idx > prev + 1) {
|
|
269
|
+
bodyLines.push(`... (${idx - prev - 1} lines omitted) ...`);
|
|
270
|
+
}
|
|
271
|
+
bodyLines.push(lines[idx]);
|
|
272
|
+
prev = idx;
|
|
273
|
+
}
|
|
274
|
+
const header = `[fiche epoch-digest ${refId}: log/output digest (${lines.length} lines -> ${sorted.length} lines); head/errors/tail preserved]`;
|
|
275
|
+
return appendSheet([header, ...bodyLines].join('\n'));
|
|
276
|
+
}
|
|
277
|
+
function isAlreadyCompactedMarker(raw) {
|
|
278
|
+
return (raw.startsWith('[fiche cas') ||
|
|
279
|
+
raw.startsWith('[fiche epoch-digest') ||
|
|
280
|
+
raw.startsWith('[fiche vm-page') ||
|
|
281
|
+
raw.startsWith('[fiche causal-episode ') ||
|
|
282
|
+
raw.startsWith('[folded into ') ||
|
|
283
|
+
raw.startsWith('[inkling cas') ||
|
|
284
|
+
raw.startsWith('[inkling epoch-digest'));
|
|
285
|
+
}
|
|
286
|
+
export function planAndApplyTextEpochs(args) {
|
|
287
|
+
const keepTail = args.keepTailMessages ?? 6;
|
|
288
|
+
const isAutoCacheOpenAI = !(args.cacheBreakpoints && args.cacheBreakpoints.length > 0) &&
|
|
289
|
+
args.ttlSec === undefined &&
|
|
290
|
+
isAutoCacheOpenAIModel(args.model);
|
|
291
|
+
const epochTarget = args.epochTokenTarget ?? 4_000;
|
|
292
|
+
const maxPayback = args.maxPaybackReads ?? 12;
|
|
293
|
+
const lsmActive = args.enableLsm !== false &&
|
|
294
|
+
(args.enableLsm === true ||
|
|
295
|
+
args.sessionKey !== undefined ||
|
|
296
|
+
args.sessionCacheCold !== undefined ||
|
|
297
|
+
args.onPageOut !== undefined ||
|
|
298
|
+
args.lsmEditTailMessages !== undefined ||
|
|
299
|
+
args.lsmMinLargeBlockTokens !== undefined);
|
|
300
|
+
const lsmEditTail = Math.max(0, args.lsmEditTailMessages ?? 2);
|
|
301
|
+
const lsmMinLargeTokens = Math.max(1, args.lsmMinLargeBlockTokens ?? 600);
|
|
302
|
+
const cutoffMsg = args.totalMessages - keepTail;
|
|
303
|
+
const cutoffL1 = args.totalMessages - lsmEditTail;
|
|
304
|
+
if (args.blocks.length === 0) {
|
|
305
|
+
return { changed: false, sealedEpochs: 0, compactedBlocks: 0, savedChars: 0, savedTokens: 0 };
|
|
306
|
+
}
|
|
307
|
+
if (lsmActive ? cutoffL1 <= 1 && cutoffMsg <= 1 : cutoffMsg <= 1) {
|
|
308
|
+
return { changed: false, sealedEpochs: 0, compactedBlocks: 0, savedChars: 0, savedTokens: 0 };
|
|
309
|
+
}
|
|
310
|
+
const maxCandidateCutoff = lsmActive ? Math.max(cutoffMsg, cutoffL1) : cutoffMsg;
|
|
311
|
+
const agedEligible = [];
|
|
312
|
+
const l1ZoneBlocks = [];
|
|
313
|
+
const coldL2Eligible = [];
|
|
314
|
+
for (const b of args.blocks) {
|
|
315
|
+
if (b.msgIndex <= 0 || b.msgIndex >= maxCandidateCutoff)
|
|
316
|
+
continue;
|
|
317
|
+
const raw = b.getText();
|
|
318
|
+
if (raw.length < 1000) {
|
|
319
|
+
if (lsmActive && !args.sessionCacheCold && b.msgIndex >= Math.max(1, cutoffMsg) && b.msgIndex < cutoffL1) {
|
|
320
|
+
l1ZoneBlocks.push(null);
|
|
321
|
+
}
|
|
322
|
+
continue;
|
|
323
|
+
}
|
|
324
|
+
if (isAlreadyCompactedMarker(raw)) {
|
|
325
|
+
if (lsmActive && !args.sessionCacheCold && b.msgIndex >= Math.max(1, cutoffMsg) && b.msgIndex < cutoffL1) {
|
|
326
|
+
l1ZoneBlocks.push(null);
|
|
327
|
+
}
|
|
328
|
+
continue;
|
|
329
|
+
}
|
|
330
|
+
const cand = {
|
|
331
|
+
block: b,
|
|
332
|
+
raw,
|
|
333
|
+
rawTokens: countTokens(raw),
|
|
334
|
+
sig: `${b.refId}:${raw.length}:${fnv64Hex(raw)}`,
|
|
335
|
+
};
|
|
336
|
+
if (lsmActive && args.sessionCacheCold === true) {
|
|
337
|
+
if (b.msgIndex < cutoffL1)
|
|
338
|
+
coldL2Eligible.push(cand);
|
|
339
|
+
}
|
|
340
|
+
else if (b.msgIndex < cutoffMsg) {
|
|
341
|
+
agedEligible.push(cand);
|
|
342
|
+
}
|
|
343
|
+
else if (lsmActive && b.msgIndex < cutoffL1) {
|
|
344
|
+
l1ZoneBlocks.push(cand);
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
const mode = priceMode();
|
|
348
|
+
const hasSession = Boolean(args.sessionKey);
|
|
349
|
+
const keyPrefix = hasSession
|
|
350
|
+
? `${args.sessionKey ?? ''}\0${mode}\0${args.model ?? ''}\0${maxPayback}\0`
|
|
351
|
+
: `${mode}\0${args.model ?? ''}\0${args.ttlSec ?? ''}\0${maxPayback}\0`;
|
|
352
|
+
const buildStickyKey = (epoch) => `${keyPrefix}${epoch.map((e) => e.sig).join('|')}`;
|
|
353
|
+
const isKeySticky = (key) => stickySealedEpochs.has(key) || hasSealedEpochKey(args.sessionKey, key);
|
|
354
|
+
const isEpochStickySealed = (epoch) => {
|
|
355
|
+
if (epoch.length === 0)
|
|
356
|
+
return false;
|
|
357
|
+
return isKeySticky(buildStickyKey(epoch));
|
|
358
|
+
};
|
|
359
|
+
const sealedList = [];
|
|
360
|
+
const stickyOnly = args.stickyOnly === true;
|
|
361
|
+
if (lsmActive && args.sessionCacheCold === true) {
|
|
362
|
+
// L2 Cold-Cache Repack: partition all eligible blocks behind cutoffL1, flushing trailing remainder.
|
|
363
|
+
let pending = [];
|
|
364
|
+
let pendingTokens = 0;
|
|
365
|
+
let pendingSig = '';
|
|
366
|
+
for (const item of coldL2Eligible) {
|
|
367
|
+
if (pending.length === 0 && isKeySticky(`${keyPrefix}${item.sig}`)) {
|
|
368
|
+
sealedList.push([item]);
|
|
369
|
+
continue;
|
|
370
|
+
}
|
|
371
|
+
pending.push(item);
|
|
372
|
+
pendingTokens += item.rawTokens;
|
|
373
|
+
pendingSig = pending.length === 1 ? item.sig : `${pendingSig}|${item.sig}`;
|
|
374
|
+
const stickyHit = isKeySticky(`${keyPrefix}${pendingSig}`);
|
|
375
|
+
if (stickyHit || pendingTokens >= epochTarget) {
|
|
376
|
+
if (!stickyOnly || stickyHit)
|
|
377
|
+
sealedList.push(pending);
|
|
378
|
+
pending = [];
|
|
379
|
+
pendingTokens = 0;
|
|
380
|
+
pendingSig = '';
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
if (!stickyOnly && pending.length > 0) {
|
|
384
|
+
sealedList.push(pending);
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
else {
|
|
388
|
+
// Standard L0/ACDC aged zone behind cutoffMsg.
|
|
389
|
+
let pending = [];
|
|
390
|
+
let pendingTokens = 0;
|
|
391
|
+
let pendingSig = '';
|
|
392
|
+
for (const item of agedEligible) {
|
|
393
|
+
const singleSticky = isKeySticky(`${keyPrefix}${item.sig}`);
|
|
394
|
+
if (pending.length === 0 && singleSticky) {
|
|
395
|
+
sealedList.push([item]);
|
|
396
|
+
continue;
|
|
397
|
+
}
|
|
398
|
+
if (lsmActive && pending.length > 0 && singleSticky) {
|
|
399
|
+
sealedList.push([item]);
|
|
400
|
+
continue;
|
|
401
|
+
}
|
|
402
|
+
pending.push(item);
|
|
403
|
+
pendingTokens += item.rawTokens;
|
|
404
|
+
pendingSig = pending.length === 1 ? item.sig : `${pendingSig}|${item.sig}`;
|
|
405
|
+
const stickyHit = lsmActive && isKeySticky(`${keyPrefix}${pendingSig}`);
|
|
406
|
+
if (stickyHit || pendingTokens >= epochTarget) {
|
|
407
|
+
if (!stickyOnly || stickyHit)
|
|
408
|
+
sealedList.push(pending);
|
|
409
|
+
pending = [];
|
|
410
|
+
pendingTokens = 0;
|
|
411
|
+
pendingSig = '';
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
// L1 Early Large-Block Compaction behind cutoffL1 (before waiting keepTailMessages = 6 turns).
|
|
415
|
+
// Strictly 1-block `[item]` epochs so crossing cutoffMsg into L0 never splits a sticky key.
|
|
416
|
+
if (lsmActive && cutoffL1 > 1) {
|
|
417
|
+
for (const item of l1ZoneBlocks) {
|
|
418
|
+
if (!item)
|
|
419
|
+
continue;
|
|
420
|
+
if ((!stickyOnly && item.rawTokens >= lsmMinLargeTokens) || isKeySticky(`${keyPrefix}${item.sig}`)) {
|
|
421
|
+
sealedList.push([item]);
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
if (sealedList.length === 0) {
|
|
427
|
+
return { changed: false, sealedEpochs: 0, compactedBlocks: 0, savedChars: 0, savedTokens: 0 };
|
|
428
|
+
}
|
|
429
|
+
// Base-tier rates keep frozen-epoch payback strictly monotonic when crossing prompt cliffs.
|
|
430
|
+
const rates = resolvePriceRates(args.model, { promptTokens: 0, ttlSec: args.ttlSec });
|
|
431
|
+
const expectedOut = args.expectedOutputTokens ?? 1000;
|
|
432
|
+
let runningPrompt = args.totalPromptTokens;
|
|
433
|
+
let sealedEpochs = 0;
|
|
434
|
+
let compactedBlocks = 0;
|
|
435
|
+
let totalSavedChars = 0;
|
|
436
|
+
let totalSavedTokens = 0;
|
|
437
|
+
let cliffAvoided;
|
|
438
|
+
const blockTokensByBlock = new Map();
|
|
439
|
+
for (const item of agedEligible)
|
|
440
|
+
blockTokensByBlock.set(item.block, item.rawTokens);
|
|
441
|
+
for (const item of coldL2Eligible)
|
|
442
|
+
blockTokensByBlock.set(item.block, item.rawTokens);
|
|
443
|
+
for (const item of l1ZoneBlocks) {
|
|
444
|
+
if (item)
|
|
445
|
+
blockTokensByBlock.set(item.block, item.rawTokens);
|
|
446
|
+
}
|
|
447
|
+
for (const b of args.blocks) {
|
|
448
|
+
if (!blockTokensByBlock.has(b))
|
|
449
|
+
blockTokensByBlock.set(b, countTokens(b.getText()));
|
|
450
|
+
}
|
|
451
|
+
const coldRepack = lsmActive && args.sessionCacheCold === true;
|
|
452
|
+
const addStickySealed = (key) => {
|
|
453
|
+
if (stickySealedEpochs.size >= STICKY_EPOCH_MAX && !stickySealedEpochs.has(key)) {
|
|
454
|
+
const oldest = stickySealedEpochs.values().next().value;
|
|
455
|
+
if (oldest !== undefined)
|
|
456
|
+
stickySealedEpochs.delete(oldest);
|
|
457
|
+
}
|
|
458
|
+
stickySealedEpochs.add(key);
|
|
459
|
+
recordSealedEpochKey(args.sessionKey, key);
|
|
460
|
+
};
|
|
461
|
+
for (const epoch of sealedList) {
|
|
462
|
+
const stickyKey = buildStickyKey(epoch);
|
|
463
|
+
const alreadySealed = stickySealedEpochs.has(stickyKey) || hasSealedEpochKey(args.sessionKey, stickyKey);
|
|
464
|
+
const proposals = epoch.map((item) => {
|
|
465
|
+
const digest = extractStructuralDigest(item.raw, item.block.refId);
|
|
466
|
+
const [rawTokPaired, digestTokPaired] = estimateTokenPair(item.raw, digest);
|
|
467
|
+
return { item, digest, rawTokPaired, digestTokPaired };
|
|
468
|
+
});
|
|
469
|
+
const epochRawTokens = proposals.reduce((sum, p) => sum + p.rawTokPaired, 0);
|
|
470
|
+
const epochDigestTokens = proposals.reduce((sum, p) => sum + p.digestTokPaired, 0);
|
|
471
|
+
if (!alreadySealed && epochDigestTokens >= epochRawTokens * 0.55)
|
|
472
|
+
continue;
|
|
473
|
+
const epochLastBlock = epoch[epoch.length - 1].block;
|
|
474
|
+
const epochLastMsg = epochLastBlock.msgIndex;
|
|
475
|
+
const epochLastBlockIdx = epochLastBlock.blockIndex ?? 0;
|
|
476
|
+
let coveringTtlSec = 0;
|
|
477
|
+
const hasBreakpoints = Boolean(args.cacheBreakpoints && args.cacheBreakpoints.length > 0);
|
|
478
|
+
let horizonEndMsg = args.totalMessages - 3;
|
|
479
|
+
if (args.cacheBreakpoints && args.cacheBreakpoints.length > 0) {
|
|
480
|
+
let maxBpMsg = -1;
|
|
481
|
+
for (const bp of args.cacheBreakpoints) {
|
|
482
|
+
if (bp.msgIndex > epochLastMsg || (bp.msgIndex === epochLastMsg && bp.blockIndex >= epochLastBlockIdx)) {
|
|
483
|
+
if (bp.ttlSec > coveringTtlSec)
|
|
484
|
+
coveringTtlSec = bp.ttlSec;
|
|
485
|
+
if (bp.msgIndex > maxBpMsg)
|
|
486
|
+
maxBpMsg = bp.msgIndex;
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
if (maxBpMsg >= 0) {
|
|
490
|
+
horizonEndMsg = Math.max(horizonEndMsg, Math.min(args.totalMessages - 1, maxBpMsg));
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
const effectiveTtlSec = Math.max(args.ttlSec ?? 0, coveringTtlSec) || undefined;
|
|
494
|
+
const epochRates = effectiveTtlSec !== args.ttlSec
|
|
495
|
+
? resolvePriceRates(args.model, { promptTokens: 0, ttlSec: effectiveTtlSec })
|
|
496
|
+
: rates;
|
|
497
|
+
let downstreamCachedTokens = 0;
|
|
498
|
+
let midPrefixDownstreamTokens = 0;
|
|
499
|
+
if (!coldRepack) {
|
|
500
|
+
let blockSum = 0;
|
|
501
|
+
for (const b of args.blocks) {
|
|
502
|
+
if (b.msgIndex > epochLastMsg && b.msgIndex <= horizonEndMsg) {
|
|
503
|
+
const tok = blockTokensByBlock.get(b) ?? 0;
|
|
504
|
+
blockSum += tok;
|
|
505
|
+
if (b.msgIndex < cutoffMsg) {
|
|
506
|
+
midPrefixDownstreamTokens += tok;
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
let msgSum = 0;
|
|
511
|
+
if (hasBreakpoints && args.msgTotalTokens && args.msgTotalTokens.length > 0) {
|
|
512
|
+
const limit = Math.min(args.msgTotalTokens.length - 1, horizonEndMsg);
|
|
513
|
+
for (let m = epochLastMsg + 1; m <= limit; m++) {
|
|
514
|
+
msgSum += args.msgTotalTokens[m] ?? 0;
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
downstreamCachedTokens = Math.max(blockSum, msgSum);
|
|
518
|
+
if (hasBreakpoints) {
|
|
519
|
+
midPrefixDownstreamTokens = downstreamCachedTokens;
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
const effectiveWriteRate = isAutoCacheOpenAI
|
|
523
|
+
? Math.min(epochRates.write, 1)
|
|
524
|
+
: epochRates.write;
|
|
525
|
+
const savedTok = epochRawTokens - epochDigestTokens;
|
|
526
|
+
const savedPerRead = savedTok * epochRates.read;
|
|
527
|
+
const transitionCost = epochDigestTokens * effectiveWriteRate -
|
|
528
|
+
epochRawTokens * epochRates.read +
|
|
529
|
+
downstreamCachedTokens * (effectiveWriteRate - epochRates.read);
|
|
530
|
+
const paybackReads = savedPerRead > 0 ? Math.ceil(Math.max(0, transitionCost) / savedPerRead) : Infinity;
|
|
531
|
+
const stickyCliffAt = mode === 'kosha' ? stickyCliffEpochs.get(stickyKey) : undefined;
|
|
532
|
+
const stickyCliffActive = stickyCliffAt !== undefined && runningPrompt > stickyCliffAt;
|
|
533
|
+
const cliff = evaluateCliffAvoidance(args.model, {
|
|
534
|
+
promptTokensBefore: runningPrompt,
|
|
535
|
+
promptTokensAfter: Math.max(0, runningPrompt - savedTok),
|
|
536
|
+
collapsedBaselineTokens: epochRawTokens,
|
|
537
|
+
collapsedActualTokens: epochDigestTokens,
|
|
538
|
+
downstreamCachedTokens,
|
|
539
|
+
expectedOutputTokens: expectedOut,
|
|
540
|
+
ttlSec: effectiveTtlSec,
|
|
541
|
+
});
|
|
542
|
+
const turnsObserved = Math.max(1, Math.floor(args.totalMessages / 2));
|
|
543
|
+
const cliffWins = Boolean(cliff?.crossesCliff && cliff.netSingleTurnUsd > 0) || stickyCliffActive;
|
|
544
|
+
const effectiveMaxPayback = args.maxPaybackReads !== undefined
|
|
545
|
+
? maxPayback
|
|
546
|
+
: computeHorizonPaybackLimit({
|
|
547
|
+
turnsObserved,
|
|
548
|
+
baseMaxPayback: maxPayback,
|
|
549
|
+
downstreamCachedTokens: midPrefixDownstreamTokens,
|
|
550
|
+
});
|
|
551
|
+
if (!alreadySealed && paybackReads > effectiveMaxPayback && !cliffWins)
|
|
552
|
+
continue;
|
|
553
|
+
let epochSavedChars = 0;
|
|
554
|
+
let epochSavedTok = 0;
|
|
555
|
+
const compactedItems = [];
|
|
556
|
+
for (const p of proposals) {
|
|
557
|
+
if (p.digest.length < p.item.raw.length && p.digestTokPaired < p.rawTokPaired) {
|
|
558
|
+
const decorated = args.onPageOut ? args.onPageOut(p.item.block, p.item.raw, p.digest) : undefined;
|
|
559
|
+
const replacement = decorated ?? p.digest;
|
|
560
|
+
if (replacement.length >= p.item.raw.length)
|
|
561
|
+
continue;
|
|
562
|
+
const repTok = replacement === p.digest
|
|
563
|
+
? p.digestTokPaired
|
|
564
|
+
: estimateTokenPair(p.item.raw, replacement)[1];
|
|
565
|
+
if (repTok >= p.rawTokPaired)
|
|
566
|
+
continue;
|
|
567
|
+
p.item.block.setText(replacement);
|
|
568
|
+
compactedBlocks++;
|
|
569
|
+
compactedItems.push(p.item);
|
|
570
|
+
epochSavedChars += p.item.raw.length - replacement.length;
|
|
571
|
+
epochSavedTok += p.rawTokPaired - repTok;
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
if (epochSavedChars > 0) {
|
|
575
|
+
sealedEpochs++;
|
|
576
|
+
totalSavedChars += epochSavedChars;
|
|
577
|
+
totalSavedTokens += epochSavedTok;
|
|
578
|
+
runningPrompt = Math.max(0, runningPrompt - epochSavedTok);
|
|
579
|
+
addStickySealed(stickyKey);
|
|
580
|
+
if (coldRepack) {
|
|
581
|
+
// Also pin per-block keys so crossing cutoffMsg after L2 -> Warm never tears an epoch.
|
|
582
|
+
for (const ci of compactedItems) {
|
|
583
|
+
addStickySealed(buildStickyKey([ci]));
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
if (cliff?.crossesCliff && cliff.netSingleTurnUsd > 0) {
|
|
587
|
+
if (stickyCliffEpochs.size >= STICKY_EPOCH_MAX && !stickyCliffEpochs.has(stickyKey)) {
|
|
588
|
+
const oldest = stickyCliffEpochs.keys().next().value;
|
|
589
|
+
if (oldest !== undefined)
|
|
590
|
+
stickyCliffEpochs.delete(oldest);
|
|
591
|
+
}
|
|
592
|
+
stickyCliffEpochs.set(stickyKey, cliff.cliffAt);
|
|
593
|
+
if (!cliffAvoided) {
|
|
594
|
+
cliffAvoided = {
|
|
595
|
+
at: cliff.cliffAt,
|
|
596
|
+
multiplier: cliff.multiplier,
|
|
597
|
+
savedUsd: cliff.netSingleTurnUsd,
|
|
598
|
+
};
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
return {
|
|
604
|
+
changed: compactedBlocks > 0,
|
|
605
|
+
sealedEpochs,
|
|
606
|
+
compactedBlocks,
|
|
607
|
+
savedChars: totalSavedChars,
|
|
608
|
+
savedTokens: totalSavedTokens,
|
|
609
|
+
...(cliffAvoided ? { cliffAvoided } : {}),
|
|
610
|
+
};
|
|
611
|
+
}
|
|
612
|
+
//# sourceMappingURL=text-history.js.map
|