@sriinnu/fiche 0.0.0-stage → 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 +288 -2
- 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 +122 -4
- 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,3028 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Context-MMU: Virtual Context Memory engine for Fiche (Pure Core — zero `node:` imports).
|
|
3
|
+
*
|
|
4
|
+
* Five deterministic, prefix-cache-safe primitives:
|
|
5
|
+
* 1. `ContextPageStore` + deterministic 64-bit FNV-1a page IDs (`pg_<12hex>`),
|
|
6
|
+
* bounded LRU eviction (`maxPages`, `maxBytes`), inverted symbol/basename index,
|
|
7
|
+
* and pluggable debounced persistence (`MmuPersistenceAdapter`).
|
|
8
|
+
* 2. `extractSymbolSpans` + `inferFilePath` + `extractErrorAnchors`: O(N) line
|
|
9
|
+
* scanner across TS/JS, Python, Go, Rust, Swift, and Java with line-gutter stripping.
|
|
10
|
+
* 3. `computeTailHydration`: read-only speculative live-tail hydration (`±15` lines)
|
|
11
|
+
* from paged-out pages without mutating cached prefixes.
|
|
12
|
+
* 4. `foldMarkovianEpisodes`: Markovian causal episode folding at verified checkpoints
|
|
13
|
+
* (`git commit`, red -> green test passes, PR merge) gated by Kosha payback / cliff avoidance.
|
|
14
|
+
* 5. `linkSessionSkills` & `pruneLowDensityBlob`: Turn-1 pinned skill stubbing with
|
|
15
|
+
* Turn-N auto-hydration, and `<3ms` birth-time information-density prose pruning.
|
|
16
|
+
*/
|
|
17
|
+
import { extractFactSheetTokens } from './factsheet.js';
|
|
18
|
+
import { gptTokenCount, hasLongUnbrokenBpeChunk } from './gpt-tokens.js';
|
|
19
|
+
import { resetGlobalPrefixTape } from './prefix-tape.js';
|
|
20
|
+
import { evaluateCliffAvoidance, isAutoCacheOpenAIModel, resolvePriceRates } from './pricing.js';
|
|
21
|
+
import { getFoldedEpisodeCertificate, hasAnyFoldedEpisodeId, hasFoldedEpisodeId, recordFoldedEpisodeId, } from './session-state.js';
|
|
22
|
+
// ---------------------------------------------------------------------------
|
|
23
|
+
// Constants & Shared Helpers
|
|
24
|
+
// ---------------------------------------------------------------------------
|
|
25
|
+
const DEFAULT_MAX_PAGES = 512;
|
|
26
|
+
const DEFAULT_MAX_BYTES = 16 * 1024 * 1024;
|
|
27
|
+
const MIN_MMU_PAGES = 64;
|
|
28
|
+
const MAX_MMU_PAGES = 16_384;
|
|
29
|
+
const MIN_MMU_BYTES = 4 * 1024 * 1024;
|
|
30
|
+
const MAX_MMU_BYTES = 256 * 1024 * 1024;
|
|
31
|
+
const DEFAULT_DEBOUNCE_MS = 250;
|
|
32
|
+
const PERSIST_FORMAT = 1;
|
|
33
|
+
const PERSIST_MAX_IDLE_MS = 24 * 60 * 60 * 1000;
|
|
34
|
+
const TOKEN_EXACT_LIMIT = 32_000;
|
|
35
|
+
const STICKY_EPISODE_CAP = 1024;
|
|
36
|
+
const MAX_LINE_SCAN_CHARS = 512;
|
|
37
|
+
const MAX_DEREF_CHARS = 65_536;
|
|
38
|
+
const TLB_MAX_SESSIONS = 512;
|
|
39
|
+
const TLB_MAX_LEASES_PER_SESSION = 64;
|
|
40
|
+
const TLB_DEFAULT_COOLDOWN_TURNS = 3;
|
|
41
|
+
const TLB_OVERLAP_PAD_LINES = 4;
|
|
42
|
+
const EMPTY_I32 = new Int32Array(0);
|
|
43
|
+
const POW_HALF = Float64Array.from({ length: 32 }, (_, k) => Math.pow(0.5, k));
|
|
44
|
+
/**
|
|
45
|
+
* Horizon-aware online compaction payback gate.
|
|
46
|
+
* At the append frontier (`downstreamCachedTokens <= 0`), admits fast (`>= 16` reads).
|
|
47
|
+
* Mid-prefix (`downstreamCachedTokens > 0`), scales conservatively with observed turns
|
|
48
|
+
* so immature sessions do not pay heavy cache-write penalties prematurely.
|
|
49
|
+
*/
|
|
50
|
+
export function computeHorizonPaybackLimit(opts) {
|
|
51
|
+
if (opts.downstreamCachedTokens <= 0) {
|
|
52
|
+
return Math.max(opts.baseMaxPayback, 16);
|
|
53
|
+
}
|
|
54
|
+
return Math.max(4, Math.min(opts.baseMaxPayback, Math.round(3 + opts.turnsObserved * 0.45)));
|
|
55
|
+
}
|
|
56
|
+
const TOKEN_CACHE_MAX = 2048;
|
|
57
|
+
const tokenCountCache = new Map();
|
|
58
|
+
function countTokensFast(text) {
|
|
59
|
+
if (!text)
|
|
60
|
+
return 0;
|
|
61
|
+
if (text.length <= TOKEN_EXACT_LIMIT && !hasLongUnbrokenBpeChunk(text)) {
|
|
62
|
+
const key = `${text.length}:${fnv64Hex(text)}`;
|
|
63
|
+
const hit = tokenCountCache.get(key);
|
|
64
|
+
if (hit !== undefined)
|
|
65
|
+
return hit;
|
|
66
|
+
const tok = gptTokenCount(text);
|
|
67
|
+
if (tokenCountCache.size >= TOKEN_CACHE_MAX) {
|
|
68
|
+
const oldest = tokenCountCache.keys().next().value;
|
|
69
|
+
if (oldest !== undefined)
|
|
70
|
+
tokenCountCache.delete(oldest);
|
|
71
|
+
}
|
|
72
|
+
tokenCountCache.set(key, tok);
|
|
73
|
+
return tok;
|
|
74
|
+
}
|
|
75
|
+
return Math.ceil(text.length / 3.5);
|
|
76
|
+
}
|
|
77
|
+
/** Exact UTF-8 byte length in pure JS without allocating a buffer. */
|
|
78
|
+
function utf8ByteLength(text) {
|
|
79
|
+
let bytes = 0;
|
|
80
|
+
for (let i = 0; i < text.length; i++) {
|
|
81
|
+
const code = text.charCodeAt(i);
|
|
82
|
+
if (code < 0x80) {
|
|
83
|
+
bytes += 1;
|
|
84
|
+
}
|
|
85
|
+
else if (code < 0x800) {
|
|
86
|
+
bytes += 2;
|
|
87
|
+
}
|
|
88
|
+
else if (code >= 0xd800 && code <= 0xdbff && i + 1 < text.length) {
|
|
89
|
+
const next = text.charCodeAt(i + 1);
|
|
90
|
+
if (next >= 0xdc00 && next <= 0xdfff) {
|
|
91
|
+
bytes += 4;
|
|
92
|
+
i += 1;
|
|
93
|
+
}
|
|
94
|
+
else {
|
|
95
|
+
bytes += 3;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
else {
|
|
99
|
+
bytes += 3;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
return bytes;
|
|
103
|
+
}
|
|
104
|
+
function countLines(text) {
|
|
105
|
+
if (!text)
|
|
106
|
+
return 0;
|
|
107
|
+
let lines = 1;
|
|
108
|
+
for (let i = 0; i < text.length; i++) {
|
|
109
|
+
if (text.charCodeAt(i) === 10)
|
|
110
|
+
lines += 1;
|
|
111
|
+
}
|
|
112
|
+
return lines;
|
|
113
|
+
}
|
|
114
|
+
function pathBasename(filePath) {
|
|
115
|
+
const normalized = filePath.replace(/\\/g, '/');
|
|
116
|
+
const idx = normalized.lastIndexOf('/');
|
|
117
|
+
return idx >= 0 ? normalized.slice(idx + 1) : normalized;
|
|
118
|
+
}
|
|
119
|
+
// ---------------------------------------------------------------------------
|
|
120
|
+
// 1. Deterministic 64-bit FNV-1a Hashing & Page IDs
|
|
121
|
+
// ---------------------------------------------------------------------------
|
|
122
|
+
/**
|
|
123
|
+
* Compute deterministic 64-bit FNV-1a digest as 16 lowercase hex chars.
|
|
124
|
+
* Uses two 32-bit lanes with exact IEEE-754 safe integer carry arithmetic
|
|
125
|
+
* (zero `node:crypto`, zero BigInt heap allocations).
|
|
126
|
+
*/
|
|
127
|
+
export function fnv64Hex(text) {
|
|
128
|
+
let hi = 0xcbf29ce4 >>> 0;
|
|
129
|
+
let lo = 0x84222325 >>> 0;
|
|
130
|
+
const step = (b) => {
|
|
131
|
+
lo = (lo ^ b) >>> 0;
|
|
132
|
+
const prodLo = lo * 0x1b3; // max 2^32 * 435 < 2^41 (exact IEEE-754 double)
|
|
133
|
+
const carry = Math.floor(prodLo / 0x100000000);
|
|
134
|
+
hi = (Math.imul(hi, 0x1b3) + carry + ((lo & 0xffffff) << 8)) >>> 0;
|
|
135
|
+
lo = prodLo >>> 0;
|
|
136
|
+
};
|
|
137
|
+
for (let i = 0; i < text.length; i++) {
|
|
138
|
+
const c = text.charCodeAt(i);
|
|
139
|
+
if (c < 0x80) {
|
|
140
|
+
step(c);
|
|
141
|
+
}
|
|
142
|
+
else if (c < 0x800) {
|
|
143
|
+
step(0xc0 | (c >>> 6));
|
|
144
|
+
step(0x80 | (c & 0x3f));
|
|
145
|
+
}
|
|
146
|
+
else if (c >= 0xd800 && c <= 0xdbff && i + 1 < text.length) {
|
|
147
|
+
const next = text.charCodeAt(i + 1);
|
|
148
|
+
if (next >= 0xdc00 && next <= 0xdfff) {
|
|
149
|
+
const cp = 0x10000 + ((c - 0xd800) << 10) + (next - 0xdc00);
|
|
150
|
+
step(0xf0 | (cp >>> 18));
|
|
151
|
+
step(0x80 | ((cp >>> 12) & 0x3f));
|
|
152
|
+
step(0x80 | ((cp >>> 6) & 0x3f));
|
|
153
|
+
step(0x80 | (cp & 0x3f));
|
|
154
|
+
i += 1;
|
|
155
|
+
}
|
|
156
|
+
else {
|
|
157
|
+
step(0xe0 | (c >>> 12));
|
|
158
|
+
step(0x80 | ((c >>> 6) & 0x3f));
|
|
159
|
+
step(0x80 | (c & 0x3f));
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
else {
|
|
163
|
+
step(0xe0 | (c >>> 12));
|
|
164
|
+
step(0x80 | ((c >>> 6) & 0x3f));
|
|
165
|
+
step(0x80 | (c & 0x3f));
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
return hi.toString(16).padStart(8, '0') + lo.toString(16).padStart(8, '0');
|
|
169
|
+
}
|
|
170
|
+
/** Deterministic Context-MMU page ID (`pg_<12hex>`) derived from 64-bit FNV-1a. */
|
|
171
|
+
export function pageIdForText(text) {
|
|
172
|
+
return `pg_${fnv64Hex(text).slice(0, 12)}`;
|
|
173
|
+
}
|
|
174
|
+
const GUTTER_EXPLICIT_RE = /^(?:\s*\d{1,7}(?:\t|→|\s*[|\u2502](?:\s|$))|L\d{1,7}:\s)/;
|
|
175
|
+
const GUTTER_COLON_RE = /^\s*(\d{1,7}):\s?(.*)$/;
|
|
176
|
+
const CODE_KW_AFTER_COLON_RE = /^(?:export|import|async|function|class|interface|type|enum|struct|trait|impl|fn|func|def|pub|public|private|protected|internal|static|const|let|var|protocol|actor|package|from)\b/;
|
|
177
|
+
function detectColonGutterMode(lines) {
|
|
178
|
+
let hits = 0;
|
|
179
|
+
const limit = Math.min(lines.length, 40);
|
|
180
|
+
for (let i = 0; i < limit; i++) {
|
|
181
|
+
const m = GUTTER_COLON_RE.exec(lines[i].slice(0, 128));
|
|
182
|
+
if (m && (CODE_KW_AFTER_COLON_RE.test(m[2]) || /^\s*$/.test(m[2]))) {
|
|
183
|
+
hits += 1;
|
|
184
|
+
if (hits >= 3)
|
|
185
|
+
return true;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
return false;
|
|
189
|
+
}
|
|
190
|
+
function stripLineGutter(line, allowColonGutter) {
|
|
191
|
+
const m = GUTTER_EXPLICIT_RE.exec(line);
|
|
192
|
+
if (m)
|
|
193
|
+
return line.slice(m[0].length);
|
|
194
|
+
if (allowColonGutter) {
|
|
195
|
+
const cm = GUTTER_COLON_RE.exec(line);
|
|
196
|
+
if (cm)
|
|
197
|
+
return cm[2] ?? '';
|
|
198
|
+
}
|
|
199
|
+
return line;
|
|
200
|
+
}
|
|
201
|
+
const FILE_HEADER_PATTERNS = [
|
|
202
|
+
/^diff --git a\/([^\s]+) b\/([^\s]+)/,
|
|
203
|
+
/^\+\+\+ (?:b\/)?([^\s\t]+)/,
|
|
204
|
+
/^--- (?:a\/)?([^\s\t]+)/,
|
|
205
|
+
/^\*\*\* (?:Update|Add|Delete) File:\s*([^\s\r\n]+)/,
|
|
206
|
+
/^(?:\/\/|#|\/\*|\*)\s*(?:file|path)\s*:\s*([^\s*]+(?:\.[A-Za-z0-9]{1,10}))/i,
|
|
207
|
+
/^(?:File|Path)\s*:\s*["']?([^\s"']+\.[A-Za-z0-9]{1,10})["']?/i,
|
|
208
|
+
/^File\s+"([^"\n]+)",\s*line\s+\d+/,
|
|
209
|
+
/^<file\s+(?:path|name)=["']([^"'\n]+)["']/i,
|
|
210
|
+
/^===\s*([^\s=]+\.[A-Za-z0-9]{1,10})\s*===$/,
|
|
211
|
+
/^(?:\/\/|#)\s*((?:[\w.-]+\/)+[\w.-]+\.[A-Za-z0-9]{1,10})\s*$/,
|
|
212
|
+
/^["']?(?:file_?[pP]ath|path)["']?\s*:\s*["']([^"'\n]+\.[A-Za-z0-9]{1,10})["']/,
|
|
213
|
+
];
|
|
214
|
+
function cleanInferredPath(raw) {
|
|
215
|
+
if (!raw)
|
|
216
|
+
return undefined;
|
|
217
|
+
let cleaned = raw.trim().replace(/^["']|["']$/g, '').replace(/[:,;]+$/, '');
|
|
218
|
+
if (!cleaned || cleaned === '/dev/null' || cleaned.length > 260)
|
|
219
|
+
return undefined;
|
|
220
|
+
if (cleaned.startsWith('a/') || cleaned.startsWith('b/')) {
|
|
221
|
+
cleaned = cleaned.slice(2);
|
|
222
|
+
}
|
|
223
|
+
if (!/[/.]/.test(cleaned) || /\s/.test(cleaned))
|
|
224
|
+
return undefined;
|
|
225
|
+
return cleaned;
|
|
226
|
+
}
|
|
227
|
+
/** Infer a source file path from header lines or `refId` if present. */
|
|
228
|
+
export function inferFilePath(text, refId) {
|
|
229
|
+
if (text) {
|
|
230
|
+
const lines = text.split('\n');
|
|
231
|
+
const limit = Math.min(lines.length, 15);
|
|
232
|
+
const allowColon = detectColonGutterMode(lines);
|
|
233
|
+
for (let i = 0; i < limit; i++) {
|
|
234
|
+
const line = stripLineGutter(lines[i], allowColon).trim().slice(0, 260);
|
|
235
|
+
if (!line)
|
|
236
|
+
continue;
|
|
237
|
+
for (let p = 0; p < FILE_HEADER_PATTERNS.length; p++) {
|
|
238
|
+
const m = FILE_HEADER_PATTERNS[p].exec(line);
|
|
239
|
+
if (!m)
|
|
240
|
+
continue;
|
|
241
|
+
const candidate = cleanInferredPath(m[2] ?? m[1]);
|
|
242
|
+
if (candidate)
|
|
243
|
+
return candidate;
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
if (refId) {
|
|
248
|
+
const trimmedRef = refId.trim();
|
|
249
|
+
if (/^(?:[\w.@+-]+\/)+[\w.@+-]+\.[A-Za-z0-9]{1,10}$/.test(trimmedRef)) {
|
|
250
|
+
return trimmedRef;
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
return undefined;
|
|
254
|
+
}
|
|
255
|
+
const MODIFIER_WORDS = new Set([
|
|
256
|
+
'export',
|
|
257
|
+
'default',
|
|
258
|
+
'declare',
|
|
259
|
+
'async',
|
|
260
|
+
'abstract',
|
|
261
|
+
'pub',
|
|
262
|
+
'public',
|
|
263
|
+
'private',
|
|
264
|
+
'protected',
|
|
265
|
+
'internal',
|
|
266
|
+
'fileprivate',
|
|
267
|
+
'open',
|
|
268
|
+
'static',
|
|
269
|
+
'final',
|
|
270
|
+
'override',
|
|
271
|
+
'readonly',
|
|
272
|
+
'sealed',
|
|
273
|
+
'unsafe',
|
|
274
|
+
'mutating',
|
|
275
|
+
'nonmutating',
|
|
276
|
+
'synchronized',
|
|
277
|
+
'native',
|
|
278
|
+
'inline',
|
|
279
|
+
'suspend',
|
|
280
|
+
'extern',
|
|
281
|
+
]);
|
|
282
|
+
const CONTROL_KEYWORDS = new Set([
|
|
283
|
+
'if',
|
|
284
|
+
'else',
|
|
285
|
+
'for',
|
|
286
|
+
'while',
|
|
287
|
+
'switch',
|
|
288
|
+
'case',
|
|
289
|
+
'catch',
|
|
290
|
+
'with',
|
|
291
|
+
'return',
|
|
292
|
+
'throw',
|
|
293
|
+
'await',
|
|
294
|
+
'new',
|
|
295
|
+
'typeof',
|
|
296
|
+
'delete',
|
|
297
|
+
'super',
|
|
298
|
+
'this',
|
|
299
|
+
'yield',
|
|
300
|
+
'import',
|
|
301
|
+
'from',
|
|
302
|
+
'match',
|
|
303
|
+
]);
|
|
304
|
+
function skipLeadingModifiers(trimmedHead) {
|
|
305
|
+
let s = trimmedHead;
|
|
306
|
+
let hadModifier = false;
|
|
307
|
+
let hadConst = false;
|
|
308
|
+
for (let steps = 0; steps < 8; steps++) {
|
|
309
|
+
// Handle Rust `pub(crate)` / `pub(super)` / `pub(in ...)`
|
|
310
|
+
if (s.startsWith('pub(')) {
|
|
311
|
+
const close = s.indexOf(')');
|
|
312
|
+
if (close > 0 && close < 32) {
|
|
313
|
+
s = s.slice(close + 1).trimStart();
|
|
314
|
+
hadModifier = true;
|
|
315
|
+
continue;
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
// Handle `extern "C"`
|
|
319
|
+
if (s.startsWith('extern ')) {
|
|
320
|
+
const m = /^extern(?:\s+"[^"\n]{1,16}")?\s+/.exec(s);
|
|
321
|
+
if (m) {
|
|
322
|
+
s = s.slice(m[0].length).trimStart();
|
|
323
|
+
hadModifier = true;
|
|
324
|
+
continue;
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
const sp = /^([A-Za-z_][A-Za-z0-9_-]*)\s+/.exec(s);
|
|
328
|
+
if (!sp)
|
|
329
|
+
break;
|
|
330
|
+
const word = sp[1];
|
|
331
|
+
if (word === 'const') {
|
|
332
|
+
// `const` can be Rust `const fn`, TS `const enum`, or JS `const foo = ...`
|
|
333
|
+
const after = s.slice(sp[0].length).trimStart();
|
|
334
|
+
if (/^(?:fn|enum|unsafe)\b/.test(after)) {
|
|
335
|
+
s = after;
|
|
336
|
+
hadModifier = true;
|
|
337
|
+
hadConst = true;
|
|
338
|
+
continue;
|
|
339
|
+
}
|
|
340
|
+
break;
|
|
341
|
+
}
|
|
342
|
+
if (!MODIFIER_WORDS.has(word))
|
|
343
|
+
break;
|
|
344
|
+
s = s.slice(sp[0].length).trimStart();
|
|
345
|
+
hadModifier = true;
|
|
346
|
+
}
|
|
347
|
+
return { rest: s, hadModifier, hadConst };
|
|
348
|
+
}
|
|
349
|
+
function parseDeclarationLine(strippedLine, insideBraceClass) {
|
|
350
|
+
const trimmed = strippedLine.trim();
|
|
351
|
+
if (!trimmed)
|
|
352
|
+
return null;
|
|
353
|
+
// Skip comments, strings, decorators
|
|
354
|
+
if (trimmed.startsWith('//') ||
|
|
355
|
+
trimmed.startsWith('/*') ||
|
|
356
|
+
trimmed.startsWith('*') ||
|
|
357
|
+
trimmed.startsWith('#') ||
|
|
358
|
+
trimmed.startsWith('@')) {
|
|
359
|
+
return null;
|
|
360
|
+
}
|
|
361
|
+
const head = trimmed.length > MAX_LINE_SCAN_CHARS ? trimmed.slice(0, MAX_LINE_SCAN_CHARS) : trimmed;
|
|
362
|
+
const { rest, hadModifier } = skipLeadingModifiers(head);
|
|
363
|
+
if (!rest)
|
|
364
|
+
return null;
|
|
365
|
+
// Python `def name(` / `class Name`
|
|
366
|
+
let m = /^def\s+([A-Za-z_]\w*)\s*\(/.exec(rest);
|
|
367
|
+
if (m) {
|
|
368
|
+
return { name: m[1], kind: 'function', isPythonIndent: true, isStatementNoBody: false };
|
|
369
|
+
}
|
|
370
|
+
// Go `func (recv) Name(` or `func Name(` / Swift `func name(`
|
|
371
|
+
m = /^func\s+(?:\([^)\n]{1,80}\)\s*)?([A-Za-z_]\w*)\s*(?:<[^>\n]{0,60}>)?\s*\(/.exec(rest);
|
|
372
|
+
if (m) {
|
|
373
|
+
const hasRecv = /^func\s*\(/.test(rest);
|
|
374
|
+
return {
|
|
375
|
+
name: m[1],
|
|
376
|
+
kind: hasRecv ? 'method' : 'function',
|
|
377
|
+
isPythonIndent: false,
|
|
378
|
+
isStatementNoBody: !rest.includes('{') && rest.endsWith(';'),
|
|
379
|
+
};
|
|
380
|
+
}
|
|
381
|
+
// Rust `fn name`
|
|
382
|
+
m = /^fn\s+([A-Za-z_]\w*)\s*(?:<|\()/.exec(rest);
|
|
383
|
+
if (m) {
|
|
384
|
+
return {
|
|
385
|
+
name: m[1],
|
|
386
|
+
kind: 'function',
|
|
387
|
+
isPythonIndent: false,
|
|
388
|
+
isStatementNoBody: !rest.includes('{') && rest.endsWith(';'),
|
|
389
|
+
};
|
|
390
|
+
}
|
|
391
|
+
// TS/JS `function [*] name(`
|
|
392
|
+
m = /^function\s*\*?\s*([A-Za-z_$][\w$]*)\s*(?:<|\()/.exec(rest);
|
|
393
|
+
if (m) {
|
|
394
|
+
return {
|
|
395
|
+
name: m[1],
|
|
396
|
+
kind: 'function',
|
|
397
|
+
isPythonIndent: false,
|
|
398
|
+
isStatementNoBody: !rest.includes('{') && rest.endsWith(';'),
|
|
399
|
+
};
|
|
400
|
+
}
|
|
401
|
+
// Type declarations across TS/Go/Rust/Swift/Java
|
|
402
|
+
m = /^(class|interface|struct|enum|trait|protocol|actor|record|namespace|mod)\s+([A-Za-z_$][\w$]*)\b/.exec(rest);
|
|
403
|
+
if (m) {
|
|
404
|
+
const kw = m[1];
|
|
405
|
+
const name = m[2];
|
|
406
|
+
const kind = kw === 'record'
|
|
407
|
+
? 'class'
|
|
408
|
+
: kw === 'mod' || kw === 'namespace'
|
|
409
|
+
? 'module'
|
|
410
|
+
: kw;
|
|
411
|
+
const isPyClass = kw === 'class' && !rest.includes('{') && (/:\s*(?:#.*)?$/.test(rest) || rest.includes('('));
|
|
412
|
+
return {
|
|
413
|
+
name,
|
|
414
|
+
kind,
|
|
415
|
+
isPythonIndent: isPyClass,
|
|
416
|
+
isStatementNoBody: !isPyClass && !rest.includes('{') && rest.endsWith(';'),
|
|
417
|
+
};
|
|
418
|
+
}
|
|
419
|
+
// Rust `impl [<T>] [Trait for] TypeName`
|
|
420
|
+
if (rest.startsWith('impl ') || rest.startsWith('impl<')) {
|
|
421
|
+
const implFor = /^impl(?:<[^>\n]{0,80}>)?\s+[A-Za-z_]\w*(?:::[A-Za-z_]\w*)*(?:<[^>\n]{0,80}>)?\s+for\s+([A-Za-z_]\w*)/.exec(rest);
|
|
422
|
+
if (implFor) {
|
|
423
|
+
return { name: implFor[1], kind: 'impl', isPythonIndent: false, isStatementNoBody: false };
|
|
424
|
+
}
|
|
425
|
+
const implSelf = /^impl(?:<[^>\n]{0,80}>)?\s+([A-Za-z_]\w*)/.exec(rest);
|
|
426
|
+
if (implSelf) {
|
|
427
|
+
return { name: implSelf[1], kind: 'impl', isPythonIndent: false, isStatementNoBody: false };
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
// TS/Go/Rust/Swift type / typealias
|
|
431
|
+
m = /^(?:type|typealias)\s+([A-Za-z_$][\w$]*)\b(?:\s*<[^>\n]{0,80}>)?\s*(struct|interface)?/.exec(rest);
|
|
432
|
+
if (m) {
|
|
433
|
+
const sub = m[2];
|
|
434
|
+
const kind = sub === 'struct' ? 'struct' : sub === 'interface' ? 'interface' : 'type';
|
|
435
|
+
return {
|
|
436
|
+
name: m[1],
|
|
437
|
+
kind,
|
|
438
|
+
isPythonIndent: false,
|
|
439
|
+
isStatementNoBody: !rest.includes('{'),
|
|
440
|
+
};
|
|
441
|
+
}
|
|
442
|
+
// TS/JS `const|let|var name = [async] (...) =>` or `= [async] function`
|
|
443
|
+
m = /^(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=\n]{1,100})?=\s*(?:async\s+)?(?:(?:\([^)\n]{0,160}\)|[A-Za-z_$][\w$]*)\s*=>|function\b|class\b)/.exec(rest);
|
|
444
|
+
if (m) {
|
|
445
|
+
return {
|
|
446
|
+
name: m[1],
|
|
447
|
+
kind: 'function',
|
|
448
|
+
isPythonIndent: false,
|
|
449
|
+
isStatementNoBody: !rest.includes('{'),
|
|
450
|
+
};
|
|
451
|
+
}
|
|
452
|
+
// Java method: modifiers + optional generic `<T>` + return type + name(
|
|
453
|
+
if (hadModifier) {
|
|
454
|
+
const firstWord = /^([A-Za-z_$][\w$]*)\b/.exec(rest)?.[1];
|
|
455
|
+
const jm = /^(?:<[^>\n]{1,60}>\s+)?[A-Za-z_$][\w$.[\]?]*(?:<[^>\n]{1,60}>)?(?:\[\])*\s+([A-Za-z_$][\w$]*)\s*\(/.exec(rest);
|
|
456
|
+
if ((!firstWord || !CONTROL_KEYWORDS.has(firstWord)) && jm && !CONTROL_KEYWORDS.has(jm[1])) {
|
|
457
|
+
return {
|
|
458
|
+
name: jm[1],
|
|
459
|
+
kind: 'method',
|
|
460
|
+
isPythonIndent: false,
|
|
461
|
+
isStatementNoBody: !rest.includes('{') && rest.endsWith(';'),
|
|
462
|
+
};
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
// TS/JS/Java class method (`async storePage(...) {` or `storePage(...): MmuPage {`)
|
|
466
|
+
if (insideBraceClass || hadModifier) {
|
|
467
|
+
const mm = /^(?:(?:get|set)\s+)?([A-Za-z_$][\w$]*)\s*(?:<[^>\n]{0,60}>)?\s*\(/.exec(rest);
|
|
468
|
+
if (mm && (!CONTROL_KEYWORDS.has(mm[1]) || mm[1] === 'constructor')) {
|
|
469
|
+
if (hadModifier || rest.includes('{') || /\)\s*(?::\s*[^\n{;]{1,80})?\s*\{/.test(rest)) {
|
|
470
|
+
return {
|
|
471
|
+
name: mm[1],
|
|
472
|
+
kind: 'method',
|
|
473
|
+
isPythonIndent: false,
|
|
474
|
+
isStatementNoBody: !rest.includes('{') && rest.endsWith(';'),
|
|
475
|
+
};
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
return null;
|
|
480
|
+
}
|
|
481
|
+
const ERROR_TOKEN_RE = /\b([A-Z][A-Za-z0-9]*(?:Error|Exception|Fault|Panic)|ERR_[A-Z0-9_]{2,}|E(?:NOENT|ACCES|PERM|CONNREFUSED|TIMEDOUT|ADDRINUSE|PIPE|ISDIR|NOSPC|EXIST|NOTDIR|BADF|INVAL|AGAIN|BUSY|IO))\b/;
|
|
482
|
+
const JS_STACK_FRAME_RE = /^\s*at\s+(?:async\s+)?([A-Za-z_$][\w$.<>]*)\s+\(/;
|
|
483
|
+
const PY_STACK_FRAME_RE = /^\s*File\s+"[^"\n]+",\s*line\s+\d+,\s*in\s+([A-Za-z_]\w*)/;
|
|
484
|
+
/** Extract error names and stack frame anchors from text with 1-based line numbers. */
|
|
485
|
+
export function extractErrorAnchors(text) {
|
|
486
|
+
if (!text)
|
|
487
|
+
return [];
|
|
488
|
+
const lines = text.split('\n');
|
|
489
|
+
const allowColon = detectColonGutterMode(lines);
|
|
490
|
+
const out = [];
|
|
491
|
+
const seenLineName = new Set();
|
|
492
|
+
for (let i = 0; i < lines.length; i++) {
|
|
493
|
+
const raw = stripLineGutter(lines[i], allowColon);
|
|
494
|
+
const head = raw.length > MAX_LINE_SCAN_CHARS ? raw.slice(0, MAX_LINE_SCAN_CHARS) : raw;
|
|
495
|
+
const lineNum = i + 1;
|
|
496
|
+
const errMatch = ERROR_TOKEN_RE.exec(head);
|
|
497
|
+
if (errMatch) {
|
|
498
|
+
const name = errMatch[1];
|
|
499
|
+
const k = `${lineNum}\0${name}`;
|
|
500
|
+
if (!seenLineName.has(k)) {
|
|
501
|
+
seenLineName.add(k);
|
|
502
|
+
out.push({ name, kind: 'error', startLine: lineNum, endLine: lineNum });
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
const jsFrame = JS_STACK_FRAME_RE.exec(head);
|
|
506
|
+
if (jsFrame) {
|
|
507
|
+
const full = jsFrame[1];
|
|
508
|
+
const short = full.includes('.') ? full.slice(full.lastIndexOf('.') + 1) : full;
|
|
509
|
+
if (short && short !== '<anonymous>') {
|
|
510
|
+
const k = `${lineNum}\0${short}`;
|
|
511
|
+
if (!seenLineName.has(k)) {
|
|
512
|
+
seenLineName.add(k);
|
|
513
|
+
out.push({ name: short, kind: 'anchor', startLine: lineNum, endLine: lineNum });
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
const pyFrame = PY_STACK_FRAME_RE.exec(head);
|
|
518
|
+
if (pyFrame) {
|
|
519
|
+
const name = pyFrame[1];
|
|
520
|
+
if (name && name !== '<module>') {
|
|
521
|
+
const k = `${lineNum}\0${name}`;
|
|
522
|
+
if (!seenLineName.has(k)) {
|
|
523
|
+
seenLineName.add(k);
|
|
524
|
+
out.push({ name, kind: 'anchor', startLine: lineNum, endLine: lineNum });
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
return out;
|
|
530
|
+
}
|
|
531
|
+
function leadingIndentWidth(line) {
|
|
532
|
+
let width = 0;
|
|
533
|
+
for (let i = 0; i < line.length; i++) {
|
|
534
|
+
const c = line.charCodeAt(i);
|
|
535
|
+
if (c === 32)
|
|
536
|
+
width += 1;
|
|
537
|
+
else if (c === 9)
|
|
538
|
+
width += 4;
|
|
539
|
+
else
|
|
540
|
+
break;
|
|
541
|
+
}
|
|
542
|
+
return width;
|
|
543
|
+
}
|
|
544
|
+
/** Single-pass O(L) scanner for braces/parens ignoring strings and comments. */
|
|
545
|
+
function scanLineDelimiters(line, inBlockComment, allowHashComment = false) {
|
|
546
|
+
let openBraces = 0;
|
|
547
|
+
let closeBraces = 0;
|
|
548
|
+
let parenDelta = 0;
|
|
549
|
+
let inBC = inBlockComment;
|
|
550
|
+
let quote = 0; // 34=" 39=' 96=`
|
|
551
|
+
let escaped = false;
|
|
552
|
+
let firstBraceDepthDelta = false;
|
|
553
|
+
let hasSemicolonAtBase = false;
|
|
554
|
+
let localDepth = 0;
|
|
555
|
+
for (let i = 0; i < line.length; i++) {
|
|
556
|
+
const c = line.charCodeAt(i);
|
|
557
|
+
const next = i + 1 < line.length ? line.charCodeAt(i + 1) : 0;
|
|
558
|
+
if (inBC) {
|
|
559
|
+
if (c === 42 && next === 47) {
|
|
560
|
+
inBC = false;
|
|
561
|
+
i += 1;
|
|
562
|
+
}
|
|
563
|
+
continue;
|
|
564
|
+
}
|
|
565
|
+
if (quote !== 0) {
|
|
566
|
+
if (escaped) {
|
|
567
|
+
escaped = false;
|
|
568
|
+
}
|
|
569
|
+
else if (c === 92) {
|
|
570
|
+
escaped = true;
|
|
571
|
+
}
|
|
572
|
+
else if (c === quote) {
|
|
573
|
+
quote = 0;
|
|
574
|
+
}
|
|
575
|
+
continue;
|
|
576
|
+
}
|
|
577
|
+
if (c === 47 && next === 47)
|
|
578
|
+
break; // // comment
|
|
579
|
+
// Treat `#` as comment only in Python/shell context (not JS/TS `#private` or Rust `#[attr]`)
|
|
580
|
+
if (c === 35 && (allowHashComment || (next === 32 && i === 0)))
|
|
581
|
+
break;
|
|
582
|
+
if (c === 47 && next === 42) {
|
|
583
|
+
inBC = true;
|
|
584
|
+
i += 1;
|
|
585
|
+
continue;
|
|
586
|
+
}
|
|
587
|
+
if (c === 34 || c === 39 || c === 96) {
|
|
588
|
+
quote = c;
|
|
589
|
+
continue;
|
|
590
|
+
}
|
|
591
|
+
if (c === 123) {
|
|
592
|
+
openBraces += 1;
|
|
593
|
+
localDepth += 1;
|
|
594
|
+
if (localDepth > 0)
|
|
595
|
+
firstBraceDepthDelta = true;
|
|
596
|
+
}
|
|
597
|
+
else if (c === 125) {
|
|
598
|
+
closeBraces += 1;
|
|
599
|
+
localDepth -= 1;
|
|
600
|
+
}
|
|
601
|
+
else if (c === 40) {
|
|
602
|
+
parenDelta += 1;
|
|
603
|
+
}
|
|
604
|
+
else if (c === 41) {
|
|
605
|
+
parenDelta -= 1;
|
|
606
|
+
}
|
|
607
|
+
else if (c === 59 && localDepth === 0) {
|
|
608
|
+
hasSemicolonAtBase = true;
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
return {
|
|
612
|
+
openBraces,
|
|
613
|
+
closeBraces,
|
|
614
|
+
parenDelta,
|
|
615
|
+
firstBraceDepthDelta,
|
|
616
|
+
hasSemicolonAtBase,
|
|
617
|
+
inBlockCommentOut: inBC,
|
|
618
|
+
};
|
|
619
|
+
}
|
|
620
|
+
/**
|
|
621
|
+
* O(N) line scanner extracting declarations (TS/JS, Python, Go, Rust, Swift, Java)
|
|
622
|
+
* and error/stack anchors with 1-based `{ name, kind, startLine, endLine }`.
|
|
623
|
+
*/
|
|
624
|
+
export function extractSymbolSpans(text) {
|
|
625
|
+
if (!text)
|
|
626
|
+
return [];
|
|
627
|
+
const lines = text.split('\n');
|
|
628
|
+
const allowColon = detectColonGutterMode(lines);
|
|
629
|
+
const spans = [];
|
|
630
|
+
const braceStack = [];
|
|
631
|
+
const indentStack = [];
|
|
632
|
+
let openBraceClassCount = 0;
|
|
633
|
+
let waitingIndentCount = 0;
|
|
634
|
+
let pendingBraceDecl = null;
|
|
635
|
+
let braceDepth = 0;
|
|
636
|
+
let parenDepth = 0;
|
|
637
|
+
let inBlockComment = false;
|
|
638
|
+
let hashCommentMode = false;
|
|
639
|
+
let lastNonEmptyLine = 1;
|
|
640
|
+
for (let i = 0; i < lines.length; i++) {
|
|
641
|
+
const lineNum = i + 1;
|
|
642
|
+
const stripped = stripLineGutter(lines[i], allowColon);
|
|
643
|
+
const trimmed = stripped.trim();
|
|
644
|
+
const indent = leadingIndentWidth(stripped);
|
|
645
|
+
if (!hashCommentMode &&
|
|
646
|
+
trimmed.length > 0 &&
|
|
647
|
+
(/^#!.*(?:python|bash|sh|zsh)\b/.test(trimmed) ||
|
|
648
|
+
/^(?:async\s+)?def\s+\w+\s*\(/.test(trimmed) ||
|
|
649
|
+
/^class\s+[A-Za-z_]\w*(?:\([^)\n]*\))?\s*:\s*(?:#.*)?$/.test(trimmed))) {
|
|
650
|
+
hashCommentMode = true;
|
|
651
|
+
}
|
|
652
|
+
// Close Python indent-scoped blocks before processing new non-empty, non-comment line (O(1) amortized).
|
|
653
|
+
if (trimmed.length > 0 && !trimmed.startsWith('#')) {
|
|
654
|
+
while (indentStack.length > 0) {
|
|
655
|
+
const blk = indentStack[indentStack.length - 1];
|
|
656
|
+
if (blk.waitingForSignatureClose || indent > blk.indent)
|
|
657
|
+
break;
|
|
658
|
+
indentStack.pop();
|
|
659
|
+
spans[blk.spanIdx].endLine = Math.max(spans[blk.spanIdx].startLine, lastNonEmptyLine);
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
const insideBraceClass = openBraceClassCount > 0;
|
|
663
|
+
const depthBefore = braceDepth;
|
|
664
|
+
let decl = null;
|
|
665
|
+
if (!inBlockComment && trimmed.length > 0) {
|
|
666
|
+
decl = parseDeclarationLine(stripped, insideBraceClass);
|
|
667
|
+
if (decl && !decl.isPythonIndent && stripped.includes('{')) {
|
|
668
|
+
hashCommentMode = false;
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
const delta = scanLineDelimiters(stripped, inBlockComment, hashCommentMode);
|
|
672
|
+
inBlockComment = delta.inBlockCommentOut;
|
|
673
|
+
braceDepth = Math.max(0, braceDepth + delta.openBraces - delta.closeBraces);
|
|
674
|
+
parenDepth = Math.max(0, parenDepth + delta.parenDelta);
|
|
675
|
+
// Resolve any pending multi-line signature waiting for `{`
|
|
676
|
+
if (pendingBraceDecl) {
|
|
677
|
+
if (delta.openBraces > 0) {
|
|
678
|
+
const blk = {
|
|
679
|
+
spanIdx: pendingBraceDecl.spanIdx,
|
|
680
|
+
targetDepth: pendingBraceDecl.baseDepth,
|
|
681
|
+
indent: 0,
|
|
682
|
+
isClassScope: pendingBraceDecl.isClassScope,
|
|
683
|
+
waitingForSignatureClose: false,
|
|
684
|
+
};
|
|
685
|
+
if (braceDepth <= blk.targetDepth) {
|
|
686
|
+
spans[blk.spanIdx].endLine = lineNum;
|
|
687
|
+
}
|
|
688
|
+
else {
|
|
689
|
+
braceStack.push(blk);
|
|
690
|
+
if (blk.isClassScope)
|
|
691
|
+
openBraceClassCount++;
|
|
692
|
+
}
|
|
693
|
+
pendingBraceDecl = null;
|
|
694
|
+
}
|
|
695
|
+
else if (delta.hasSemicolonAtBase && parenDepth === 0) {
|
|
696
|
+
spans[pendingBraceDecl.spanIdx].endLine = lineNum;
|
|
697
|
+
pendingBraceDecl = null;
|
|
698
|
+
}
|
|
699
|
+
else if (i - pendingBraceDecl.startIdx > 6) {
|
|
700
|
+
pendingBraceDecl = null;
|
|
701
|
+
}
|
|
702
|
+
}
|
|
703
|
+
// Check if an indent block's multi-line signature just finished (`):`)
|
|
704
|
+
if (waitingIndentCount > 0 && parenDepth === 0 && /:\s*(?:#.*)?$/.test(trimmed)) {
|
|
705
|
+
for (let s = indentStack.length - 1; s >= 0; s--) {
|
|
706
|
+
const blk = indentStack[s];
|
|
707
|
+
if (blk.waitingForSignatureClose) {
|
|
708
|
+
blk.waitingForSignatureClose = false;
|
|
709
|
+
waitingIndentCount--;
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
}
|
|
713
|
+
// Register new declaration found on this line
|
|
714
|
+
if (decl) {
|
|
715
|
+
const spanIdx = spans.length;
|
|
716
|
+
spans.push({
|
|
717
|
+
name: decl.name,
|
|
718
|
+
kind: decl.kind,
|
|
719
|
+
startLine: lineNum,
|
|
720
|
+
endLine: lineNum,
|
|
721
|
+
});
|
|
722
|
+
const isClassScope = decl.kind === 'class' ||
|
|
723
|
+
decl.kind === 'struct' ||
|
|
724
|
+
decl.kind === 'interface' ||
|
|
725
|
+
decl.kind === 'trait' ||
|
|
726
|
+
decl.kind === 'impl' ||
|
|
727
|
+
decl.kind === 'protocol' ||
|
|
728
|
+
decl.kind === 'actor';
|
|
729
|
+
if (decl.isPythonIndent) {
|
|
730
|
+
const waiting = parenDepth > 0 || !/:\s*(?:#.*)?$/.test(trimmed);
|
|
731
|
+
if (waiting)
|
|
732
|
+
waitingIndentCount++;
|
|
733
|
+
indentStack.push({
|
|
734
|
+
spanIdx,
|
|
735
|
+
targetDepth: 0,
|
|
736
|
+
indent,
|
|
737
|
+
isClassScope,
|
|
738
|
+
waitingForSignatureClose: waiting,
|
|
739
|
+
});
|
|
740
|
+
}
|
|
741
|
+
else if (delta.openBraces > 0) {
|
|
742
|
+
if (braceDepth <= depthBefore) {
|
|
743
|
+
// Opened and closed on same line (e.g. `function noop() {}`)
|
|
744
|
+
spans[spanIdx].endLine = lineNum;
|
|
745
|
+
}
|
|
746
|
+
else {
|
|
747
|
+
braceStack.push({
|
|
748
|
+
spanIdx,
|
|
749
|
+
targetDepth: depthBefore,
|
|
750
|
+
indent,
|
|
751
|
+
isClassScope,
|
|
752
|
+
waitingForSignatureClose: false,
|
|
753
|
+
});
|
|
754
|
+
if (isClassScope)
|
|
755
|
+
openBraceClassCount++;
|
|
756
|
+
}
|
|
757
|
+
}
|
|
758
|
+
else if (!decl.isStatementNoBody) {
|
|
759
|
+
pendingBraceDecl = {
|
|
760
|
+
spanIdx,
|
|
761
|
+
baseDepth: depthBefore,
|
|
762
|
+
startIdx: i,
|
|
763
|
+
isClassScope,
|
|
764
|
+
};
|
|
765
|
+
}
|
|
766
|
+
}
|
|
767
|
+
// Close brace-scoped blocks whose brace depth returned to targetDepth (monotonic stack)
|
|
768
|
+
if (delta.closeBraces > 0) {
|
|
769
|
+
while (braceStack.length > 0 && braceDepth <= braceStack[braceStack.length - 1].targetDepth) {
|
|
770
|
+
const blk = braceStack.pop();
|
|
771
|
+
if (blk.isClassScope)
|
|
772
|
+
openBraceClassCount--;
|
|
773
|
+
spans[blk.spanIdx].endLine = lineNum;
|
|
774
|
+
}
|
|
775
|
+
}
|
|
776
|
+
if (trimmed.length > 0) {
|
|
777
|
+
lastNonEmptyLine = lineNum;
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
// Close any open blocks reaching EOF
|
|
781
|
+
const eofLine = Math.max(1, lines.length);
|
|
782
|
+
for (const blk of indentStack) {
|
|
783
|
+
spans[blk.spanIdx].endLine = Math.max(spans[blk.spanIdx].startLine, lastNonEmptyLine);
|
|
784
|
+
}
|
|
785
|
+
for (const blk of braceStack) {
|
|
786
|
+
spans[blk.spanIdx].endLine = eofLine;
|
|
787
|
+
}
|
|
788
|
+
// Append error / stack anchors (deduped against declaration lines with identical name)
|
|
789
|
+
const declKeys = new Set(spans.map((s) => `${s.startLine}\0${s.name}`));
|
|
790
|
+
for (const anchor of extractErrorAnchors(text)) {
|
|
791
|
+
if (!declKeys.has(`${anchor.startLine}\0${anchor.name}`)) {
|
|
792
|
+
spans.push(anchor);
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
return spans.sort((a, b) => a.startLine - b.startLine || a.endLine - b.endLine);
|
|
796
|
+
}
|
|
797
|
+
const SECRET_PEM_RE = /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----/;
|
|
798
|
+
const SECRET_BEARER_RE = /\bBearer\s+[A-Za-z0-9._~+/=-]{20,}/;
|
|
799
|
+
const SECRET_TOKEN_PREFIX_RE = /\b(?:sk-(?:proj-|ant-)?[A-Za-z0-9_-]{20,}|gh[pousr]_[A-Za-z0-9]{30,}|AKIA[0-9A-Z]{16})\b/;
|
|
800
|
+
const SECRET_ENV_ASSIGN_RE = /^[ \t]*(?:export[ \t]+)?[A-Z0-9_]*(?:SECRET|TOKEN|API_KEY|PASSWORD|PRIVATE_KEY|ACCESS_KEY)[A-Z0-9_]*[ \t]*=[ \t]*["']?[^\s"'#]{8,}/m;
|
|
801
|
+
/** Skip persisting raw pages containing high-confidence credentials or private keys. */
|
|
802
|
+
function containsHighConfidenceSecret(text) {
|
|
803
|
+
return (SECRET_PEM_RE.test(text) ||
|
|
804
|
+
SECRET_BEARER_RE.test(text) ||
|
|
805
|
+
SECRET_TOKEN_PREFIX_RE.test(text) ||
|
|
806
|
+
SECRET_ENV_ASSIGN_RE.test(text));
|
|
807
|
+
}
|
|
808
|
+
function emptyStats() {
|
|
809
|
+
return {
|
|
810
|
+
pagesStored: 0,
|
|
811
|
+
pagesEvicted: 0,
|
|
812
|
+
totalRawChars: 0,
|
|
813
|
+
activePages: 0,
|
|
814
|
+
activeBytes: 0,
|
|
815
|
+
tailHydrations: 0,
|
|
816
|
+
tailHydrationTokens: 0,
|
|
817
|
+
markovFolds: 0,
|
|
818
|
+
markovFoldedChars: 0,
|
|
819
|
+
skillsStubbed: 0,
|
|
820
|
+
skillStubSavedChars: 0,
|
|
821
|
+
densityPrunedBlocks: 0,
|
|
822
|
+
densityPrunedChars: 0,
|
|
823
|
+
};
|
|
824
|
+
}
|
|
825
|
+
function summarizePage(page) {
|
|
826
|
+
const { rawText, ...rest } = page;
|
|
827
|
+
return { ...rest, chars: rawText.length };
|
|
828
|
+
}
|
|
829
|
+
function collectIndexKeys(symbols, filePath, extraSymbols) {
|
|
830
|
+
const keys = new Set();
|
|
831
|
+
for (const sym of symbols) {
|
|
832
|
+
const low = sym.name.trim().toLowerCase();
|
|
833
|
+
if (low)
|
|
834
|
+
keys.add(low);
|
|
835
|
+
}
|
|
836
|
+
if (filePath) {
|
|
837
|
+
const norm = filePath.replace(/\\/g, '/').toLowerCase();
|
|
838
|
+
keys.add(norm);
|
|
839
|
+
const base = pathBasename(norm);
|
|
840
|
+
if (base)
|
|
841
|
+
keys.add(base);
|
|
842
|
+
}
|
|
843
|
+
if (extraSymbols) {
|
|
844
|
+
for (const sym of extraSymbols) {
|
|
845
|
+
const low = sym.trim().toLowerCase();
|
|
846
|
+
if (low)
|
|
847
|
+
keys.add(low);
|
|
848
|
+
}
|
|
849
|
+
}
|
|
850
|
+
return [...keys];
|
|
851
|
+
}
|
|
852
|
+
export class ContextPageStore {
|
|
853
|
+
maxPages;
|
|
854
|
+
maxBytes;
|
|
855
|
+
debounceMs;
|
|
856
|
+
/** LRU map keyed by `${sessionKey}\0${id}` (insertion order = LRU -> MRU). */
|
|
857
|
+
entries = new Map();
|
|
858
|
+
/** Fast pageId -> latest entryKey lookup (one pageId can exist under multiple sessions). */
|
|
859
|
+
keysByPageId = new Map();
|
|
860
|
+
/** Inverted index: lowercased symbol / basename -> page IDs. */
|
|
861
|
+
symbolIndex = new Map();
|
|
862
|
+
/** Session index: sessionKey -> page IDs. */
|
|
863
|
+
sessionIndex = new Map();
|
|
864
|
+
totalBytes = 0;
|
|
865
|
+
stats = emptyStats();
|
|
866
|
+
persistence;
|
|
867
|
+
saveTimer;
|
|
868
|
+
dirty = false;
|
|
869
|
+
/** Per-session Context-TLB leases: sessionKey -> (pageId -> { startLine, endLine, turn }). */
|
|
870
|
+
hydrationTlb = new Map();
|
|
871
|
+
/** Per-session logical hydration turn counter (bounded to 512 LRU sessions). */
|
|
872
|
+
hydrationTurn = new Map();
|
|
873
|
+
constructor(options = {}) {
|
|
874
|
+
this.maxPages = Math.max(1, Math.floor(options.maxPages ?? DEFAULT_MAX_PAGES));
|
|
875
|
+
this.maxBytes = Math.max(1, Math.floor(options.maxBytes ?? DEFAULT_MAX_BYTES));
|
|
876
|
+
this.debounceMs = Math.max(0, Math.floor(options.debounceMs ?? DEFAULT_DEBOUNCE_MS));
|
|
877
|
+
if (options.persistence) {
|
|
878
|
+
this.configurePersistence(options.persistence);
|
|
879
|
+
}
|
|
880
|
+
}
|
|
881
|
+
/** Attach or detach persistence adapter, restoring saved pages fail-open. */
|
|
882
|
+
configurePersistence(adapter) {
|
|
883
|
+
this.flush();
|
|
884
|
+
this.persistence = adapter;
|
|
885
|
+
if (!adapter)
|
|
886
|
+
return 0;
|
|
887
|
+
let raw;
|
|
888
|
+
try {
|
|
889
|
+
raw = adapter.load();
|
|
890
|
+
}
|
|
891
|
+
catch {
|
|
892
|
+
return 0;
|
|
893
|
+
}
|
|
894
|
+
return this.restore(raw);
|
|
895
|
+
}
|
|
896
|
+
scheduleSave() {
|
|
897
|
+
if (!this.persistence)
|
|
898
|
+
return;
|
|
899
|
+
this.dirty = true;
|
|
900
|
+
if (this.saveTimer)
|
|
901
|
+
return;
|
|
902
|
+
this.saveTimer = setTimeout(() => {
|
|
903
|
+
this.saveTimer = undefined;
|
|
904
|
+
this.flush();
|
|
905
|
+
}, this.debounceMs);
|
|
906
|
+
this.saveTimer.unref?.();
|
|
907
|
+
}
|
|
908
|
+
/** Immediately write pending updates to the configured persistence adapter. */
|
|
909
|
+
flush() {
|
|
910
|
+
if (this.saveTimer) {
|
|
911
|
+
clearTimeout(this.saveTimer);
|
|
912
|
+
this.saveTimer = undefined;
|
|
913
|
+
}
|
|
914
|
+
if (!this.persistence || !this.dirty)
|
|
915
|
+
return false;
|
|
916
|
+
this.dirty = false;
|
|
917
|
+
try {
|
|
918
|
+
this.persistence.save(this.serialize());
|
|
919
|
+
return true;
|
|
920
|
+
}
|
|
921
|
+
catch {
|
|
922
|
+
return false;
|
|
923
|
+
}
|
|
924
|
+
}
|
|
925
|
+
/** Serialize current store state in LRU order (oldest first), skipping expired or secret-bearing pages. */
|
|
926
|
+
serialize(nowMs = Date.now()) {
|
|
927
|
+
const pages = [];
|
|
928
|
+
for (const entry of this.entries.values()) {
|
|
929
|
+
const p = entry.page;
|
|
930
|
+
const createdAtMs = p.createdAtMs > 0 ? p.createdAtMs : nowMs;
|
|
931
|
+
if (nowMs - createdAtMs > PERSIST_MAX_IDLE_MS)
|
|
932
|
+
continue;
|
|
933
|
+
if (containsHighConfidenceSecret(p.rawText))
|
|
934
|
+
continue;
|
|
935
|
+
pages.push({
|
|
936
|
+
id: p.id,
|
|
937
|
+
sessionKey: p.sessionKey,
|
|
938
|
+
refId: p.refId,
|
|
939
|
+
...(p.toolName !== undefined ? { toolName: p.toolName } : {}),
|
|
940
|
+
...(p.filePath !== undefined ? { filePath: p.filePath } : {}),
|
|
941
|
+
createdAtMs,
|
|
942
|
+
rawText: p.rawText,
|
|
943
|
+
lineCount: p.lineCount,
|
|
944
|
+
symbols: [...p.symbols],
|
|
945
|
+
factTokens: [...p.factTokens],
|
|
946
|
+
});
|
|
947
|
+
}
|
|
948
|
+
const payload = {
|
|
949
|
+
format: PERSIST_FORMAT,
|
|
950
|
+
savedAtMs: nowMs,
|
|
951
|
+
pages,
|
|
952
|
+
stats: { ...this.stats },
|
|
953
|
+
};
|
|
954
|
+
return JSON.stringify(payload);
|
|
955
|
+
}
|
|
956
|
+
/** Restore serialized pages into the store (in-memory entries win on collision; drops expired or secret-bearing records). */
|
|
957
|
+
restore(json, nowMs = Date.now()) {
|
|
958
|
+
if (!json)
|
|
959
|
+
return 0;
|
|
960
|
+
let parsed;
|
|
961
|
+
try {
|
|
962
|
+
parsed = JSON.parse(json);
|
|
963
|
+
}
|
|
964
|
+
catch {
|
|
965
|
+
return 0;
|
|
966
|
+
}
|
|
967
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
|
|
968
|
+
return 0;
|
|
969
|
+
const obj = parsed;
|
|
970
|
+
if (obj.format !== PERSIST_FORMAT || !Array.isArray(obj.pages))
|
|
971
|
+
return 0;
|
|
972
|
+
let restored = 0;
|
|
973
|
+
for (const rawRec of obj.pages) {
|
|
974
|
+
if (!rawRec || typeof rawRec !== 'object' || Array.isArray(rawRec))
|
|
975
|
+
continue;
|
|
976
|
+
const r = rawRec;
|
|
977
|
+
if (typeof r.rawText !== 'string' || typeof r.sessionKey !== 'string' || !r.sessionKey)
|
|
978
|
+
continue;
|
|
979
|
+
const createdAtMs = typeof r.createdAtMs === 'number' && Number.isFinite(r.createdAtMs) ? r.createdAtMs : 0;
|
|
980
|
+
if (createdAtMs <= 0 || nowMs - createdAtMs > PERSIST_MAX_IDLE_MS)
|
|
981
|
+
continue;
|
|
982
|
+
if (containsHighConfidenceSecret(r.rawText))
|
|
983
|
+
continue;
|
|
984
|
+
const id = typeof r.id === 'string' && /^pg_[0-9a-f]{8,16}$/.test(r.id) ? r.id : pageIdForText(r.rawText);
|
|
985
|
+
const entryKey = `${r.sessionKey}\0${id}`;
|
|
986
|
+
if (this.entries.has(entryKey))
|
|
987
|
+
continue;
|
|
988
|
+
const bytes = utf8ByteLength(r.rawText);
|
|
989
|
+
if (bytes > this.maxBytes)
|
|
990
|
+
continue;
|
|
991
|
+
const filePath = typeof r.filePath === 'string' && r.filePath ? r.filePath : inferFilePath(r.rawText, r.refId);
|
|
992
|
+
const symbols = Array.isArray(r.symbols)
|
|
993
|
+
? r.symbols.filter((s) => Boolean(s) &&
|
|
994
|
+
typeof s.name === 'string' &&
|
|
995
|
+
typeof s.kind === 'string' &&
|
|
996
|
+
typeof s.startLine === 'number' &&
|
|
997
|
+
typeof s.endLine === 'number')
|
|
998
|
+
: extractSymbolSpans(r.rawText);
|
|
999
|
+
const factTokens = Array.isArray(r.factTokens)
|
|
1000
|
+
? r.factTokens.filter((t) => typeof t === 'string')
|
|
1001
|
+
: extractFactSheetTokens(r.rawText);
|
|
1002
|
+
const page = {
|
|
1003
|
+
id,
|
|
1004
|
+
sessionKey: r.sessionKey,
|
|
1005
|
+
refId: typeof r.refId === 'string' && r.refId ? r.refId : 'restored',
|
|
1006
|
+
...(typeof r.toolName === 'string' && r.toolName ? { toolName: r.toolName } : {}),
|
|
1007
|
+
...(filePath !== undefined ? { filePath } : {}),
|
|
1008
|
+
createdAtMs,
|
|
1009
|
+
rawText: r.rawText,
|
|
1010
|
+
lineCount: typeof r.lineCount === 'number' && Number.isFinite(r.lineCount) && r.lineCount >= 0
|
|
1011
|
+
? r.lineCount
|
|
1012
|
+
: countLines(r.rawText),
|
|
1013
|
+
symbols,
|
|
1014
|
+
factTokens,
|
|
1015
|
+
};
|
|
1016
|
+
this.insertEntry(entryKey, page, bytes, collectIndexKeys(symbols, filePath), false);
|
|
1017
|
+
restored += 1;
|
|
1018
|
+
}
|
|
1019
|
+
if (obj.stats && typeof obj.stats === 'object') {
|
|
1020
|
+
const s = obj.stats;
|
|
1021
|
+
const num = (v, cur) => (typeof v === 'number' && Number.isFinite(v) && v >= 0 ? Math.max(cur, v) : cur);
|
|
1022
|
+
this.stats.pagesStored = num(s.pagesStored, this.stats.pagesStored);
|
|
1023
|
+
this.stats.pagesEvicted = num(s.pagesEvicted, this.stats.pagesEvicted);
|
|
1024
|
+
this.stats.totalRawChars = num(s.totalRawChars, this.stats.totalRawChars);
|
|
1025
|
+
this.stats.tailHydrations = num(s.tailHydrations, this.stats.tailHydrations);
|
|
1026
|
+
this.stats.tailHydrationTokens = num(s.tailHydrationTokens, this.stats.tailHydrationTokens);
|
|
1027
|
+
this.stats.markovFolds = num(s.markovFolds, this.stats.markovFolds);
|
|
1028
|
+
this.stats.markovFoldedChars = num(s.markovFoldedChars, this.stats.markovFoldedChars);
|
|
1029
|
+
this.stats.skillsStubbed = num(s.skillsStubbed, this.stats.skillsStubbed);
|
|
1030
|
+
this.stats.skillStubSavedChars = num(s.skillStubSavedChars, this.stats.skillStubSavedChars);
|
|
1031
|
+
this.stats.densityPrunedBlocks = num(s.densityPrunedBlocks, this.stats.densityPrunedBlocks);
|
|
1032
|
+
this.stats.densityPrunedChars = num(s.densityPrunedChars, this.stats.densityPrunedChars);
|
|
1033
|
+
}
|
|
1034
|
+
return restored;
|
|
1035
|
+
}
|
|
1036
|
+
touchEntry(entry) {
|
|
1037
|
+
this.entries.delete(entry.key);
|
|
1038
|
+
this.entries.set(entry.key, entry);
|
|
1039
|
+
}
|
|
1040
|
+
addIndexes(entry) {
|
|
1041
|
+
const { page, key, indexKeys } = entry;
|
|
1042
|
+
let pidKeys = this.keysByPageId.get(page.id);
|
|
1043
|
+
if (!pidKeys) {
|
|
1044
|
+
pidKeys = new Set();
|
|
1045
|
+
this.keysByPageId.set(page.id, pidKeys);
|
|
1046
|
+
}
|
|
1047
|
+
pidKeys.add(key);
|
|
1048
|
+
let sessPages = this.sessionIndex.get(page.sessionKey);
|
|
1049
|
+
if (!sessPages) {
|
|
1050
|
+
sessPages = new Set();
|
|
1051
|
+
this.sessionIndex.set(page.sessionKey, sessPages);
|
|
1052
|
+
}
|
|
1053
|
+
sessPages.add(page.id);
|
|
1054
|
+
for (const idxKey of indexKeys) {
|
|
1055
|
+
let set = this.symbolIndex.get(idxKey);
|
|
1056
|
+
if (!set) {
|
|
1057
|
+
set = new Set();
|
|
1058
|
+
this.symbolIndex.set(idxKey, set);
|
|
1059
|
+
}
|
|
1060
|
+
set.add(page.id);
|
|
1061
|
+
}
|
|
1062
|
+
}
|
|
1063
|
+
removeIndexes(entry) {
|
|
1064
|
+
const { page, key, indexKeys } = entry;
|
|
1065
|
+
const pidKeys = this.keysByPageId.get(page.id);
|
|
1066
|
+
let pageIdStillExists = false;
|
|
1067
|
+
if (pidKeys) {
|
|
1068
|
+
pidKeys.delete(key);
|
|
1069
|
+
if (pidKeys.size === 0) {
|
|
1070
|
+
this.keysByPageId.delete(page.id);
|
|
1071
|
+
}
|
|
1072
|
+
else {
|
|
1073
|
+
pageIdStillExists = true;
|
|
1074
|
+
}
|
|
1075
|
+
}
|
|
1076
|
+
const sessPages = this.sessionIndex.get(page.sessionKey);
|
|
1077
|
+
if (sessPages) {
|
|
1078
|
+
sessPages.delete(page.id);
|
|
1079
|
+
if (sessPages.size === 0)
|
|
1080
|
+
this.sessionIndex.delete(page.sessionKey);
|
|
1081
|
+
}
|
|
1082
|
+
for (const idxKey of indexKeys) {
|
|
1083
|
+
const set = this.symbolIndex.get(idxKey);
|
|
1084
|
+
if (!set)
|
|
1085
|
+
continue;
|
|
1086
|
+
if (!pageIdStillExists) {
|
|
1087
|
+
set.delete(page.id);
|
|
1088
|
+
}
|
|
1089
|
+
else {
|
|
1090
|
+
// Only keep page.id under idxKey if another remaining entry with page.id owns idxKey
|
|
1091
|
+
let stillOwned = false;
|
|
1092
|
+
for (const otherKey of pidKeys) {
|
|
1093
|
+
const other = this.entries.get(otherKey);
|
|
1094
|
+
if (other && other.indexKeys.includes(idxKey)) {
|
|
1095
|
+
stillOwned = true;
|
|
1096
|
+
break;
|
|
1097
|
+
}
|
|
1098
|
+
}
|
|
1099
|
+
if (!stillOwned)
|
|
1100
|
+
set.delete(page.id);
|
|
1101
|
+
}
|
|
1102
|
+
if (set.size === 0)
|
|
1103
|
+
this.symbolIndex.delete(idxKey);
|
|
1104
|
+
}
|
|
1105
|
+
}
|
|
1106
|
+
evictOldest() {
|
|
1107
|
+
let candidate;
|
|
1108
|
+
let firstEntry;
|
|
1109
|
+
for (const pair of this.entries.entries()) {
|
|
1110
|
+
if (!firstEntry)
|
|
1111
|
+
firstEntry = pair;
|
|
1112
|
+
if (pair[1].page.toolName !== 'skill-catalog') {
|
|
1113
|
+
candidate = pair;
|
|
1114
|
+
break;
|
|
1115
|
+
}
|
|
1116
|
+
}
|
|
1117
|
+
const victim = candidate ?? firstEntry;
|
|
1118
|
+
if (!victim)
|
|
1119
|
+
return false;
|
|
1120
|
+
const [key, entry] = victim;
|
|
1121
|
+
this.entries.delete(key);
|
|
1122
|
+
this.totalBytes = Math.max(0, this.totalBytes - entry.bytes);
|
|
1123
|
+
this.removeIndexes(entry);
|
|
1124
|
+
this.stats.pagesEvicted += 1;
|
|
1125
|
+
return true;
|
|
1126
|
+
}
|
|
1127
|
+
insertEntry(entryKey, page, bytes, indexKeys, schedule) {
|
|
1128
|
+
while (this.entries.size > 0 &&
|
|
1129
|
+
(this.entries.size >= this.maxPages || this.totalBytes + bytes > this.maxBytes)) {
|
|
1130
|
+
if (!this.evictOldest())
|
|
1131
|
+
break;
|
|
1132
|
+
}
|
|
1133
|
+
const entry = { key: entryKey, page, bytes, indexKeys };
|
|
1134
|
+
this.entries.set(entryKey, entry);
|
|
1135
|
+
this.totalBytes += bytes;
|
|
1136
|
+
this.addIndexes(entry);
|
|
1137
|
+
this.stats.pagesStored += 1;
|
|
1138
|
+
this.stats.totalRawChars += page.rawText.length;
|
|
1139
|
+
if (schedule)
|
|
1140
|
+
this.scheduleSave();
|
|
1141
|
+
}
|
|
1142
|
+
/**
|
|
1143
|
+
* Store a paged-out block into Context-MMU.
|
|
1144
|
+
* Reuses an existing entry with identical `id` under `sessionKey` (no-op, refreshes LRU).
|
|
1145
|
+
*/
|
|
1146
|
+
storePage(input) {
|
|
1147
|
+
const sessionKey = input.sessionKey && input.sessionKey.trim() ? input.sessionKey.trim() : 'default';
|
|
1148
|
+
const refId = input.refId && input.refId.trim() ? input.refId.trim() : 'page';
|
|
1149
|
+
const id = pageIdForText(input.rawText);
|
|
1150
|
+
const entryKey = `${sessionKey}\0${id}`;
|
|
1151
|
+
const existing = this.entries.get(entryKey);
|
|
1152
|
+
if (existing) {
|
|
1153
|
+
if (input.extraSymbols && input.extraSymbols.length > 0) {
|
|
1154
|
+
const extraKeys = collectIndexKeys([], existing.page.filePath, input.extraSymbols);
|
|
1155
|
+
const merged = [...new Set([...existing.indexKeys, ...extraKeys])];
|
|
1156
|
+
const updated = { ...existing, indexKeys: merged };
|
|
1157
|
+
this.entries.delete(entryKey);
|
|
1158
|
+
this.entries.set(entryKey, updated);
|
|
1159
|
+
this.addIndexes(updated);
|
|
1160
|
+
}
|
|
1161
|
+
else {
|
|
1162
|
+
this.touchEntry(existing);
|
|
1163
|
+
}
|
|
1164
|
+
return existing.page;
|
|
1165
|
+
}
|
|
1166
|
+
const filePath = input.filePath ?? inferFilePath(input.rawText, refId);
|
|
1167
|
+
const symbols = extractSymbolSpans(input.rawText);
|
|
1168
|
+
const factTokens = extractFactSheetTokens(input.rawText);
|
|
1169
|
+
const page = {
|
|
1170
|
+
id,
|
|
1171
|
+
sessionKey,
|
|
1172
|
+
refId,
|
|
1173
|
+
...(input.toolName !== undefined ? { toolName: input.toolName } : {}),
|
|
1174
|
+
...(filePath !== undefined ? { filePath } : {}),
|
|
1175
|
+
createdAtMs: input.nowMs ?? Date.now(),
|
|
1176
|
+
rawText: input.rawText,
|
|
1177
|
+
lineCount: countLines(input.rawText),
|
|
1178
|
+
symbols,
|
|
1179
|
+
factTokens,
|
|
1180
|
+
};
|
|
1181
|
+
const bytes = utf8ByteLength(input.rawText);
|
|
1182
|
+
if (bytes > this.maxBytes) {
|
|
1183
|
+
// Single page exceeds total memory cap: return record without violating store bound.
|
|
1184
|
+
return page;
|
|
1185
|
+
}
|
|
1186
|
+
const indexKeys = collectIndexKeys(symbols, filePath, input.extraSymbols);
|
|
1187
|
+
this.insertEntry(entryKey, page, bytes, indexKeys, true);
|
|
1188
|
+
return page;
|
|
1189
|
+
}
|
|
1190
|
+
resolveEntryByPageId(pageId, sessionKey) {
|
|
1191
|
+
if (sessionKey !== undefined) {
|
|
1192
|
+
const sk = sessionKey.trim();
|
|
1193
|
+
return sk ? this.entries.get(`${sk}\0${pageId}`) : undefined;
|
|
1194
|
+
}
|
|
1195
|
+
const keys = this.keysByPageId.get(pageId);
|
|
1196
|
+
if (!keys || keys.size === 0)
|
|
1197
|
+
return undefined;
|
|
1198
|
+
let latest;
|
|
1199
|
+
for (const key of keys) {
|
|
1200
|
+
const e = this.entries.get(key);
|
|
1201
|
+
if (e)
|
|
1202
|
+
latest = e;
|
|
1203
|
+
}
|
|
1204
|
+
return latest;
|
|
1205
|
+
}
|
|
1206
|
+
/** Dereference a stored page by ID with optional sessionKey boundary, line range, or focused query. */
|
|
1207
|
+
derefPage(pageId, opts = {}) {
|
|
1208
|
+
if (!pageId || typeof pageId !== 'string')
|
|
1209
|
+
return null;
|
|
1210
|
+
const entry = this.resolveEntryByPageId(pageId.trim(), opts.sessionKey);
|
|
1211
|
+
if (!entry)
|
|
1212
|
+
return null;
|
|
1213
|
+
this.touchEntry(entry);
|
|
1214
|
+
const { page } = entry;
|
|
1215
|
+
const lines = page.rawText.split('\n');
|
|
1216
|
+
const total = lines.length;
|
|
1217
|
+
if (total === 0) {
|
|
1218
|
+
return { page, text: '', startLine: 1, endLine: 0 };
|
|
1219
|
+
}
|
|
1220
|
+
const maxLines = opts.maxLines !== undefined && Number.isFinite(opts.maxLines)
|
|
1221
|
+
? Math.max(1, Math.min(2000, Math.floor(opts.maxLines)))
|
|
1222
|
+
: undefined;
|
|
1223
|
+
let startLine = 1;
|
|
1224
|
+
let endLine = total;
|
|
1225
|
+
if (opts.startLine !== undefined || opts.endLine !== undefined) {
|
|
1226
|
+
const reqStart = opts.startLine !== undefined && Number.isFinite(opts.startLine)
|
|
1227
|
+
? Math.floor(opts.startLine)
|
|
1228
|
+
: 1;
|
|
1229
|
+
startLine = Math.max(1, Math.min(total, reqStart));
|
|
1230
|
+
const defaultEnd = maxLines !== undefined ? startLine + maxLines - 1 : total;
|
|
1231
|
+
const reqEnd = opts.endLine !== undefined && Number.isFinite(opts.endLine)
|
|
1232
|
+
? Math.floor(opts.endLine)
|
|
1233
|
+
: defaultEnd;
|
|
1234
|
+
endLine = Math.max(startLine, Math.min(total, reqEnd));
|
|
1235
|
+
if (maxLines !== undefined) {
|
|
1236
|
+
endLine = Math.min(endLine, startLine + maxLines - 1);
|
|
1237
|
+
}
|
|
1238
|
+
}
|
|
1239
|
+
else if (opts.query && opts.query.trim()) {
|
|
1240
|
+
const q = opts.query.trim().slice(0, 512).toLowerCase();
|
|
1241
|
+
const symHit = page.symbols.find((s) => s.name.toLowerCase() === q) ??
|
|
1242
|
+
page.symbols.find((s) => s.name.toLowerCase().includes(q));
|
|
1243
|
+
let centerLine = symHit?.startLine;
|
|
1244
|
+
if (centerLine === undefined) {
|
|
1245
|
+
for (let i = 0; i < total; i++) {
|
|
1246
|
+
if (lines[i].toLowerCase().includes(q)) {
|
|
1247
|
+
centerLine = i + 1;
|
|
1248
|
+
break;
|
|
1249
|
+
}
|
|
1250
|
+
}
|
|
1251
|
+
}
|
|
1252
|
+
if (centerLine !== undefined) {
|
|
1253
|
+
const cap = maxLines ?? 40;
|
|
1254
|
+
if (symHit && symHit.endLine - symHit.startLine + 1 <= cap) {
|
|
1255
|
+
startLine = Math.max(1, symHit.startLine - 5);
|
|
1256
|
+
endLine = Math.min(total, Math.max(symHit.endLine + 5, startLine + cap - 1));
|
|
1257
|
+
}
|
|
1258
|
+
else {
|
|
1259
|
+
const before = Math.min(15, Math.floor(cap / 2));
|
|
1260
|
+
startLine = Math.max(1, centerLine - before);
|
|
1261
|
+
endLine = Math.min(total, startLine + cap - 1);
|
|
1262
|
+
}
|
|
1263
|
+
}
|
|
1264
|
+
else {
|
|
1265
|
+
startLine = 1;
|
|
1266
|
+
endLine = maxLines !== undefined ? Math.min(total, maxLines) : total;
|
|
1267
|
+
}
|
|
1268
|
+
}
|
|
1269
|
+
else if (maxLines !== undefined) {
|
|
1270
|
+
startLine = 1;
|
|
1271
|
+
endLine = Math.min(total, maxLines);
|
|
1272
|
+
}
|
|
1273
|
+
const slicedLines = lines.slice(startLine - 1, endLine);
|
|
1274
|
+
let text = slicedLines.join('\n');
|
|
1275
|
+
let actualEnd = endLine;
|
|
1276
|
+
if (text.length > MAX_DEREF_CHARS) {
|
|
1277
|
+
const kept = [];
|
|
1278
|
+
let len = 0;
|
|
1279
|
+
for (let k = 0; k < slicedLines.length; k++) {
|
|
1280
|
+
const l = slicedLines[k];
|
|
1281
|
+
const nextLen = kept.length === 0 ? l.length : len + 1 + l.length;
|
|
1282
|
+
if (nextLen > MAX_DEREF_CHARS) {
|
|
1283
|
+
if (kept.length === 0) {
|
|
1284
|
+
kept.push(`${l.slice(0, Math.max(0, MAX_DEREF_CHARS - 16))}\n... [truncated]`);
|
|
1285
|
+
actualEnd = startLine;
|
|
1286
|
+
}
|
|
1287
|
+
else {
|
|
1288
|
+
actualEnd = startLine + kept.length - 1;
|
|
1289
|
+
}
|
|
1290
|
+
break;
|
|
1291
|
+
}
|
|
1292
|
+
kept.push(l);
|
|
1293
|
+
len = nextLen;
|
|
1294
|
+
}
|
|
1295
|
+
text = kept.join('\n');
|
|
1296
|
+
}
|
|
1297
|
+
return {
|
|
1298
|
+
page,
|
|
1299
|
+
text,
|
|
1300
|
+
startLine,
|
|
1301
|
+
endLine: actualEnd,
|
|
1302
|
+
};
|
|
1303
|
+
}
|
|
1304
|
+
/** List stored page metadata (no `rawText`), strictly scoped when `sessionKey` is provided. */
|
|
1305
|
+
listPages(sessionKey) {
|
|
1306
|
+
let scopedKey;
|
|
1307
|
+
if (sessionKey !== undefined) {
|
|
1308
|
+
scopedKey = sessionKey.trim();
|
|
1309
|
+
if (!scopedKey)
|
|
1310
|
+
return [];
|
|
1311
|
+
}
|
|
1312
|
+
const out = [];
|
|
1313
|
+
for (const entry of this.entries.values()) {
|
|
1314
|
+
if (scopedKey !== undefined && entry.page.sessionKey !== scopedKey)
|
|
1315
|
+
continue;
|
|
1316
|
+
out.push(summarizePage(entry.page));
|
|
1317
|
+
}
|
|
1318
|
+
return out;
|
|
1319
|
+
}
|
|
1320
|
+
/** Search resident pages by symbol name, file path, fact token, or text content. */
|
|
1321
|
+
searchPages(query, sessionKey) {
|
|
1322
|
+
let scopedKey;
|
|
1323
|
+
if (sessionKey !== undefined) {
|
|
1324
|
+
scopedKey = sessionKey.trim();
|
|
1325
|
+
if (!scopedKey)
|
|
1326
|
+
return [];
|
|
1327
|
+
}
|
|
1328
|
+
const q = query.trim().slice(0, 512);
|
|
1329
|
+
if (!q)
|
|
1330
|
+
return [];
|
|
1331
|
+
const qLower = q.toLowerCase();
|
|
1332
|
+
const terms = qLower
|
|
1333
|
+
.split(/[\s,;/()]+/)
|
|
1334
|
+
.map((t) => t.trim())
|
|
1335
|
+
.filter((t) => t.length >= 2)
|
|
1336
|
+
.slice(0, 16);
|
|
1337
|
+
if (terms.length === 0)
|
|
1338
|
+
terms.push(qLower);
|
|
1339
|
+
const indexedIds = new Set();
|
|
1340
|
+
const exactIdSet = this.symbolIndex.get(qLower);
|
|
1341
|
+
if (exactIdSet) {
|
|
1342
|
+
for (const id of exactIdSet)
|
|
1343
|
+
indexedIds.add(id);
|
|
1344
|
+
}
|
|
1345
|
+
for (const term of terms) {
|
|
1346
|
+
const s = this.symbolIndex.get(term);
|
|
1347
|
+
if (s)
|
|
1348
|
+
for (const id of s)
|
|
1349
|
+
indexedIds.add(id);
|
|
1350
|
+
}
|
|
1351
|
+
const hits = [];
|
|
1352
|
+
const sessionFilter = scopedKey !== undefined ? this.sessionIndex.get(scopedKey) : undefined;
|
|
1353
|
+
if (scopedKey !== undefined && (!sessionFilter || sessionFilter.size === 0)) {
|
|
1354
|
+
return [];
|
|
1355
|
+
}
|
|
1356
|
+
// Walk MRU -> LRU by iterating entries in reverse insertion order
|
|
1357
|
+
const ordered = [...this.entries.values()].reverse();
|
|
1358
|
+
for (const entry of ordered) {
|
|
1359
|
+
const { page } = entry;
|
|
1360
|
+
if (scopedKey !== undefined && page.sessionKey !== scopedKey)
|
|
1361
|
+
continue;
|
|
1362
|
+
let score = indexedIds.has(page.id) ? 50 : 0;
|
|
1363
|
+
const matchedSymbols = [];
|
|
1364
|
+
for (const sym of page.symbols) {
|
|
1365
|
+
const sLower = sym.name.toLowerCase();
|
|
1366
|
+
if (sLower === qLower || terms.includes(sLower)) {
|
|
1367
|
+
score += 100;
|
|
1368
|
+
matchedSymbols.push(sym);
|
|
1369
|
+
}
|
|
1370
|
+
else if (terms.some((t) => sLower.includes(t))) {
|
|
1371
|
+
score += 40;
|
|
1372
|
+
matchedSymbols.push(sym);
|
|
1373
|
+
}
|
|
1374
|
+
}
|
|
1375
|
+
if (page.filePath) {
|
|
1376
|
+
const fpLower = page.filePath.toLowerCase();
|
|
1377
|
+
const baseLower = pathBasename(fpLower);
|
|
1378
|
+
if (baseLower === qLower || terms.includes(baseLower))
|
|
1379
|
+
score += 80;
|
|
1380
|
+
else if (fpLower.includes(qLower) || terms.some((t) => fpLower.includes(t)))
|
|
1381
|
+
score += 30;
|
|
1382
|
+
}
|
|
1383
|
+
if (page.refId.toLowerCase().includes(qLower))
|
|
1384
|
+
score += 25;
|
|
1385
|
+
for (const ft of page.factTokens) {
|
|
1386
|
+
const ftLow = ft.toLowerCase();
|
|
1387
|
+
if (ftLow === qLower || terms.includes(ftLow)) {
|
|
1388
|
+
score += 30;
|
|
1389
|
+
break;
|
|
1390
|
+
}
|
|
1391
|
+
}
|
|
1392
|
+
let textLineHit;
|
|
1393
|
+
if (score === 0 || matchedSymbols.length === 0) {
|
|
1394
|
+
const rawLower = page.rawText.toLowerCase();
|
|
1395
|
+
const idx = rawLower.indexOf(qLower);
|
|
1396
|
+
if (idx >= 0) {
|
|
1397
|
+
score += 15;
|
|
1398
|
+
textLineHit = countLines(page.rawText.slice(0, idx));
|
|
1399
|
+
}
|
|
1400
|
+
else if (terms.length > 1) {
|
|
1401
|
+
for (const t of terms) {
|
|
1402
|
+
const tidx = rawLower.indexOf(t);
|
|
1403
|
+
if (tidx >= 0) {
|
|
1404
|
+
score += 10;
|
|
1405
|
+
textLineHit = textLineHit ?? countLines(page.rawText.slice(0, tidx));
|
|
1406
|
+
break;
|
|
1407
|
+
}
|
|
1408
|
+
}
|
|
1409
|
+
}
|
|
1410
|
+
}
|
|
1411
|
+
if (score > 0) {
|
|
1412
|
+
hits.push({
|
|
1413
|
+
page: summarizePage(page),
|
|
1414
|
+
score,
|
|
1415
|
+
matchedSymbols,
|
|
1416
|
+
matchedLine: matchedSymbols[0]?.startLine ?? textLineHit ?? 1,
|
|
1417
|
+
});
|
|
1418
|
+
}
|
|
1419
|
+
}
|
|
1420
|
+
hits.sort((a, b) => b.score - a.score || b.page.createdAtMs - a.page.createdAtMs);
|
|
1421
|
+
return hits;
|
|
1422
|
+
}
|
|
1423
|
+
/** Lookup page IDs indexed for a lowercased symbol or basename key. */
|
|
1424
|
+
lookupSymbolPageIds(symbolOrBasename, sessionKey) {
|
|
1425
|
+
const set = this.symbolIndex.get(symbolOrBasename.trim().toLowerCase());
|
|
1426
|
+
if (!set || set.size === 0)
|
|
1427
|
+
return [];
|
|
1428
|
+
if (!sessionKey)
|
|
1429
|
+
return [...set];
|
|
1430
|
+
const sessPages = this.sessionIndex.get(sessionKey);
|
|
1431
|
+
if (!sessPages || sessPages.size === 0)
|
|
1432
|
+
return [];
|
|
1433
|
+
const out = [];
|
|
1434
|
+
for (const id of set) {
|
|
1435
|
+
if (sessPages.has(id))
|
|
1436
|
+
out.push(id);
|
|
1437
|
+
}
|
|
1438
|
+
return out;
|
|
1439
|
+
}
|
|
1440
|
+
/** O(1) resident page count (optionally scoped to one session). */
|
|
1441
|
+
getSessionPageCount(sessionKey) {
|
|
1442
|
+
if (!sessionKey)
|
|
1443
|
+
return this.entries.size;
|
|
1444
|
+
return this.sessionIndex.get(sessionKey.trim())?.size ?? 0;
|
|
1445
|
+
}
|
|
1446
|
+
/** Retrieve raw page object by ID (optional sessionKey preference) without modifying text. */
|
|
1447
|
+
getPage(pageId, sessionKey) {
|
|
1448
|
+
const entry = this.resolveEntryByPageId(pageId, sessionKey);
|
|
1449
|
+
return entry ? entry.page : null;
|
|
1450
|
+
}
|
|
1451
|
+
/**
|
|
1452
|
+
* Append a clean, idempotent Virtual Memory page card to a compact digest.
|
|
1453
|
+
*/
|
|
1454
|
+
formatPageCard(page, compactDigest) {
|
|
1455
|
+
const markerPrefix = `[fiche vm-page ${page.id}`;
|
|
1456
|
+
if (compactDigest.includes(markerPrefix))
|
|
1457
|
+
return compactDigest;
|
|
1458
|
+
const seenSyms = new Set();
|
|
1459
|
+
const declNames = [];
|
|
1460
|
+
const anchorNames = [];
|
|
1461
|
+
for (const sym of page.symbols) {
|
|
1462
|
+
if (seenSyms.has(sym.name))
|
|
1463
|
+
continue;
|
|
1464
|
+
seenSyms.add(sym.name);
|
|
1465
|
+
if (sym.kind === 'error' || sym.kind === 'anchor') {
|
|
1466
|
+
if (anchorNames.length < 4)
|
|
1467
|
+
anchorNames.push(sym.name);
|
|
1468
|
+
}
|
|
1469
|
+
else if (declNames.length < 5) {
|
|
1470
|
+
declNames.push(sym.name);
|
|
1471
|
+
}
|
|
1472
|
+
}
|
|
1473
|
+
const topSyms = declNames.length > 0 ? declNames : anchorNames;
|
|
1474
|
+
const loc = page.filePath ? ` (${page.filePath}, ${page.lineCount}L)` : '';
|
|
1475
|
+
const symPart = topSyms.length > 0 ? ` | top symbols: ${topSyms.join(', ')}` : '';
|
|
1476
|
+
const card = `[fiche vm-page ${page.id}${loc}${symPart} | page_in("${page.id}")]`;
|
|
1477
|
+
return compactDigest ? `${compactDigest}\n${card}` : card;
|
|
1478
|
+
}
|
|
1479
|
+
recordTailHydration(tokens) {
|
|
1480
|
+
if (tokens <= 0)
|
|
1481
|
+
return;
|
|
1482
|
+
this.stats.tailHydrations += 1;
|
|
1483
|
+
this.stats.tailHydrationTokens += tokens;
|
|
1484
|
+
this.scheduleSave();
|
|
1485
|
+
}
|
|
1486
|
+
recordMarkovFold(foldedChars) {
|
|
1487
|
+
if (foldedChars <= 0)
|
|
1488
|
+
return;
|
|
1489
|
+
this.stats.markovFolds += 1;
|
|
1490
|
+
this.stats.markovFoldedChars += foldedChars;
|
|
1491
|
+
this.scheduleSave();
|
|
1492
|
+
}
|
|
1493
|
+
recordSkillStub(stubbedCount, savedChars) {
|
|
1494
|
+
if (stubbedCount <= 0)
|
|
1495
|
+
return;
|
|
1496
|
+
this.stats.skillsStubbed += stubbedCount;
|
|
1497
|
+
this.stats.skillStubSavedChars += Math.max(0, savedChars);
|
|
1498
|
+
this.scheduleSave();
|
|
1499
|
+
}
|
|
1500
|
+
recordDensityPrune(prunedChars) {
|
|
1501
|
+
if (prunedChars <= 0)
|
|
1502
|
+
return;
|
|
1503
|
+
this.stats.densityPrunedBlocks += 1;
|
|
1504
|
+
this.stats.densityPrunedChars += prunedChars;
|
|
1505
|
+
this.scheduleSave();
|
|
1506
|
+
}
|
|
1507
|
+
getStats() {
|
|
1508
|
+
return {
|
|
1509
|
+
...this.stats,
|
|
1510
|
+
activePages: this.entries.size,
|
|
1511
|
+
activeBytes: this.totalBytes,
|
|
1512
|
+
};
|
|
1513
|
+
}
|
|
1514
|
+
/** Return active page/RAM bounds and whether disk persistence is attached. */
|
|
1515
|
+
getLimits() {
|
|
1516
|
+
return {
|
|
1517
|
+
maxPages: this.maxPages,
|
|
1518
|
+
maxBytes: this.maxBytes,
|
|
1519
|
+
persisted: this.persistence !== undefined,
|
|
1520
|
+
};
|
|
1521
|
+
}
|
|
1522
|
+
/**
|
|
1523
|
+
* Update page/byte bounds dynamically and evict oldest pages if the store
|
|
1524
|
+
* currently exceeds the new limits.
|
|
1525
|
+
*/
|
|
1526
|
+
setLimits(opts) {
|
|
1527
|
+
if (opts.maxPages !== undefined && Number.isFinite(opts.maxPages)) {
|
|
1528
|
+
this.maxPages = Math.max(1, Math.floor(opts.maxPages));
|
|
1529
|
+
}
|
|
1530
|
+
if (opts.maxBytes !== undefined && Number.isFinite(opts.maxBytes)) {
|
|
1531
|
+
this.maxBytes = Math.max(1, Math.floor(opts.maxBytes));
|
|
1532
|
+
}
|
|
1533
|
+
while (this.entries.size > 0 &&
|
|
1534
|
+
(this.entries.size > this.maxPages || this.totalBytes > this.maxBytes)) {
|
|
1535
|
+
if (!this.evictOldest())
|
|
1536
|
+
break;
|
|
1537
|
+
}
|
|
1538
|
+
}
|
|
1539
|
+
/** Increment and return the per-session logical hydration turn counter (LRU-bounded to 512 sessions). */
|
|
1540
|
+
nextHydrationTurn(sessionKey) {
|
|
1541
|
+
const key = sessionKey || 'default';
|
|
1542
|
+
const next = (this.hydrationTurn.get(key) ?? 0) + 1;
|
|
1543
|
+
if (this.hydrationTurn.has(key)) {
|
|
1544
|
+
this.hydrationTurn.delete(key);
|
|
1545
|
+
}
|
|
1546
|
+
else if (this.hydrationTurn.size >= TLB_MAX_SESSIONS) {
|
|
1547
|
+
const oldest = this.hydrationTurn.keys().next().value;
|
|
1548
|
+
if (oldest !== undefined) {
|
|
1549
|
+
this.hydrationTurn.delete(oldest);
|
|
1550
|
+
this.hydrationTlb.delete(oldest);
|
|
1551
|
+
}
|
|
1552
|
+
}
|
|
1553
|
+
this.hydrationTurn.set(key, next);
|
|
1554
|
+
return next;
|
|
1555
|
+
}
|
|
1556
|
+
/**
|
|
1557
|
+
* Return true iff an overlapping slice on `pageId` (`±4` lines) was already
|
|
1558
|
+
* hydrated for `sessionKey` within the last `cooldownTurns` logical turns.
|
|
1559
|
+
*/
|
|
1560
|
+
isTlbSuppressed(sessionKey, pageId, startLine, endLine, turn, cooldownTurns = TLB_DEFAULT_COOLDOWN_TURNS) {
|
|
1561
|
+
const key = sessionKey || 'default';
|
|
1562
|
+
const sessionLeases = this.hydrationTlb.get(key);
|
|
1563
|
+
if (!sessionLeases)
|
|
1564
|
+
return false;
|
|
1565
|
+
const prev = sessionLeases.get(pageId);
|
|
1566
|
+
if (!prev)
|
|
1567
|
+
return false;
|
|
1568
|
+
if (turn - prev.turn > cooldownTurns)
|
|
1569
|
+
return false;
|
|
1570
|
+
return Math.max(startLine, prev.startLine) <= Math.min(endLine, prev.endLine) + TLB_OVERLAP_PAD_LINES;
|
|
1571
|
+
}
|
|
1572
|
+
/** Record/refresh a Context-TLB hydration lease (LRU-bounded to 64 leases per session). */
|
|
1573
|
+
recordHydrationLease(sessionKey, pageId, startLine, endLine, turn) {
|
|
1574
|
+
const key = sessionKey || 'default';
|
|
1575
|
+
let sessionLeases = this.hydrationTlb.get(key);
|
|
1576
|
+
if (sessionLeases) {
|
|
1577
|
+
this.hydrationTlb.delete(key);
|
|
1578
|
+
}
|
|
1579
|
+
else {
|
|
1580
|
+
if (this.hydrationTlb.size >= TLB_MAX_SESSIONS) {
|
|
1581
|
+
const oldest = this.hydrationTlb.keys().next().value;
|
|
1582
|
+
if (oldest !== undefined) {
|
|
1583
|
+
this.hydrationTlb.delete(oldest);
|
|
1584
|
+
this.hydrationTurn.delete(oldest);
|
|
1585
|
+
}
|
|
1586
|
+
}
|
|
1587
|
+
sessionLeases = new Map();
|
|
1588
|
+
}
|
|
1589
|
+
this.hydrationTlb.set(key, sessionLeases);
|
|
1590
|
+
if (sessionLeases.has(pageId)) {
|
|
1591
|
+
sessionLeases.delete(pageId);
|
|
1592
|
+
}
|
|
1593
|
+
else if (sessionLeases.size >= TLB_MAX_LEASES_PER_SESSION) {
|
|
1594
|
+
const oldestPage = sessionLeases.keys().next().value;
|
|
1595
|
+
if (oldestPage !== undefined)
|
|
1596
|
+
sessionLeases.delete(oldestPage);
|
|
1597
|
+
}
|
|
1598
|
+
sessionLeases.set(pageId, { startLine, endLine, turn });
|
|
1599
|
+
}
|
|
1600
|
+
reset() {
|
|
1601
|
+
if (this.saveTimer) {
|
|
1602
|
+
clearTimeout(this.saveTimer);
|
|
1603
|
+
this.saveTimer = undefined;
|
|
1604
|
+
}
|
|
1605
|
+
this.dirty = false;
|
|
1606
|
+
this.entries.clear();
|
|
1607
|
+
this.keysByPageId.clear();
|
|
1608
|
+
this.symbolIndex.clear();
|
|
1609
|
+
this.sessionIndex.clear();
|
|
1610
|
+
this.hydrationTlb.clear();
|
|
1611
|
+
this.hydrationTurn.clear();
|
|
1612
|
+
this.totalBytes = 0;
|
|
1613
|
+
this.stats = emptyStats();
|
|
1614
|
+
}
|
|
1615
|
+
}
|
|
1616
|
+
let globalMmuStore;
|
|
1617
|
+
export function getGlobalMmuStore() {
|
|
1618
|
+
if (!globalMmuStore) {
|
|
1619
|
+
globalMmuStore = new ContextPageStore();
|
|
1620
|
+
}
|
|
1621
|
+
return globalMmuStore;
|
|
1622
|
+
}
|
|
1623
|
+
/**
|
|
1624
|
+
* Configure the global Context-MMU RAM limits (clamped to `[64, 16384]` pages
|
|
1625
|
+
* and `[4 MiB, 256 MiB]` bytes), evicting oldest pages immediately if shrunk.
|
|
1626
|
+
*/
|
|
1627
|
+
export function configureMmuLimits(opts) {
|
|
1628
|
+
const store = getGlobalMmuStore();
|
|
1629
|
+
const next = {};
|
|
1630
|
+
if (opts.maxPages !== undefined && Number.isFinite(opts.maxPages)) {
|
|
1631
|
+
next.maxPages = Math.min(MAX_MMU_PAGES, Math.max(MIN_MMU_PAGES, Math.floor(opts.maxPages)));
|
|
1632
|
+
}
|
|
1633
|
+
if (opts.maxBytes !== undefined && Number.isFinite(opts.maxBytes)) {
|
|
1634
|
+
next.maxBytes = Math.min(MAX_MMU_BYTES, Math.max(MIN_MMU_BYTES, Math.floor(opts.maxBytes)));
|
|
1635
|
+
}
|
|
1636
|
+
store.setLimits(next);
|
|
1637
|
+
return { maxPages: store.maxPages, maxBytes: store.maxBytes };
|
|
1638
|
+
}
|
|
1639
|
+
export function configureMmuPersistence(adapter) {
|
|
1640
|
+
return getGlobalMmuStore().configurePersistence(adapter);
|
|
1641
|
+
}
|
|
1642
|
+
export function flushMmuPersistence() {
|
|
1643
|
+
return globalMmuStore ? globalMmuStore.flush() : false;
|
|
1644
|
+
}
|
|
1645
|
+
export function resetGlobalMmuStore() {
|
|
1646
|
+
globalMmuStore?.reset();
|
|
1647
|
+
resetGlobalPrefixTape();
|
|
1648
|
+
}
|
|
1649
|
+
const TAIL_PAGE_ID_RE = /\bpg_[0-9a-f]{8,16}\b/g;
|
|
1650
|
+
// Non-backtracking maximal path token scan for O(N) basename extraction (no nested path quantifier).
|
|
1651
|
+
const TAIL_PATH_TOKEN_RE = /[\w.@+/-]+/g;
|
|
1652
|
+
const TAIL_BASE_VALID_RE = /^[\w.-]+$/;
|
|
1653
|
+
const TAIL_EXT_VALID_RE = /^[A-Za-z0-9]{1,10}$/;
|
|
1654
|
+
const TAIL_CAMEL_RE = /\b[a-z][a-z0-9]*(?:[A-Z][a-z0-9]*)+\b/g;
|
|
1655
|
+
const TAIL_PASCAL_RE = /\b[A-Z][a-z0-9]+(?:[A-Z][a-z0-9]*)+\b/g;
|
|
1656
|
+
const TAIL_SNAKE_RE = /\b[a-z][a-z0-9]*(?:_[a-z0-9]+)+\b/g;
|
|
1657
|
+
const TAIL_KEBAB_RE = /\b[a-z][a-z0-9]*(?:-[a-z0-9]+)+\b/g;
|
|
1658
|
+
const TAIL_ERROR_RE = /\b(?:[A-Z][A-Za-z0-9]*(?:Error|Exception|Fault|Panic)|ERR_[A-Z0-9_]{2,}|E(?:NOENT|ACCES|PERM|CONNREFUSED|TIMEDOUT|ADDRINUSE|PIPE|ISDIR|NOSPC))\b/g;
|
|
1659
|
+
const TAIL_SKILL_WORD_RE = /\b[A-Za-z][A-Za-z0-9]{2,31}\b/g;
|
|
1660
|
+
const TAIL_FAULT_SIGNAL_RE = /\b(?:pg_[0-9a-f]{8,16}|[A-Za-z_]\w*(?:Error|Exception|Fault|Panic)|ERR_[A-Z0-9_]+|FAIL(?:ED)?|exit[_ ]?code[:=\s]+[1-9]\d*|returned [1-9]\d*)\b|Traceback \(most recent call last\)|^\s*at\s+\S+\s*\(/m;
|
|
1661
|
+
/**
|
|
1662
|
+
* Intent-stratified tool-output filter for SB-SMP: returns the trailing
|
|
1663
|
+
* snippet only when a tool output carries an active fault/stack signal or
|
|
1664
|
+
* explicit `pg_*` page pointer, preventing routine `read_file` outputs from
|
|
1665
|
+
* triggering speculative hydrations on passing turns.
|
|
1666
|
+
*/
|
|
1667
|
+
export function extractFaultSignalSnippet(toolText, maxChars = 2048) {
|
|
1668
|
+
if (!toolText || !toolText.trim())
|
|
1669
|
+
return undefined;
|
|
1670
|
+
if (!TAIL_FAULT_SIGNAL_RE.test(toolText))
|
|
1671
|
+
return undefined;
|
|
1672
|
+
return toolText.length > maxChars ? toolText.slice(-maxChars) : toolText;
|
|
1673
|
+
}
|
|
1674
|
+
function extractTailIdentifierTokens(texts) {
|
|
1675
|
+
const pageIds = [];
|
|
1676
|
+
const symbols = [];
|
|
1677
|
+
const basenames = [];
|
|
1678
|
+
const skillWords = [];
|
|
1679
|
+
const seenPage = new Set();
|
|
1680
|
+
const seenSym = new Set();
|
|
1681
|
+
const seenBase = new Set();
|
|
1682
|
+
const seenWord = new Set();
|
|
1683
|
+
const pushMatches = (src, re, target, seen, lowercaseOut = false) => {
|
|
1684
|
+
re.lastIndex = 0;
|
|
1685
|
+
let m;
|
|
1686
|
+
while ((m = re.exec(src)) !== null) {
|
|
1687
|
+
const val = m[0].trim();
|
|
1688
|
+
if (!val || val.length < 3 || val.length > 120)
|
|
1689
|
+
continue;
|
|
1690
|
+
const low = val.toLowerCase();
|
|
1691
|
+
if (!seen.has(low)) {
|
|
1692
|
+
seen.add(low);
|
|
1693
|
+
target.push(lowercaseOut ? low : val);
|
|
1694
|
+
}
|
|
1695
|
+
if (target.length >= 64)
|
|
1696
|
+
break;
|
|
1697
|
+
}
|
|
1698
|
+
};
|
|
1699
|
+
// Iterate newest-to-oldest so the active prompt/tool turn never starves behind earlier messages.
|
|
1700
|
+
for (let i = texts.length - 1; i >= 0; i--) {
|
|
1701
|
+
const raw = texts[i];
|
|
1702
|
+
if (!raw)
|
|
1703
|
+
continue;
|
|
1704
|
+
const sample = raw.length > 16_384 ? raw.slice(-16_384) : raw;
|
|
1705
|
+
if (pageIds.length < 64)
|
|
1706
|
+
pushMatches(sample, TAIL_PAGE_ID_RE, pageIds, seenPage);
|
|
1707
|
+
if (symbols.length < 64)
|
|
1708
|
+
pushMatches(sample, TAIL_CAMEL_RE, symbols, seenSym);
|
|
1709
|
+
if (symbols.length < 64)
|
|
1710
|
+
pushMatches(sample, TAIL_PASCAL_RE, symbols, seenSym);
|
|
1711
|
+
if (symbols.length < 64)
|
|
1712
|
+
pushMatches(sample, TAIL_SNAKE_RE, symbols, seenSym);
|
|
1713
|
+
if (symbols.length < 64)
|
|
1714
|
+
pushMatches(sample, TAIL_KEBAB_RE, symbols, seenSym);
|
|
1715
|
+
if (symbols.length < 64)
|
|
1716
|
+
pushMatches(sample, TAIL_ERROR_RE, symbols, seenSym);
|
|
1717
|
+
if (basenames.length < 64) {
|
|
1718
|
+
TAIL_PATH_TOKEN_RE.lastIndex = 0;
|
|
1719
|
+
let pm;
|
|
1720
|
+
while ((pm = TAIL_PATH_TOKEN_RE.exec(sample)) !== null) {
|
|
1721
|
+
const tok = pm[0];
|
|
1722
|
+
const slash = tok.lastIndexOf('/');
|
|
1723
|
+
const base = slash >= 0 ? tok.slice(slash + 1) : tok;
|
|
1724
|
+
if (base.length < 3 || base.length > 120 || !TAIL_BASE_VALID_RE.test(base))
|
|
1725
|
+
continue;
|
|
1726
|
+
const dot = base.lastIndexOf('.');
|
|
1727
|
+
if (dot <= 0 || !TAIL_EXT_VALID_RE.test(base.slice(dot + 1)))
|
|
1728
|
+
continue;
|
|
1729
|
+
const low = base.toLowerCase();
|
|
1730
|
+
if (!seenBase.has(low)) {
|
|
1731
|
+
seenBase.add(low);
|
|
1732
|
+
basenames.push(base);
|
|
1733
|
+
}
|
|
1734
|
+
if (basenames.length >= 64)
|
|
1735
|
+
break;
|
|
1736
|
+
}
|
|
1737
|
+
}
|
|
1738
|
+
if (skillWords.length < 64)
|
|
1739
|
+
pushMatches(sample, TAIL_SKILL_WORD_RE, skillWords, seenWord, true);
|
|
1740
|
+
}
|
|
1741
|
+
return { pageIds, symbols, basenames, skillWords };
|
|
1742
|
+
}
|
|
1743
|
+
/**
|
|
1744
|
+
* Purely read-only Symbol-Boundary-Aware Speculative MMU Prefetcher (SB-SMP).
|
|
1745
|
+
* Fuses `pg_*`, declaration spans, error anchors, basenames, and skill matches
|
|
1746
|
+
* with exact session IDF weighting; preserves full enclosing function bodies
|
|
1747
|
+
* up to ~45 lines; never modifies cached prefixes; fails closed without `sessionKey`.
|
|
1748
|
+
*/
|
|
1749
|
+
export function computeTailHydration(input) {
|
|
1750
|
+
const budgetTokens = Math.max(64, Math.floor(input.budgetTokens ?? 1400));
|
|
1751
|
+
const maxSlices = Math.max(1, Math.floor(input.maxSlices ?? 3));
|
|
1752
|
+
const sessionKey = input.sessionKey?.trim();
|
|
1753
|
+
if (!sessionKey || input.liveTailTexts.length === 0) {
|
|
1754
|
+
return { text: '', changed: false, slices: [], totalTokens: 0 };
|
|
1755
|
+
}
|
|
1756
|
+
const tlbTurn = input.store.nextHydrationTurn(sessionKey);
|
|
1757
|
+
const tokens = extractTailIdentifierTokens(input.liveTailTexts);
|
|
1758
|
+
if (tokens.pageIds.length === 0 &&
|
|
1759
|
+
tokens.symbols.length === 0 &&
|
|
1760
|
+
tokens.basenames.length === 0 &&
|
|
1761
|
+
tokens.skillWords.length === 0) {
|
|
1762
|
+
return { text: '', changed: false, slices: [], totalTokens: 0 };
|
|
1763
|
+
}
|
|
1764
|
+
const recentTexts = (input.recentVerbatimTexts ?? []).filter(Boolean);
|
|
1765
|
+
const isAlreadyVerbatim = (page, sliceText) => {
|
|
1766
|
+
for (const r of recentTexts) {
|
|
1767
|
+
if (r.includes(page.rawText))
|
|
1768
|
+
return true;
|
|
1769
|
+
if (sliceText.length >= 40 && r.includes(sliceText))
|
|
1770
|
+
return true;
|
|
1771
|
+
}
|
|
1772
|
+
return false;
|
|
1773
|
+
};
|
|
1774
|
+
const totalSessionPages = Math.max(1, input.store.getSessionPageCount(sessionKey));
|
|
1775
|
+
const computeIdf = (df) => Math.log(1 + totalSessionPages / (1 + Math.max(0, df)));
|
|
1776
|
+
// Collect basename-matched pages up front so co-hits receive multi-signal fusion bonus.
|
|
1777
|
+
const basenamePageInfo = new Map();
|
|
1778
|
+
for (const base of tokens.basenames) {
|
|
1779
|
+
const pageIds = input.store.lookupSymbolPageIds(base, sessionKey);
|
|
1780
|
+
const idf = computeIdf(pageIds.length);
|
|
1781
|
+
for (const pid of pageIds) {
|
|
1782
|
+
const prev = basenamePageInfo.get(pid);
|
|
1783
|
+
if (!prev || idf > prev.idf)
|
|
1784
|
+
basenamePageInfo.set(pid, { base, idf });
|
|
1785
|
+
}
|
|
1786
|
+
}
|
|
1787
|
+
const candidates = [];
|
|
1788
|
+
const addOrFuseCandidate = (next) => {
|
|
1789
|
+
for (const existing of candidates) {
|
|
1790
|
+
if (existing.page.id !== next.page.id)
|
|
1791
|
+
continue;
|
|
1792
|
+
if (Math.abs(existing.targetLine - next.targetLine) <= 8) {
|
|
1793
|
+
// Multi-signal fusion: boost composite score and preserve tighter/fuller span info.
|
|
1794
|
+
existing.score += next.score * 0.5;
|
|
1795
|
+
if (next.isExplicitPageId)
|
|
1796
|
+
existing.isExplicitPageId = true;
|
|
1797
|
+
if (next.hasHighSignal)
|
|
1798
|
+
existing.hasHighSignal = true;
|
|
1799
|
+
if (next.hasDeclSpan && !existing.hasDeclSpan) {
|
|
1800
|
+
existing.matchedSymbol = next.matchedSymbol;
|
|
1801
|
+
existing.targetLine = next.targetLine;
|
|
1802
|
+
existing.spanStartLine = next.spanStartLine;
|
|
1803
|
+
existing.spanEndLine = next.spanEndLine;
|
|
1804
|
+
existing.hasDeclSpan = true;
|
|
1805
|
+
}
|
|
1806
|
+
return;
|
|
1807
|
+
}
|
|
1808
|
+
}
|
|
1809
|
+
candidates.push(next);
|
|
1810
|
+
};
|
|
1811
|
+
// Explicit `pg_<hex>` reference (highest confidence, scoped to sessionKey)
|
|
1812
|
+
for (const pid of tokens.pageIds) {
|
|
1813
|
+
const page = input.store.getPage(pid, sessionKey);
|
|
1814
|
+
if (!page)
|
|
1815
|
+
continue;
|
|
1816
|
+
const sp = page.symbols[0];
|
|
1817
|
+
const hasDecl = Boolean(sp && sp.kind !== 'error' && sp.kind !== 'anchor' && sp.endLine > sp.startLine);
|
|
1818
|
+
addOrFuseCandidate({
|
|
1819
|
+
page,
|
|
1820
|
+
matchedSymbol: pid,
|
|
1821
|
+
targetLine: sp?.startLine ?? 1,
|
|
1822
|
+
spanStartLine: sp?.startLine ?? 1,
|
|
1823
|
+
spanEndLine: sp?.endLine ?? (sp?.startLine ?? 1),
|
|
1824
|
+
hasDeclSpan: hasDecl,
|
|
1825
|
+
score: 100,
|
|
1826
|
+
isExplicitPageId: true,
|
|
1827
|
+
hasHighSignal: true,
|
|
1828
|
+
});
|
|
1829
|
+
}
|
|
1830
|
+
// Symbol / declaration / error hits via inverted symbolIndex + IDF weighting
|
|
1831
|
+
const symbolMatchedPageIds = new Set();
|
|
1832
|
+
for (const sym of tokens.symbols) {
|
|
1833
|
+
const pageIds = input.store.lookupSymbolPageIds(sym, sessionKey);
|
|
1834
|
+
if (pageIds.length === 0)
|
|
1835
|
+
continue;
|
|
1836
|
+
const idf = computeIdf(pageIds.length);
|
|
1837
|
+
const symLow = sym.toLowerCase();
|
|
1838
|
+
for (const pid of pageIds) {
|
|
1839
|
+
const page = input.store.getPage(pid, sessionKey);
|
|
1840
|
+
if (!page)
|
|
1841
|
+
continue;
|
|
1842
|
+
symbolMatchedPageIds.add(pid);
|
|
1843
|
+
const span = page.symbols.find((s) => s.name.toLowerCase() === symLow);
|
|
1844
|
+
const isErrorOrAnchor = span?.kind === 'error' || span?.kind === 'anchor';
|
|
1845
|
+
const hasDecl = Boolean(span && !isErrorOrAnchor && span.endLine > span.startLine);
|
|
1846
|
+
const baseBonus = basenamePageInfo.has(pid) ? 6 : 0;
|
|
1847
|
+
const score = (isErrorOrAnchor ? 7 + 2 * idf : 12 + 4 * idf) + baseBonus;
|
|
1848
|
+
addOrFuseCandidate({
|
|
1849
|
+
page,
|
|
1850
|
+
matchedSymbol: span?.name ?? sym,
|
|
1851
|
+
targetLine: span?.startLine ?? 1,
|
|
1852
|
+
spanStartLine: span?.startLine ?? 1,
|
|
1853
|
+
spanEndLine: span?.endLine ?? (span?.startLine ?? 1),
|
|
1854
|
+
hasDeclSpan: hasDecl,
|
|
1855
|
+
score,
|
|
1856
|
+
hasHighSignal: true,
|
|
1857
|
+
});
|
|
1858
|
+
}
|
|
1859
|
+
}
|
|
1860
|
+
// Case-insensitive single-word skill name lookup (restricted to `skill-catalog` pages)
|
|
1861
|
+
for (const word of tokens.skillWords) {
|
|
1862
|
+
const pageIds = input.store.lookupSymbolPageIds(word, sessionKey);
|
|
1863
|
+
if (pageIds.length === 0)
|
|
1864
|
+
continue;
|
|
1865
|
+
const idf = computeIdf(pageIds.length);
|
|
1866
|
+
for (const pid of pageIds) {
|
|
1867
|
+
const page = input.store.getPage(pid, sessionKey);
|
|
1868
|
+
if (!page || page.toolName !== 'skill-catalog')
|
|
1869
|
+
continue;
|
|
1870
|
+
const sp = page.symbols[0];
|
|
1871
|
+
addOrFuseCandidate({
|
|
1872
|
+
page,
|
|
1873
|
+
matchedSymbol: word,
|
|
1874
|
+
targetLine: sp?.startLine ?? 1,
|
|
1875
|
+
spanStartLine: sp?.startLine ?? 1,
|
|
1876
|
+
spanEndLine: sp?.endLine ?? (sp?.startLine ?? 1),
|
|
1877
|
+
hasDeclSpan: Boolean(sp && sp.endLine > sp.startLine),
|
|
1878
|
+
score: 10 + 3 * idf,
|
|
1879
|
+
hasHighSignal: true,
|
|
1880
|
+
});
|
|
1881
|
+
}
|
|
1882
|
+
}
|
|
1883
|
+
// File basename fallback hits (for pages matched by path/filename)
|
|
1884
|
+
for (const [pid, info] of basenamePageInfo) {
|
|
1885
|
+
const page = input.store.getPage(pid, sessionKey);
|
|
1886
|
+
if (!page)
|
|
1887
|
+
continue;
|
|
1888
|
+
const sp = page.symbols[0];
|
|
1889
|
+
const hasDecl = Boolean(sp && sp.kind !== 'error' && sp.kind !== 'anchor' && sp.endLine > sp.startLine);
|
|
1890
|
+
addOrFuseCandidate({
|
|
1891
|
+
page,
|
|
1892
|
+
matchedSymbol: info.base,
|
|
1893
|
+
targetLine: sp?.startLine ?? 1,
|
|
1894
|
+
spanStartLine: sp?.startLine ?? 1,
|
|
1895
|
+
spanEndLine: sp?.endLine ?? (sp?.startLine ?? 1),
|
|
1896
|
+
hasDeclSpan: hasDecl,
|
|
1897
|
+
score: 4 + 2 * info.idf,
|
|
1898
|
+
hasHighSignal: symbolMatchedPageIds.has(pid),
|
|
1899
|
+
});
|
|
1900
|
+
}
|
|
1901
|
+
if (candidates.length === 0) {
|
|
1902
|
+
return { text: '', changed: false, slices: [], totalTokens: 0 };
|
|
1903
|
+
}
|
|
1904
|
+
candidates.sort((a, b) => b.score - a.score ||
|
|
1905
|
+
b.page.createdAtMs - a.page.createdAtMs ||
|
|
1906
|
+
(a.page.id < b.page.id ? -1 : a.page.id > b.page.id ? 1 : 0));
|
|
1907
|
+
const wrapperOverheadTokens = 16;
|
|
1908
|
+
let usedTokens = wrapperOverheadTokens;
|
|
1909
|
+
const emitted = [];
|
|
1910
|
+
const emittedChunks = [];
|
|
1911
|
+
const acceptedTargetsByPage = new Map();
|
|
1912
|
+
for (const cand of candidates) {
|
|
1913
|
+
if (emitted.length >= maxSlices)
|
|
1914
|
+
break;
|
|
1915
|
+
if (!cand.isExplicitPageId && !cand.hasHighSignal && cand.score < 9)
|
|
1916
|
+
continue;
|
|
1917
|
+
const { page } = cand;
|
|
1918
|
+
const prevTargets = acceptedTargetsByPage.get(page.id);
|
|
1919
|
+
if (prevTargets && prevTargets.some((t) => Math.abs(t - cand.targetLine) <= 15)) {
|
|
1920
|
+
continue;
|
|
1921
|
+
}
|
|
1922
|
+
const lines = page.rawText.split('\n');
|
|
1923
|
+
const totalLines = lines.length;
|
|
1924
|
+
if (totalLines === 0)
|
|
1925
|
+
continue;
|
|
1926
|
+
// Enclosing AST/symbol-boundary slicing when span bounds are known; otherwise ±15 window.
|
|
1927
|
+
let startLine = cand.hasDeclSpan
|
|
1928
|
+
? Math.max(1, cand.spanStartLine - 2)
|
|
1929
|
+
: Math.max(1, cand.targetLine - 15);
|
|
1930
|
+
let endLine = cand.hasDeclSpan
|
|
1931
|
+
? Math.min(totalLines, Math.min(cand.spanStartLine + 44, cand.spanEndLine + 2))
|
|
1932
|
+
: Math.min(totalLines, cand.targetLine + 15);
|
|
1933
|
+
let sliceBody = lines.slice(startLine - 1, endLine).join('\n');
|
|
1934
|
+
if (!sliceBody.trim() || isAlreadyVerbatim(page, sliceBody))
|
|
1935
|
+
continue;
|
|
1936
|
+
if (!cand.isExplicitPageId && input.store.isTlbSuppressed(sessionKey, page.id, startLine, endLine, tlbTurn)) {
|
|
1937
|
+
continue;
|
|
1938
|
+
}
|
|
1939
|
+
const label = page.filePath ?? page.refId;
|
|
1940
|
+
const makeChunk = (s, e, body) => `--- page ${page.id} (${label} L${s}-${e}, matched "${cand.matchedSymbol}") ---\n${body}`;
|
|
1941
|
+
let chunk = makeChunk(startLine, endLine, sliceBody);
|
|
1942
|
+
let chunkTokens = countTokensFast(chunk);
|
|
1943
|
+
// If a slice exceeds remaining budget, try exact span first, then shrink radius cleanly.
|
|
1944
|
+
if (usedTokens + chunkTokens > budgetTokens) {
|
|
1945
|
+
const remaining = budgetTokens - usedTokens;
|
|
1946
|
+
if (remaining < 48)
|
|
1947
|
+
continue;
|
|
1948
|
+
let fitted = false;
|
|
1949
|
+
if (cand.hasDeclSpan && cand.spanEndLine <= cand.spanStartLine + 42) {
|
|
1950
|
+
const sExact = Math.max(1, cand.spanStartLine);
|
|
1951
|
+
const eExact = Math.min(totalLines, cand.spanEndLine);
|
|
1952
|
+
const bExact = lines.slice(sExact - 1, eExact).join('\n');
|
|
1953
|
+
const cExact = makeChunk(sExact, eExact, bExact);
|
|
1954
|
+
const tExact = countTokensFast(cExact);
|
|
1955
|
+
if (tExact <= remaining) {
|
|
1956
|
+
startLine = sExact;
|
|
1957
|
+
endLine = eExact;
|
|
1958
|
+
sliceBody = bExact;
|
|
1959
|
+
chunk = cExact;
|
|
1960
|
+
chunkTokens = tExact;
|
|
1961
|
+
fitted = true;
|
|
1962
|
+
}
|
|
1963
|
+
}
|
|
1964
|
+
if (!fitted) {
|
|
1965
|
+
let radius = 10;
|
|
1966
|
+
while (radius >= 2) {
|
|
1967
|
+
const s2 = Math.max(1, cand.targetLine - radius);
|
|
1968
|
+
const e2 = Math.min(totalLines, cand.targetLine + radius);
|
|
1969
|
+
const b2 = lines.slice(s2 - 1, e2).join('\n');
|
|
1970
|
+
const c2 = makeChunk(s2, e2, b2);
|
|
1971
|
+
const t2 = countTokensFast(c2);
|
|
1972
|
+
if (t2 <= remaining) {
|
|
1973
|
+
startLine = s2;
|
|
1974
|
+
endLine = e2;
|
|
1975
|
+
sliceBody = b2;
|
|
1976
|
+
chunk = c2;
|
|
1977
|
+
chunkTokens = t2;
|
|
1978
|
+
fitted = true;
|
|
1979
|
+
break;
|
|
1980
|
+
}
|
|
1981
|
+
radius = Math.floor(radius / 2);
|
|
1982
|
+
}
|
|
1983
|
+
}
|
|
1984
|
+
if (!fitted)
|
|
1985
|
+
continue;
|
|
1986
|
+
}
|
|
1987
|
+
usedTokens += chunkTokens;
|
|
1988
|
+
const existingTargets = acceptedTargetsByPage.get(page.id);
|
|
1989
|
+
if (existingTargets)
|
|
1990
|
+
existingTargets.push(cand.targetLine);
|
|
1991
|
+
else
|
|
1992
|
+
acceptedTargetsByPage.set(page.id, [cand.targetLine]);
|
|
1993
|
+
emitted.push({
|
|
1994
|
+
pageId: page.id,
|
|
1995
|
+
refId: page.refId,
|
|
1996
|
+
...(page.filePath !== undefined ? { filePath: page.filePath } : {}),
|
|
1997
|
+
matchedSymbol: cand.matchedSymbol,
|
|
1998
|
+
startLine,
|
|
1999
|
+
endLine,
|
|
2000
|
+
text: sliceBody,
|
|
2001
|
+
tokens: chunkTokens,
|
|
2002
|
+
});
|
|
2003
|
+
input.store.recordHydrationLease(sessionKey, page.id, startLine, endLine, tlbTurn);
|
|
2004
|
+
emittedChunks.push(chunk);
|
|
2005
|
+
}
|
|
2006
|
+
if (emitted.length === 0) {
|
|
2007
|
+
return { text: '', changed: false, slices: [], totalTokens: 0 };
|
|
2008
|
+
}
|
|
2009
|
+
const text = `[fiche vm-hydrate]\n${emittedChunks.join('\n')}\n[/fiche vm-hydrate]`;
|
|
2010
|
+
const totalTokens = countTokensFast(text);
|
|
2011
|
+
input.store.recordTailHydration(totalTokens);
|
|
2012
|
+
return {
|
|
2013
|
+
text,
|
|
2014
|
+
changed: true,
|
|
2015
|
+
slices: emitted,
|
|
2016
|
+
totalTokens,
|
|
2017
|
+
};
|
|
2018
|
+
}
|
|
2019
|
+
const FILE_READ_TOOL_RE = /^(?:read|read_?file|view_?file|view_?file_?outline|view_?code_?item|cat|get_?file_?contents|get_?file|read_?text_?file|read_?resource|open_?file|fs_?read|file_?read|show_?file|inspect_?file)$/i;
|
|
2020
|
+
/** True when a tool name represents a file/resource read whose contents must not trigger checkpoints or whitespace rewrites. */
|
|
2021
|
+
export function isFileReadToolName(name) {
|
|
2022
|
+
if (!name)
|
|
2023
|
+
return false;
|
|
2024
|
+
const trimmed = name.trim();
|
|
2025
|
+
const bare = trimmed.split(/(?:__|[.:/])/).pop() ?? trimmed;
|
|
2026
|
+
return FILE_READ_TOOL_RE.test(bare);
|
|
2027
|
+
}
|
|
2028
|
+
const MARKOV_CHECKPOINT_TOOL_RE = /^(?:bash|sh|zsh|shell|terminal|cmd|command|exec(?:ute)?(?:_?command)?|run(?:_?command|_?shell|_?tests?)?|test(?:s|ing)?|verify|check|git|gh|pr|ci|vitest|jest|pytest|cargo|npm|pnpm|yarn|bun|make|gradle|mvn)$/i;
|
|
2029
|
+
function isMarkovCheckpointToolName(toolName) {
|
|
2030
|
+
if (!toolName)
|
|
2031
|
+
return true;
|
|
2032
|
+
if (isFileReadToolName(toolName))
|
|
2033
|
+
return false;
|
|
2034
|
+
const trimmed = toolName.trim();
|
|
2035
|
+
const bare = trimmed.split(/(?:__|[.:/])/).pop() ?? trimmed;
|
|
2036
|
+
if (MARKOV_CHECKPOINT_TOOL_RE.test(bare))
|
|
2037
|
+
return true;
|
|
2038
|
+
return /(?:^|[_-])(bash|shell|exec|command|git|gh|test|verify|check)(?:$|[_-])/i.test(bare);
|
|
2039
|
+
}
|
|
2040
|
+
const stickyMarkovEpisodes = new Set();
|
|
2041
|
+
const stickyMarkovCertificates = new Map();
|
|
2042
|
+
const stickyMarkovSessions = new Set();
|
|
2043
|
+
function addStickyMarkovSession(sessionKey) {
|
|
2044
|
+
if (stickyMarkovSessions.has(sessionKey)) {
|
|
2045
|
+
stickyMarkovSessions.delete(sessionKey);
|
|
2046
|
+
}
|
|
2047
|
+
else if (stickyMarkovSessions.size >= STICKY_EPISODE_CAP) {
|
|
2048
|
+
const oldest = stickyMarkovSessions.values().next().value;
|
|
2049
|
+
if (oldest !== undefined)
|
|
2050
|
+
stickyMarkovSessions.delete(oldest);
|
|
2051
|
+
}
|
|
2052
|
+
stickyMarkovSessions.add(sessionKey);
|
|
2053
|
+
}
|
|
2054
|
+
/** O(1) check for whether this session has ever folded a Markovian episode. */
|
|
2055
|
+
export function hasAnyStickyMarkovEpisode(sessionKey) {
|
|
2056
|
+
const key = sessionKey?.trim() || 'default';
|
|
2057
|
+
const hit = stickyMarkovSessions.has(key);
|
|
2058
|
+
if (hit) {
|
|
2059
|
+
stickyMarkovSessions.delete(key);
|
|
2060
|
+
stickyMarkovSessions.add(key);
|
|
2061
|
+
return true;
|
|
2062
|
+
}
|
|
2063
|
+
return hasAnyFoldedEpisodeId(sessionKey);
|
|
2064
|
+
}
|
|
2065
|
+
/** Test helper: clear sticky Markovian episode seal memory. */
|
|
2066
|
+
export function clearStickyMarkovEpisodesForTests() {
|
|
2067
|
+
stickyMarkovEpisodes.clear();
|
|
2068
|
+
stickyMarkovCertificates.clear();
|
|
2069
|
+
stickyMarkovSessions.clear();
|
|
2070
|
+
}
|
|
2071
|
+
const GIT_COMMIT_HEADER_TAIL_RE = /^\[[^\]\r\n]+\s+[0-9a-f]{7,40}\]$/;
|
|
2072
|
+
const GIT_FILES_CHANGED_RE = /\b\d+\s+files?\s+changed\b|\b(?:insertions?\(\+\)|deletions?\(-\))\b/i;
|
|
2073
|
+
const COMMIT_BRACKET_RE = /^\s*\[commit\b[^\]]*\]/im;
|
|
2074
|
+
const PR_MERGE_RE = /(?:Squashed and merged pull request|Merged pull request)/i;
|
|
2075
|
+
/** Strict O(N) scan for `[branch deadbeef]` git-commit headers (zero backtracking). */
|
|
2076
|
+
function hasGitCommitHeader(text) {
|
|
2077
|
+
let lineStart = 0;
|
|
2078
|
+
while (lineStart < text.length) {
|
|
2079
|
+
const nl = text.indexOf('\n', lineStart);
|
|
2080
|
+
const lineEnd = nl >= 0 ? nl : text.length;
|
|
2081
|
+
if (text.charCodeAt(lineStart) === 91 /* '[' */) {
|
|
2082
|
+
const limit = Math.min(lineEnd, lineStart + 200);
|
|
2083
|
+
const close = text.indexOf(']', lineStart + 1);
|
|
2084
|
+
if (close > lineStart + 1 && close < limit) {
|
|
2085
|
+
if (GIT_COMMIT_HEADER_TAIL_RE.test(text.slice(lineStart, close + 1))) {
|
|
2086
|
+
return true;
|
|
2087
|
+
}
|
|
2088
|
+
}
|
|
2089
|
+
}
|
|
2090
|
+
if (nl < 0)
|
|
2091
|
+
break;
|
|
2092
|
+
lineStart = nl + 1;
|
|
2093
|
+
}
|
|
2094
|
+
return false;
|
|
2095
|
+
}
|
|
2096
|
+
const FAIL_SIGNAL_RE = /\b(?:FAIL(?:ED)?|AssertionError|TypeError|SyntaxError|ReferenceError|ERR_[A-Z0-9_]+|exit[_ ]?code[:=\s]+[1-9]\d*|returned [1-9]\d*|[1-9]\d*\s+failed)\b|^\s*×\s+\S|Traceback \(most recent call last\)/im;
|
|
2097
|
+
const PASS_SUMMARY_RE = /(?:Test Files\s+\d+\s+passed|Tests\s+\d+\s+passed|\b\d+\s+passing\b|0 failed|\bAll \d+ tests? passed\b)/i;
|
|
2098
|
+
const ANY_ACTIVE_FAILURE_RE = /\b(?:[1-9]\d*\s+failed|FAIL(?:ED)?)\b/;
|
|
2099
|
+
function isGitCommitCheckpoint(text) {
|
|
2100
|
+
if (COMMIT_BRACKET_RE.test(text))
|
|
2101
|
+
return true;
|
|
2102
|
+
return hasGitCommitHeader(text) && GIT_FILES_CHANGED_RE.test(text);
|
|
2103
|
+
}
|
|
2104
|
+
function isPrMergeCheckpoint(text) {
|
|
2105
|
+
return PR_MERGE_RE.test(text);
|
|
2106
|
+
}
|
|
2107
|
+
function isGreenVerificationCheckpoint(text, sawPriorFailure) {
|
|
2108
|
+
if (!sawPriorFailure)
|
|
2109
|
+
return false;
|
|
2110
|
+
return PASS_SUMMARY_RE.test(text) && !ANY_ACTIVE_FAILURE_RE.test(text);
|
|
2111
|
+
}
|
|
2112
|
+
function alreadyFoldedOrCompactedMarker(text) {
|
|
2113
|
+
return (text.startsWith('[fiche causal-episode ') ||
|
|
2114
|
+
text.startsWith('[folded into ') ||
|
|
2115
|
+
text.startsWith('[fiche cas') ||
|
|
2116
|
+
text.startsWith('[fiche epoch-digest') ||
|
|
2117
|
+
text.startsWith('[fiche vm-page ') ||
|
|
2118
|
+
text.startsWith('[inkling cas') ||
|
|
2119
|
+
text.startsWith('[inkling epoch-digest'));
|
|
2120
|
+
}
|
|
2121
|
+
/**
|
|
2122
|
+
* Fold completed intermediate debugging spans preceding Markovian checkpoints
|
|
2123
|
+
* (`git commit`, red -> green verification, PR merge) into deterministic causal
|
|
2124
|
+
* certificates while preserving the checkpoint block and raw pages in `ContextPageStore`.
|
|
2125
|
+
*/
|
|
2126
|
+
export function foldMarkovianEpisodes(args) {
|
|
2127
|
+
const keepTail = args.keepTailMessages ?? 6;
|
|
2128
|
+
const cutoffMsg = args.totalMessages - keepTail;
|
|
2129
|
+
if (cutoffMsg <= 1 || args.blocks.length === 0) {
|
|
2130
|
+
return {
|
|
2131
|
+
changed: false,
|
|
2132
|
+
foldedEpisodes: 0,
|
|
2133
|
+
foldedBlocks: 0,
|
|
2134
|
+
savedChars: 0,
|
|
2135
|
+
savedTokens: 0,
|
|
2136
|
+
episodeIds: [],
|
|
2137
|
+
};
|
|
2138
|
+
}
|
|
2139
|
+
const closedBlocks = args.blocks
|
|
2140
|
+
.filter((b) => b.msgIndex > 0 && b.msgIndex < cutoffMsg)
|
|
2141
|
+
.sort((a, b) => a.msgIndex - b.msgIndex);
|
|
2142
|
+
if (closedBlocks.length < 4) {
|
|
2143
|
+
return {
|
|
2144
|
+
changed: false,
|
|
2145
|
+
foldedEpisodes: 0,
|
|
2146
|
+
foldedBlocks: 0,
|
|
2147
|
+
savedChars: 0,
|
|
2148
|
+
savedTokens: 0,
|
|
2149
|
+
episodeIds: [],
|
|
2150
|
+
};
|
|
2151
|
+
}
|
|
2152
|
+
const episodes = [];
|
|
2153
|
+
let pending = [];
|
|
2154
|
+
let firstFailureIdx = -1;
|
|
2155
|
+
for (const block of closedBlocks) {
|
|
2156
|
+
const raw = block.getText();
|
|
2157
|
+
if (alreadyFoldedOrCompactedMarker(raw)) {
|
|
2158
|
+
pending = [];
|
|
2159
|
+
firstFailureIdx = -1;
|
|
2160
|
+
continue;
|
|
2161
|
+
}
|
|
2162
|
+
const checkpointAllowed = isMarkovCheckpointToolName(block.toolName);
|
|
2163
|
+
const isCommitOrMerge = checkpointAllowed && (isGitCommitCheckpoint(raw) || isPrMergeCheckpoint(raw));
|
|
2164
|
+
const isGreen = checkpointAllowed && !isCommitOrMerge && isGreenVerificationCheckpoint(raw, firstFailureIdx >= 0);
|
|
2165
|
+
if (isCommitOrMerge || isGreen) {
|
|
2166
|
+
const slice = isGreen && firstFailureIdx >= 0 ? pending.slice(firstFailureIdx) : pending;
|
|
2167
|
+
const sliceChars = slice.reduce((s, p) => s + p.raw.length, 0);
|
|
2168
|
+
if (slice.length >= 3 && sliceChars >= 4000) {
|
|
2169
|
+
episodes.push({
|
|
2170
|
+
predecessors: slice,
|
|
2171
|
+
checkpoint: { block, raw },
|
|
2172
|
+
});
|
|
2173
|
+
}
|
|
2174
|
+
pending = [];
|
|
2175
|
+
firstFailureIdx = -1;
|
|
2176
|
+
continue;
|
|
2177
|
+
}
|
|
2178
|
+
if (firstFailureIdx < 0 && checkpointAllowed && FAIL_SIGNAL_RE.test(raw)) {
|
|
2179
|
+
firstFailureIdx = pending.length;
|
|
2180
|
+
}
|
|
2181
|
+
pending.push({ block, raw, rawTokens: countTokensFast(raw) });
|
|
2182
|
+
}
|
|
2183
|
+
if (episodes.length === 0) {
|
|
2184
|
+
return {
|
|
2185
|
+
changed: false,
|
|
2186
|
+
foldedEpisodes: 0,
|
|
2187
|
+
foldedBlocks: 0,
|
|
2188
|
+
savedChars: 0,
|
|
2189
|
+
savedTokens: 0,
|
|
2190
|
+
episodeIds: [],
|
|
2191
|
+
};
|
|
2192
|
+
}
|
|
2193
|
+
const blockTokens = new Map();
|
|
2194
|
+
let toolBlockSum = 0;
|
|
2195
|
+
let runningPrompt = args.totalPromptTokens ?? 0;
|
|
2196
|
+
const computeTotalPrompt = args.totalPromptTokens === undefined;
|
|
2197
|
+
for (const b of args.blocks) {
|
|
2198
|
+
const tok = countTokensFast(b.getText());
|
|
2199
|
+
blockTokens.set(b, tok);
|
|
2200
|
+
toolBlockSum += tok;
|
|
2201
|
+
if (computeTotalPrompt)
|
|
2202
|
+
runningPrompt += tok;
|
|
2203
|
+
}
|
|
2204
|
+
const nonToolPromptTokens = args.totalPromptTokens !== undefined ? Math.max(0, args.totalPromptTokens - toolBlockSum) : 0;
|
|
2205
|
+
const rates = resolvePriceRates(args.model, { promptTokens: 0, ttlSec: args.ttlSec });
|
|
2206
|
+
const expectedOut = args.expectedOutputTokens ?? 1000;
|
|
2207
|
+
const sessionKey = args.sessionKey?.trim() || 'default';
|
|
2208
|
+
let foldedEpisodes = 0;
|
|
2209
|
+
let foldedBlocks = 0;
|
|
2210
|
+
let totalSavedChars = 0;
|
|
2211
|
+
let totalSavedTokens = 0;
|
|
2212
|
+
const episodeIds = [];
|
|
2213
|
+
for (const ep of episodes) {
|
|
2214
|
+
const signatureSource = ep.predecessors.map((p) => `${p.block.refId}:${p.raw.length}:${fnv64Hex(p.raw)}`).join('|') +
|
|
2215
|
+
`->${ep.checkpoint.block.refId}:${fnv64Hex(ep.checkpoint.raw)}`;
|
|
2216
|
+
const epId = `ep_${fnv64Hex(signatureSource).slice(0, 10)}`;
|
|
2217
|
+
const stickyKey = `${sessionKey}\0${args.model ?? ''}\0${epId}`;
|
|
2218
|
+
const alreadySealed = stickyMarkovEpisodes.has(stickyKey) || hasFoldedEpisodeId(args.sessionKey, stickyKey);
|
|
2219
|
+
if (args.stickyOnly && !alreadySealed)
|
|
2220
|
+
continue;
|
|
2221
|
+
const frozenCertificate = alreadySealed
|
|
2222
|
+
? (stickyMarkovCertificates.get(stickyKey) ?? getFoldedEpisodeCertificate(args.sessionKey, stickyKey))
|
|
2223
|
+
: undefined;
|
|
2224
|
+
// Write the causal certificate into the longest predecessor; skip tiny blocks that would bloat.
|
|
2225
|
+
let certIdx = 0;
|
|
2226
|
+
for (let k = 1; k < ep.predecessors.length; k++) {
|
|
2227
|
+
if (ep.predecessors[k].raw.length > ep.predecessors[certIdx].raw.length) {
|
|
2228
|
+
certIdx = k;
|
|
2229
|
+
}
|
|
2230
|
+
}
|
|
2231
|
+
const continuationMarker = `[folded into ${epId}]`;
|
|
2232
|
+
const replaceableIndices = [certIdx];
|
|
2233
|
+
for (let k = 0; k < ep.predecessors.length; k++) {
|
|
2234
|
+
if (k !== certIdx && ep.predecessors[k].raw.length > continuationMarker.length + 8) {
|
|
2235
|
+
replaceableIndices.push(k);
|
|
2236
|
+
}
|
|
2237
|
+
}
|
|
2238
|
+
replaceableIndices.sort((a, b) => a - b);
|
|
2239
|
+
const pgIds = [];
|
|
2240
|
+
const touchedSet = new Set();
|
|
2241
|
+
const predMeta = new Map();
|
|
2242
|
+
for (const idx of replaceableIndices) {
|
|
2243
|
+
const pred = ep.predecessors[idx];
|
|
2244
|
+
pgIds.push(pageIdForText(pred.raw));
|
|
2245
|
+
const fp = inferFilePath(pred.raw, pred.block.refId);
|
|
2246
|
+
if (fp && touchedSet.size < 12)
|
|
2247
|
+
touchedSet.add(fp);
|
|
2248
|
+
const syms = extractSymbolSpans(pred.raw);
|
|
2249
|
+
predMeta.set(idx, { filePath: fp, symbols: syms });
|
|
2250
|
+
for (const s of syms) {
|
|
2251
|
+
if (s.kind !== 'error' && s.kind !== 'anchor') {
|
|
2252
|
+
touchedSet.add(s.name);
|
|
2253
|
+
if (touchedSet.size >= 12)
|
|
2254
|
+
break;
|
|
2255
|
+
}
|
|
2256
|
+
}
|
|
2257
|
+
}
|
|
2258
|
+
const touchedSummary = touchedSet.size > 0 ? [...touchedSet].join(', ') : 'none';
|
|
2259
|
+
const cpRef = ep.checkpoint.block.refId;
|
|
2260
|
+
const formatCertificate = (ids) => {
|
|
2261
|
+
const pageSummary = ids.length > 0 ? ids.join(', ') : 'none';
|
|
2262
|
+
return (`[fiche causal-episode ${epId}: folded ${replaceableIndices.length} intermediate debug steps ` +
|
|
2263
|
+
`before verified checkpoint ${cpRef}; archived pages: ${pageSummary}; ` +
|
|
2264
|
+
`touched symbols/paths: ${touchedSummary}]`);
|
|
2265
|
+
};
|
|
2266
|
+
let certificate = frozenCertificate ?? formatCertificate(pgIds);
|
|
2267
|
+
if (certificate.length >= ep.predecessors[certIdx].raw.length)
|
|
2268
|
+
continue;
|
|
2269
|
+
const rawChars = replaceableIndices.reduce((s, idx) => s + ep.predecessors[idx].raw.length, 0);
|
|
2270
|
+
const rawTok = replaceableIndices.reduce((s, idx) => s + ep.predecessors[idx].rawTokens, 0);
|
|
2271
|
+
let foldedChars = certificate.length + Math.max(0, replaceableIndices.length - 1) * continuationMarker.length;
|
|
2272
|
+
let foldedTok = countTokensFast(certificate) +
|
|
2273
|
+
Math.max(0, replaceableIndices.length - 1) * countTokensFast(continuationMarker);
|
|
2274
|
+
if (foldedChars >= rawChars || foldedTok >= rawTok)
|
|
2275
|
+
continue;
|
|
2276
|
+
const lastReplacedBlock = ep.predecessors[replaceableIndices[replaceableIndices.length - 1]].block;
|
|
2277
|
+
let coveringTtlSec = 0;
|
|
2278
|
+
let horizonEndMsg = args.totalMessages - 2;
|
|
2279
|
+
if (args.cacheBreakpoints && args.cacheBreakpoints.length > 0) {
|
|
2280
|
+
const lastReplacedBlockIdx = lastReplacedBlock.blockIndex ?? 0;
|
|
2281
|
+
let maxBpMsg = -1;
|
|
2282
|
+
for (const bp of args.cacheBreakpoints) {
|
|
2283
|
+
if (bp.msgIndex > lastReplacedBlock.msgIndex || (bp.msgIndex === lastReplacedBlock.msgIndex && bp.blockIndex >= lastReplacedBlockIdx)) {
|
|
2284
|
+
if (bp.ttlSec > coveringTtlSec)
|
|
2285
|
+
coveringTtlSec = bp.ttlSec;
|
|
2286
|
+
if (bp.msgIndex > maxBpMsg)
|
|
2287
|
+
maxBpMsg = bp.msgIndex;
|
|
2288
|
+
}
|
|
2289
|
+
}
|
|
2290
|
+
if (maxBpMsg >= 0) {
|
|
2291
|
+
horizonEndMsg = Math.max(horizonEndMsg, Math.min(args.totalMessages - 1, maxBpMsg));
|
|
2292
|
+
}
|
|
2293
|
+
}
|
|
2294
|
+
const effectiveTtlSec = Math.max(args.ttlSec ?? 0, coveringTtlSec) || undefined;
|
|
2295
|
+
const epRates = effectiveTtlSec !== args.ttlSec
|
|
2296
|
+
? resolvePriceRates(args.model, { promptTokens: 0, ttlSec: effectiveTtlSec })
|
|
2297
|
+
: rates;
|
|
2298
|
+
if (!alreadySealed && args.sessionCacheCold !== true) {
|
|
2299
|
+
let downstreamCachedTokens = 0;
|
|
2300
|
+
if (args.msgTotalTokens && args.msgTotalTokens.length > 0) {
|
|
2301
|
+
const limit = Math.min(args.msgTotalTokens.length - 1, horizonEndMsg);
|
|
2302
|
+
for (let m = ep.checkpoint.block.msgIndex; m <= limit; m++) {
|
|
2303
|
+
downstreamCachedTokens += args.msgTotalTokens[m] ?? 0;
|
|
2304
|
+
}
|
|
2305
|
+
}
|
|
2306
|
+
else {
|
|
2307
|
+
for (const b of args.blocks) {
|
|
2308
|
+
if (b.msgIndex >= ep.checkpoint.block.msgIndex && b.msgIndex <= horizonEndMsg) {
|
|
2309
|
+
downstreamCachedTokens += blockTokens.get(b) ?? 0;
|
|
2310
|
+
}
|
|
2311
|
+
}
|
|
2312
|
+
if (nonToolPromptTokens > 0 && args.totalMessages > 2) {
|
|
2313
|
+
const spanRatio = Math.max(0, Math.min(1, (args.totalMessages - 2 - ep.predecessors[0].block.msgIndex) / Math.max(1, args.totalMessages)));
|
|
2314
|
+
downstreamCachedTokens += Math.round(nonToolPromptTokens * spanRatio);
|
|
2315
|
+
}
|
|
2316
|
+
}
|
|
2317
|
+
const isAutoCacheOpenAI = !(args.cacheBreakpoints && args.cacheBreakpoints.length > 0) &&
|
|
2318
|
+
args.ttlSec === undefined &&
|
|
2319
|
+
isAutoCacheOpenAIModel(args.model);
|
|
2320
|
+
const effectiveWriteRate = isAutoCacheOpenAI ? Math.min(epRates.write, 1) : epRates.write;
|
|
2321
|
+
const savedTok = rawTok - foldedTok;
|
|
2322
|
+
const savedPerRead = savedTok * epRates.read;
|
|
2323
|
+
const transitionCost = foldedTok * effectiveWriteRate -
|
|
2324
|
+
rawTok * epRates.read +
|
|
2325
|
+
downstreamCachedTokens * (effectiveWriteRate - epRates.read);
|
|
2326
|
+
const paybackReads = savedPerRead > 0 ? Math.ceil(Math.max(0, transitionCost) / savedPerRead) : Infinity;
|
|
2327
|
+
const cliff = evaluateCliffAvoidance(args.model, {
|
|
2328
|
+
promptTokensBefore: runningPrompt,
|
|
2329
|
+
promptTokensAfter: Math.max(0, runningPrompt - savedTok),
|
|
2330
|
+
collapsedBaselineTokens: rawTok,
|
|
2331
|
+
collapsedActualTokens: foldedTok,
|
|
2332
|
+
downstreamCachedTokens,
|
|
2333
|
+
expectedOutputTokens: expectedOut,
|
|
2334
|
+
ttlSec: effectiveTtlSec,
|
|
2335
|
+
});
|
|
2336
|
+
const cliffWins = Boolean(cliff?.crossesCliff && cliff.netSingleTurnUsd > 0);
|
|
2337
|
+
if (coveringTtlSec >= 3600 && savedTok < 2000 && !cliffWins)
|
|
2338
|
+
continue;
|
|
2339
|
+
let effectiveMaxPayback = computeHorizonPaybackLimit({
|
|
2340
|
+
turnsObserved: Math.max(1, Math.floor(args.totalMessages / 2)),
|
|
2341
|
+
baseMaxPayback: 12,
|
|
2342
|
+
downstreamCachedTokens,
|
|
2343
|
+
});
|
|
2344
|
+
if (coveringTtlSec >= 3600 && downstreamCachedTokens >= 20_000) {
|
|
2345
|
+
effectiveMaxPayback = Math.min(effectiveMaxPayback, 8);
|
|
2346
|
+
}
|
|
2347
|
+
if (paybackReads > effectiveMaxPayback && !cliffWins)
|
|
2348
|
+
continue;
|
|
2349
|
+
}
|
|
2350
|
+
// Archive raw pages into ContextPageStore ONLY after payback gate passes.
|
|
2351
|
+
// On replay of an already-sealed episode, preserve the frozen certificate bytes verbatim
|
|
2352
|
+
// so page eviction never changes replayed prefix bytes.
|
|
2353
|
+
if (args.store && !frozenCertificate) {
|
|
2354
|
+
const residentIds = [];
|
|
2355
|
+
for (const idx of replaceableIndices) {
|
|
2356
|
+
const pred = ep.predecessors[idx];
|
|
2357
|
+
const meta = predMeta.get(idx);
|
|
2358
|
+
const stored = args.store.storePage({
|
|
2359
|
+
sessionKey,
|
|
2360
|
+
refId: pred.block.refId,
|
|
2361
|
+
toolName: pred.block.toolName,
|
|
2362
|
+
filePath: meta?.filePath,
|
|
2363
|
+
rawText: pred.raw,
|
|
2364
|
+
});
|
|
2365
|
+
if (args.store.getPage(stored.id, sessionKey)) {
|
|
2366
|
+
residentIds.push(stored.id);
|
|
2367
|
+
}
|
|
2368
|
+
}
|
|
2369
|
+
if (!alreadySealed && residentIds.length !== pgIds.length) {
|
|
2370
|
+
certificate = formatCertificate(residentIds);
|
|
2371
|
+
if (certificate.length >= ep.predecessors[certIdx].raw.length)
|
|
2372
|
+
continue;
|
|
2373
|
+
foldedChars = certificate.length + Math.max(0, replaceableIndices.length - 1) * continuationMarker.length;
|
|
2374
|
+
foldedTok =
|
|
2375
|
+
countTokensFast(certificate) +
|
|
2376
|
+
Math.max(0, replaceableIndices.length - 1) * countTokensFast(continuationMarker);
|
|
2377
|
+
if (foldedChars >= rawChars || foldedTok >= rawTok)
|
|
2378
|
+
continue;
|
|
2379
|
+
}
|
|
2380
|
+
}
|
|
2381
|
+
// Apply fold across replaced predecessor blocks; checkpoint block stays untouched.
|
|
2382
|
+
ep.predecessors[certIdx].block.setText(certificate);
|
|
2383
|
+
for (const idx of replaceableIndices) {
|
|
2384
|
+
if (idx !== certIdx) {
|
|
2385
|
+
ep.predecessors[idx].block.setText(continuationMarker);
|
|
2386
|
+
}
|
|
2387
|
+
}
|
|
2388
|
+
if (stickyMarkovEpisodes.has(stickyKey)) {
|
|
2389
|
+
stickyMarkovEpisodes.delete(stickyKey);
|
|
2390
|
+
}
|
|
2391
|
+
else if (stickyMarkovEpisodes.size >= STICKY_EPISODE_CAP) {
|
|
2392
|
+
const oldest = stickyMarkovEpisodes.values().next().value;
|
|
2393
|
+
if (oldest !== undefined) {
|
|
2394
|
+
stickyMarkovEpisodes.delete(oldest);
|
|
2395
|
+
stickyMarkovCertificates.delete(oldest);
|
|
2396
|
+
}
|
|
2397
|
+
}
|
|
2398
|
+
stickyMarkovEpisodes.add(stickyKey);
|
|
2399
|
+
stickyMarkovCertificates.delete(stickyKey);
|
|
2400
|
+
stickyMarkovCertificates.set(stickyKey, certificate);
|
|
2401
|
+
addStickyMarkovSession(sessionKey);
|
|
2402
|
+
recordFoldedEpisodeId(args.sessionKey, stickyKey, certificate);
|
|
2403
|
+
const savedChars = rawChars - foldedChars;
|
|
2404
|
+
const savedTokens = rawTok - foldedTok;
|
|
2405
|
+
foldedEpisodes += 1;
|
|
2406
|
+
foldedBlocks += replaceableIndices.length;
|
|
2407
|
+
totalSavedChars += savedChars;
|
|
2408
|
+
totalSavedTokens += savedTokens;
|
|
2409
|
+
runningPrompt = Math.max(0, runningPrompt - savedTokens);
|
|
2410
|
+
episodeIds.push(epId);
|
|
2411
|
+
args.store?.recordMarkovFold(savedChars);
|
|
2412
|
+
}
|
|
2413
|
+
return {
|
|
2414
|
+
changed: foldedEpisodes > 0,
|
|
2415
|
+
foldedEpisodes,
|
|
2416
|
+
foldedBlocks,
|
|
2417
|
+
savedChars: totalSavedChars,
|
|
2418
|
+
savedTokens: totalSavedTokens,
|
|
2419
|
+
episodeIds,
|
|
2420
|
+
};
|
|
2421
|
+
}
|
|
2422
|
+
const DEFAULT_CORE_SKILLS = new Set(['accidental-data-loss-prevention', 'fiche']);
|
|
2423
|
+
const SKILL_ENTRY_HEAD_RE = /^-\s+([A-Za-z0-9][A-Za-z0-9._-]{1,80})(?:\s+\(([^)\n]+)\))?\s*:\s*(.*)$/;
|
|
2424
|
+
const SKILL_STOPWORDS = new Set([
|
|
2425
|
+
'the', 'and', 'for', 'with', 'from', 'that', 'this', 'use', 'when', 'you', 'are',
|
|
2426
|
+
'not', 'can', 'will', 'any', 'all', 'into', 'your', 'about', 'have', 'only', 'user',
|
|
2427
|
+
]);
|
|
2428
|
+
function tokenizeQueryWords(text) {
|
|
2429
|
+
const out = new Set();
|
|
2430
|
+
const spaced = text.replace(/([a-z])([A-Z])/g, '$1 $2').toLowerCase();
|
|
2431
|
+
for (const part of spaced.split(/[^a-z0-9]+/)) {
|
|
2432
|
+
if (part.length >= 2 && !SKILL_STOPWORDS.has(part)) {
|
|
2433
|
+
out.add(part);
|
|
2434
|
+
}
|
|
2435
|
+
}
|
|
2436
|
+
// Also preserve common extension signals (.sqlx -> sqlx, .tf -> terraform, etc.)
|
|
2437
|
+
const lower = text.toLowerCase();
|
|
2438
|
+
if (lower.includes('.sqlx') || lower.includes('sqlx'))
|
|
2439
|
+
out.add('dataform');
|
|
2440
|
+
if (lower.includes('.ipynb'))
|
|
2441
|
+
out.add('notebook');
|
|
2442
|
+
if (lower.includes('.py'))
|
|
2443
|
+
out.add('python');
|
|
2444
|
+
if (lower.includes('.tf'))
|
|
2445
|
+
out.add('terraform');
|
|
2446
|
+
if (lower.includes('dockerfile'))
|
|
2447
|
+
out.add('docker');
|
|
2448
|
+
return [...out];
|
|
2449
|
+
}
|
|
2450
|
+
function parseSkillCatalogEntries(lines) {
|
|
2451
|
+
const entries = [];
|
|
2452
|
+
let currentStart = -1;
|
|
2453
|
+
let currentName = '';
|
|
2454
|
+
let currentPath;
|
|
2455
|
+
let inSkillsXml = false;
|
|
2456
|
+
let inAvailableHeader = false;
|
|
2457
|
+
const flushCurrent = (endLineExclusive) => {
|
|
2458
|
+
if (currentStart < 0)
|
|
2459
|
+
return;
|
|
2460
|
+
// Trim trailing blank lines out of the entry so separator spacing stays intact
|
|
2461
|
+
let last = endLineExclusive - 1;
|
|
2462
|
+
while (last > currentStart && lines[last].trim() === '') {
|
|
2463
|
+
last -= 1;
|
|
2464
|
+
}
|
|
2465
|
+
entries.push({
|
|
2466
|
+
name: currentName,
|
|
2467
|
+
...(currentPath ? { skillPath: currentPath } : {}),
|
|
2468
|
+
startLine: currentStart,
|
|
2469
|
+
endLine: last,
|
|
2470
|
+
rawEntry: lines.slice(currentStart, last + 1).join('\n'),
|
|
2471
|
+
catalogIndex: entries.length,
|
|
2472
|
+
});
|
|
2473
|
+
currentStart = -1;
|
|
2474
|
+
currentName = '';
|
|
2475
|
+
currentPath = undefined;
|
|
2476
|
+
};
|
|
2477
|
+
for (let i = 0; i < lines.length; i++) {
|
|
2478
|
+
const line = lines[i];
|
|
2479
|
+
const trimmed = line.trim();
|
|
2480
|
+
if (trimmed === '<skills>' || /^Available skills:\s*$/i.test(trimmed)) {
|
|
2481
|
+
if (trimmed === '<skills>')
|
|
2482
|
+
inSkillsXml = true;
|
|
2483
|
+
else
|
|
2484
|
+
inAvailableHeader = true;
|
|
2485
|
+
continue;
|
|
2486
|
+
}
|
|
2487
|
+
if (trimmed === '</skills>') {
|
|
2488
|
+
flushCurrent(i);
|
|
2489
|
+
inSkillsXml = false;
|
|
2490
|
+
inAvailableHeader = false;
|
|
2491
|
+
continue;
|
|
2492
|
+
}
|
|
2493
|
+
const headMatch = SKILL_ENTRY_HEAD_RE.exec(line);
|
|
2494
|
+
if (headMatch && (inSkillsXml || inAvailableHeader || (headMatch[2] !== undefined && /SKILL\.md$/i.test(headMatch[2])))) {
|
|
2495
|
+
flushCurrent(i);
|
|
2496
|
+
currentStart = i;
|
|
2497
|
+
currentName = headMatch[1];
|
|
2498
|
+
currentPath = headMatch[2]?.trim();
|
|
2499
|
+
continue;
|
|
2500
|
+
}
|
|
2501
|
+
if (currentStart >= 0) {
|
|
2502
|
+
// Detect clean end of skill list outside `<skills>` block
|
|
2503
|
+
if (!inSkillsXml && /^<\/[A-Za-z_][\w-]*>$/.test(trimmed)) {
|
|
2504
|
+
flushCurrent(i);
|
|
2505
|
+
inAvailableHeader = false;
|
|
2506
|
+
continue;
|
|
2507
|
+
}
|
|
2508
|
+
if (!inSkillsXml && /^#{1,3}\s+\S/.test(trimmed)) {
|
|
2509
|
+
flushCurrent(i);
|
|
2510
|
+
inAvailableHeader = false;
|
|
2511
|
+
continue;
|
|
2512
|
+
}
|
|
2513
|
+
if (!inSkillsXml && i > 0 && lines[i - 1].trim() === '' && trimmed !== '' && !/^(?:\s|[-*]|\d+\.)/.test(line)) {
|
|
2514
|
+
// Peek ahead up to 12 lines: if no new `- skill-name` entry follows, section ended
|
|
2515
|
+
let moreSkills = false;
|
|
2516
|
+
for (let k = i + 1; k < Math.min(lines.length, i + 15); k++) {
|
|
2517
|
+
if (SKILL_ENTRY_HEAD_RE.test(lines[k])) {
|
|
2518
|
+
moreSkills = true;
|
|
2519
|
+
break;
|
|
2520
|
+
}
|
|
2521
|
+
}
|
|
2522
|
+
if (!moreSkills) {
|
|
2523
|
+
flushCurrent(i);
|
|
2524
|
+
inAvailableHeader = false;
|
|
2525
|
+
}
|
|
2526
|
+
}
|
|
2527
|
+
}
|
|
2528
|
+
}
|
|
2529
|
+
flushCurrent(lines.length);
|
|
2530
|
+
return entries;
|
|
2531
|
+
}
|
|
2532
|
+
/**
|
|
2533
|
+
* Stub low-relevance skill descriptions in large skill catalogs (`>= 10` skills),
|
|
2534
|
+
* pinning Turn-1 selection per `(sessionKey, catalogHash)` and archiving full entries
|
|
2535
|
+
* in `ContextPageStore` so mentioning a stubbed skill on Turn N triggers tail hydration.
|
|
2536
|
+
*/
|
|
2537
|
+
export function linkSessionSkills(input) {
|
|
2538
|
+
const minSkills = Math.max(1, input.minSkills ?? 10);
|
|
2539
|
+
const maxVerbatim = Math.max(0, input.maxVerbatim ?? 6);
|
|
2540
|
+
const noop = {
|
|
2541
|
+
text: input.text,
|
|
2542
|
+
changed: false,
|
|
2543
|
+
keptSkills: [],
|
|
2544
|
+
stubbedSkills: [],
|
|
2545
|
+
savedChars: 0,
|
|
2546
|
+
savedTokens: 0,
|
|
2547
|
+
};
|
|
2548
|
+
if (!input.text || !input.store)
|
|
2549
|
+
return noop;
|
|
2550
|
+
const lines = input.text.split('\n');
|
|
2551
|
+
const entries = parseSkillCatalogEntries(lines);
|
|
2552
|
+
if (entries.length < minSkills)
|
|
2553
|
+
return noop;
|
|
2554
|
+
const catalogHash = fnv64Hex(entries.map((e) => `${e.name}\0${e.rawEntry}`).join('\n'));
|
|
2555
|
+
const sessionKey = input.sessionKey && input.sessionKey.trim() ? input.sessionKey.trim() : 'default';
|
|
2556
|
+
const coreSet = new Set(DEFAULT_CORE_SKILLS);
|
|
2557
|
+
if (input.alwaysKeep) {
|
|
2558
|
+
for (const k of input.alwaysKeep)
|
|
2559
|
+
coreSet.add(k.trim());
|
|
2560
|
+
}
|
|
2561
|
+
let keptNames;
|
|
2562
|
+
let shouldPinSelected = false;
|
|
2563
|
+
let toPin = [];
|
|
2564
|
+
const pinnedList = input.pinnedStore?.get(sessionKey, catalogHash);
|
|
2565
|
+
if (pinnedList && pinnedList.length > 0) {
|
|
2566
|
+
keptNames = new Set(pinnedList);
|
|
2567
|
+
for (const c of coreSet)
|
|
2568
|
+
keptNames.add(c);
|
|
2569
|
+
}
|
|
2570
|
+
else {
|
|
2571
|
+
const querySource = [input.firstUserText, ...(input.workspaceHints ?? [])].join(' ');
|
|
2572
|
+
const queryTokens = tokenizeQueryWords(querySource);
|
|
2573
|
+
const queryLower = querySource.toLowerCase();
|
|
2574
|
+
const scoredNonCore = [];
|
|
2575
|
+
keptNames = new Set();
|
|
2576
|
+
for (const entry of entries) {
|
|
2577
|
+
if (coreSet.has(entry.name)) {
|
|
2578
|
+
keptNames.add(entry.name);
|
|
2579
|
+
continue;
|
|
2580
|
+
}
|
|
2581
|
+
let score = 0;
|
|
2582
|
+
const nameLower = entry.name.toLowerCase();
|
|
2583
|
+
const bodyLower = entry.rawEntry.toLowerCase();
|
|
2584
|
+
if (queryLower.includes(nameLower))
|
|
2585
|
+
score += 100;
|
|
2586
|
+
const nameParts = nameLower.split(/[-_.]+/);
|
|
2587
|
+
for (const qt of queryTokens) {
|
|
2588
|
+
if (nameParts.includes(qt))
|
|
2589
|
+
score += 20;
|
|
2590
|
+
else if (bodyLower.includes(qt))
|
|
2591
|
+
score += 3;
|
|
2592
|
+
}
|
|
2593
|
+
scoredNonCore.push({ entry, score });
|
|
2594
|
+
}
|
|
2595
|
+
scoredNonCore.sort((a, b) => b.score - a.score || a.entry.catalogIndex - b.entry.catalogIndex);
|
|
2596
|
+
for (let i = 0; i < Math.min(maxVerbatim, scoredNonCore.length); i++) {
|
|
2597
|
+
keptNames.add(scoredNonCore[i].entry.name);
|
|
2598
|
+
}
|
|
2599
|
+
toPin = entries.filter((e) => keptNames.has(e.name)).map((e) => e.name);
|
|
2600
|
+
shouldPinSelected = true;
|
|
2601
|
+
}
|
|
2602
|
+
const entryByStart = new Map();
|
|
2603
|
+
for (const entry of entries)
|
|
2604
|
+
entryByStart.set(entry.startLine, entry);
|
|
2605
|
+
const outLines = [];
|
|
2606
|
+
const keptSkills = [];
|
|
2607
|
+
const stubbedEntries = [];
|
|
2608
|
+
for (let i = 0; i < lines.length; i++) {
|
|
2609
|
+
const entry = entryByStart.get(i);
|
|
2610
|
+
if (!entry) {
|
|
2611
|
+
outLines.push(lines[i]);
|
|
2612
|
+
continue;
|
|
2613
|
+
}
|
|
2614
|
+
if (keptNames.has(entry.name)) {
|
|
2615
|
+
keptSkills.push(entry.name);
|
|
2616
|
+
outLines.push(entry.rawEntry);
|
|
2617
|
+
}
|
|
2618
|
+
else {
|
|
2619
|
+
const pgId = pageIdForText(entry.rawEntry);
|
|
2620
|
+
stubbedEntries.push({ entry, pageId: pgId });
|
|
2621
|
+
outLines.push(`- ${entry.name} [${pgId}] (stubbed; mention name to auto-hydrate)`);
|
|
2622
|
+
}
|
|
2623
|
+
i = entry.endLine;
|
|
2624
|
+
}
|
|
2625
|
+
if (stubbedEntries.length === 0)
|
|
2626
|
+
return noop;
|
|
2627
|
+
const rewritten = outLines.join('\n');
|
|
2628
|
+
const savedChars = input.text.length - rewritten.length;
|
|
2629
|
+
if (savedChars < 400)
|
|
2630
|
+
return noop;
|
|
2631
|
+
const savedTokens = countTokensFast(input.text) - countTokensFast(rewritten);
|
|
2632
|
+
if (savedTokens < 100)
|
|
2633
|
+
return noop;
|
|
2634
|
+
if (shouldPinSelected) {
|
|
2635
|
+
input.pinnedStore?.set(sessionKey, catalogHash, toPin);
|
|
2636
|
+
}
|
|
2637
|
+
// Commit stubbed entries into ContextPageStore ONLY after threshold check succeeds
|
|
2638
|
+
for (const { entry } of stubbedEntries) {
|
|
2639
|
+
input.store.storePage({
|
|
2640
|
+
sessionKey,
|
|
2641
|
+
refId: `skill:${entry.name}`,
|
|
2642
|
+
toolName: 'skill-catalog',
|
|
2643
|
+
filePath: entry.skillPath,
|
|
2644
|
+
rawText: entry.rawEntry,
|
|
2645
|
+
extraSymbols: [entry.name],
|
|
2646
|
+
});
|
|
2647
|
+
}
|
|
2648
|
+
input.store.recordSkillStub(stubbedEntries.length, savedChars);
|
|
2649
|
+
return {
|
|
2650
|
+
text: rewritten,
|
|
2651
|
+
changed: true,
|
|
2652
|
+
catalogHash,
|
|
2653
|
+
keptSkills,
|
|
2654
|
+
stubbedSkills: stubbedEntries.map((s) => s.entry.name),
|
|
2655
|
+
savedChars,
|
|
2656
|
+
savedTokens,
|
|
2657
|
+
};
|
|
2658
|
+
}
|
|
2659
|
+
const HEADING_RE = /^#{1,6}\s+\S/;
|
|
2660
|
+
const URL_RE = /https?:\/\/[^\s)>'"]+/;
|
|
2661
|
+
const FILE_PATH_RE = /(?:(?:^|[\s(`"'])(?:[\w.-]+\/)+[\w.-]+\.[A-Za-z]{1,8}(?:$|[\s)`"':,])|\b[\w.-]+\.(?:ts|tsx|js|jsx|mjs|cjs|py|go|rs|java|swift|sql|yaml|yml|json|toml|md)(?::\d+(?::\d+)?)?\b)/i;
|
|
2662
|
+
const STACK_PREFIX_RE = /^(?:at\s+\S+\s*\(|Caused by:|File\s+"[^"\n]+",\s+line\s+\d+|Traceback\s+\(most recent call last\))/;
|
|
2663
|
+
const BACKTICK_ID_RE = /`[^`\n]{2,60}`/;
|
|
2664
|
+
const NUMBER_RE = /\b\d+(?:\.\d+)?%?\b/;
|
|
2665
|
+
const BULLET_KEY_RE = /^[-*]\s+(?:\*\*[^*\n]{2,40}\*\*|[A-Za-z0-9 _-]{2,30}:)/;
|
|
2666
|
+
const STRUCTURED_LOG_RE = /^(?:\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}|\[(?:INFO|WARN|WARNING|ERROR|DEBUG|TRACE|FATAL)\])/;
|
|
2667
|
+
const DIFF_LINE_RE = /^(?:diff --git |@@ -\d+(?:,\d+)? \+\d+(?:,\d+)? @@|\*\*\* (?:Begin Patch|Update File:|Add File:))/;
|
|
2668
|
+
const YAML_KV_RE = /^[ \t]*(?:-\s+)?[A-Za-z_][\w.-]*:[ \t]*\S/;
|
|
2669
|
+
function looksLikeJsonText(text) {
|
|
2670
|
+
const trimmed = text.trim();
|
|
2671
|
+
if (!trimmed)
|
|
2672
|
+
return false;
|
|
2673
|
+
const first = trimmed.charCodeAt(0);
|
|
2674
|
+
const last = trimmed.charCodeAt(trimmed.length - 1);
|
|
2675
|
+
if ((first === 123 && last === 125) || (first === 91 && last === 93))
|
|
2676
|
+
return true;
|
|
2677
|
+
// Detect HTTP-header-prefixed JSON bodies (e.g., `HTTP/1.1 200 OK\n...\n\n{...}`)
|
|
2678
|
+
if (last === 125 || last === 93) {
|
|
2679
|
+
const lines = trimmed.split('\n', 24);
|
|
2680
|
+
if (/^HTTP\/\d/.test(lines[0] ?? '')) {
|
|
2681
|
+
for (let i = 1; i < lines.length; i++) {
|
|
2682
|
+
if (lines[i].trim() === '' && i + 1 < lines.length) {
|
|
2683
|
+
const bodyChar = lines[i + 1].trimStart().charCodeAt(0);
|
|
2684
|
+
if (bodyChar === 123 || bodyChar === 91)
|
|
2685
|
+
return true;
|
|
2686
|
+
}
|
|
2687
|
+
}
|
|
2688
|
+
}
|
|
2689
|
+
}
|
|
2690
|
+
return false;
|
|
2691
|
+
}
|
|
2692
|
+
function isNonProseBlob(text, lines) {
|
|
2693
|
+
if (text.startsWith('@toon ') || text.includes('[Drain ') || looksLikeJsonText(text))
|
|
2694
|
+
return true;
|
|
2695
|
+
let codeHints = 0;
|
|
2696
|
+
let logHints = 0;
|
|
2697
|
+
let gutterHints = 0;
|
|
2698
|
+
let yamlHints = 0;
|
|
2699
|
+
let nonEmpty = 0;
|
|
2700
|
+
const sample = Math.min(lines.length, 60);
|
|
2701
|
+
for (let i = 0; i < sample; i++) {
|
|
2702
|
+
const l = lines[i];
|
|
2703
|
+
const trimmed = l.trim();
|
|
2704
|
+
if (!trimmed)
|
|
2705
|
+
continue;
|
|
2706
|
+
nonEmpty += 1;
|
|
2707
|
+
if (DIFF_LINE_RE.test(trimmed))
|
|
2708
|
+
return true;
|
|
2709
|
+
if (GUTTER_EXPLICIT_RE.test(l) || GUTTER_COLON_RE.test(l) || /^\s+\d{1,7}\t/.test(l))
|
|
2710
|
+
gutterHints += 1;
|
|
2711
|
+
if (STRUCTURED_LOG_RE.test(trimmed))
|
|
2712
|
+
logHints += 1;
|
|
2713
|
+
if (YAML_KV_RE.test(l))
|
|
2714
|
+
yamlHints += 1;
|
|
2715
|
+
if (/^(?:export\s+|import\s+|from\s+\S+\s+import\b|(?:async\s+)?(?:function|def|fn|func|class|interface|struct|enum)\s+[A-Za-z_])/.test(trimmed)) {
|
|
2716
|
+
codeHints += 1;
|
|
2717
|
+
}
|
|
2718
|
+
}
|
|
2719
|
+
if (gutterHints >= 5 || codeHints >= 3)
|
|
2720
|
+
return true;
|
|
2721
|
+
if (nonEmpty > 0 && logHints / nonEmpty >= 0.4)
|
|
2722
|
+
return true;
|
|
2723
|
+
if (nonEmpty >= 8 && yamlHints / nonEmpty >= 0.45)
|
|
2724
|
+
return true;
|
|
2725
|
+
return false;
|
|
2726
|
+
}
|
|
2727
|
+
function extractLineRarityWords(line) {
|
|
2728
|
+
const words = [];
|
|
2729
|
+
let start = -1;
|
|
2730
|
+
for (let i = 0; i <= line.length; i++) {
|
|
2731
|
+
const c = i < line.length ? line.charCodeAt(i) : 32;
|
|
2732
|
+
const isWord = (c >= 65 && c <= 90) || (c >= 97 && c <= 122) || (c >= 48 && c <= 57) || c === 95;
|
|
2733
|
+
if (isWord) {
|
|
2734
|
+
if (start < 0)
|
|
2735
|
+
start = i;
|
|
2736
|
+
}
|
|
2737
|
+
else if (start >= 0) {
|
|
2738
|
+
const len = i - start;
|
|
2739
|
+
if (len >= 3 && len <= 40) {
|
|
2740
|
+
words.push(line.slice(start, i).toLowerCase());
|
|
2741
|
+
}
|
|
2742
|
+
start = -1;
|
|
2743
|
+
if (words.length >= 48)
|
|
2744
|
+
break;
|
|
2745
|
+
}
|
|
2746
|
+
}
|
|
2747
|
+
return words;
|
|
2748
|
+
}
|
|
2749
|
+
/**
|
|
2750
|
+
* Deterministic, pure-TS `<3ms` birth-time extractive pruner for large
|
|
2751
|
+
* unstructured prose/web blobs (`>= 4,000` chars). Archives full raw text in
|
|
2752
|
+
* `ContextPageStore` and drops the bottom redundant lines (~45%–55% reduction).
|
|
2753
|
+
*/
|
|
2754
|
+
export function pruneLowDensityBlob(text, opts = {}) {
|
|
2755
|
+
const minChars = opts.minChars ?? 4000;
|
|
2756
|
+
const targetDropRatio = Math.min(0.65, Math.max(0.3, opts.targetDropRatio ?? 0.5));
|
|
2757
|
+
const totalLines = countLines(text);
|
|
2758
|
+
if (!text || text.length < minChars) {
|
|
2759
|
+
return { text, changed: false, prunedLines: 0, totalLines, savedChars: 0 };
|
|
2760
|
+
}
|
|
2761
|
+
if (text.includes('low-density lines pruned; raw in pg_') || text.startsWith('[fiche ')) {
|
|
2762
|
+
return { text, changed: false, prunedLines: 0, totalLines, savedChars: 0 };
|
|
2763
|
+
}
|
|
2764
|
+
const lines = text.split('\n');
|
|
2765
|
+
if (lines.length < 12 || isNonProseBlob(text, lines)) {
|
|
2766
|
+
return { text, changed: false, prunedLines: 0, totalLines: lines.length, savedChars: 0 };
|
|
2767
|
+
}
|
|
2768
|
+
const n = lines.length;
|
|
2769
|
+
const wordIdMap = new Map();
|
|
2770
|
+
const dfCounts = [];
|
|
2771
|
+
const uniqLineWordIds = new Array(n);
|
|
2772
|
+
// Pass 1: document-frequency scan + integer-indexed unique rarity words per line (O(N))
|
|
2773
|
+
for (let i = 0; i < n; i++) {
|
|
2774
|
+
const words = extractLineRarityWords(lines[i]);
|
|
2775
|
+
if (words.length === 0) {
|
|
2776
|
+
uniqLineWordIds[i] = EMPTY_I32;
|
|
2777
|
+
continue;
|
|
2778
|
+
}
|
|
2779
|
+
const ids = [];
|
|
2780
|
+
for (let k = 0; k < words.length; k++) {
|
|
2781
|
+
const w = words[k];
|
|
2782
|
+
let id = wordIdMap.get(w);
|
|
2783
|
+
if (id === undefined) {
|
|
2784
|
+
if (wordIdMap.size >= 8192)
|
|
2785
|
+
continue;
|
|
2786
|
+
id = dfCounts.length;
|
|
2787
|
+
wordIdMap.set(w, id);
|
|
2788
|
+
dfCounts.push(0);
|
|
2789
|
+
}
|
|
2790
|
+
let dup = false;
|
|
2791
|
+
for (let j = 0; j < ids.length; j++) {
|
|
2792
|
+
if (ids[j] === id) {
|
|
2793
|
+
dup = true;
|
|
2794
|
+
break;
|
|
2795
|
+
}
|
|
2796
|
+
}
|
|
2797
|
+
if (!dup) {
|
|
2798
|
+
ids.push(id);
|
|
2799
|
+
dfCounts[id] += 1;
|
|
2800
|
+
}
|
|
2801
|
+
}
|
|
2802
|
+
uniqLineWordIds[i] = ids.length > 0 ? Int32Array.from(ids) : EMPTY_I32;
|
|
2803
|
+
}
|
|
2804
|
+
const wordCount = dfCounts.length;
|
|
2805
|
+
const wordIdf = new Float64Array(wordCount);
|
|
2806
|
+
for (let id = 0; id < wordCount; id++) {
|
|
2807
|
+
wordIdf[id] = Math.log(1 + n / (1 + dfCounts[id]));
|
|
2808
|
+
}
|
|
2809
|
+
// Pass 2: seed submodular coverage from fixed head-4 + tail-4 lines
|
|
2810
|
+
const seenNormalized = new Set();
|
|
2811
|
+
const keep = new Uint8Array(n);
|
|
2812
|
+
let keptChars = 0;
|
|
2813
|
+
const covered = new Uint16Array(wordCount);
|
|
2814
|
+
const addCoverage = (ids) => {
|
|
2815
|
+
for (let k = 0; k < ids.length; k++) {
|
|
2816
|
+
const id = ids[k];
|
|
2817
|
+
if (covered[id] < 0xffff)
|
|
2818
|
+
covered[id] += 1;
|
|
2819
|
+
}
|
|
2820
|
+
};
|
|
2821
|
+
for (let i = 0; i < Math.min(4, n); i++) {
|
|
2822
|
+
keep[i] = 1;
|
|
2823
|
+
keptChars += lines[i].length + 1;
|
|
2824
|
+
addCoverage(uniqLineWordIds[i]);
|
|
2825
|
+
}
|
|
2826
|
+
for (let i = Math.max(4, n - 4); i < n; i++) {
|
|
2827
|
+
keep[i] = 1;
|
|
2828
|
+
keptChars += lines[i].length + 1;
|
|
2829
|
+
addCoverage(uniqLineWordIds[i]);
|
|
2830
|
+
}
|
|
2831
|
+
const computeGain = (structScore, ids) => {
|
|
2832
|
+
if (ids.length === 0)
|
|
2833
|
+
return structScore;
|
|
2834
|
+
let sum = 0;
|
|
2835
|
+
for (let k = 0; k < ids.length; k++) {
|
|
2836
|
+
const id = ids[k];
|
|
2837
|
+
const c = covered[id];
|
|
2838
|
+
if (c < 32)
|
|
2839
|
+
sum += wordIdf[id] * POW_HALF[c];
|
|
2840
|
+
}
|
|
2841
|
+
return structScore + 1.5 * sum;
|
|
2842
|
+
};
|
|
2843
|
+
const heap = [];
|
|
2844
|
+
const lineScores = new Float32Array(n);
|
|
2845
|
+
for (let i = 4; i < n - 4; i++) {
|
|
2846
|
+
const line = lines[i];
|
|
2847
|
+
const trimmed = line.trim();
|
|
2848
|
+
const head = trimmed.length > MAX_LINE_SCAN_CHARS ? trimmed.slice(0, MAX_LINE_SCAN_CHARS) : trimmed;
|
|
2849
|
+
if (!trimmed) {
|
|
2850
|
+
lineScores[i] = -10;
|
|
2851
|
+
continue;
|
|
2852
|
+
}
|
|
2853
|
+
let structScore = 0;
|
|
2854
|
+
if (HEADING_RE.test(head))
|
|
2855
|
+
structScore += 10;
|
|
2856
|
+
if (STACK_PREFIX_RE.test(head))
|
|
2857
|
+
structScore += 7;
|
|
2858
|
+
if (ERROR_TOKEN_RE.test(head) || /\b(?:error|exception|fatal|warn|failed|timeout|http\s*[45]\d\d)\b/i.test(head)) {
|
|
2859
|
+
structScore += 6;
|
|
2860
|
+
}
|
|
2861
|
+
if (URL_RE.test(head))
|
|
2862
|
+
structScore += 5;
|
|
2863
|
+
if (FILE_PATH_RE.test(head))
|
|
2864
|
+
structScore += 5;
|
|
2865
|
+
if (BACKTICK_ID_RE.test(head))
|
|
2866
|
+
structScore += 4;
|
|
2867
|
+
if (NUMBER_RE.test(head))
|
|
2868
|
+
structScore += 2.5;
|
|
2869
|
+
if (BULLET_KEY_RE.test(head))
|
|
2870
|
+
structScore += 2;
|
|
2871
|
+
if (trimmed.length < 15 && structScore < 4)
|
|
2872
|
+
structScore -= 2;
|
|
2873
|
+
const norm = trimmed.toLowerCase();
|
|
2874
|
+
if (seenNormalized.has(norm))
|
|
2875
|
+
structScore -= 5;
|
|
2876
|
+
else if (seenNormalized.size < 4096)
|
|
2877
|
+
seenNormalized.add(norm);
|
|
2878
|
+
const uniqIds = uniqLineWordIds[i];
|
|
2879
|
+
const initialGain = computeGain(structScore, uniqIds);
|
|
2880
|
+
const chars = line.length + 1;
|
|
2881
|
+
lineScores[i] = initialGain;
|
|
2882
|
+
if (initialGain > -5) {
|
|
2883
|
+
heap.push({
|
|
2884
|
+
idx: i,
|
|
2885
|
+
chars,
|
|
2886
|
+
structScore,
|
|
2887
|
+
uniqIds,
|
|
2888
|
+
rawGain: initialGain,
|
|
2889
|
+
density: initialGain / Math.max(16, chars),
|
|
2890
|
+
evalVersion: 0,
|
|
2891
|
+
});
|
|
2892
|
+
}
|
|
2893
|
+
}
|
|
2894
|
+
const higherPriority = (a, b) => a.density > b.density || (a.density === b.density && a.idx < b.idx);
|
|
2895
|
+
const siftDown = (arr, startIdx) => {
|
|
2896
|
+
let idx = startIdx;
|
|
2897
|
+
const len = arr.length;
|
|
2898
|
+
while (true) {
|
|
2899
|
+
const left = (idx << 1) + 1;
|
|
2900
|
+
if (left >= len)
|
|
2901
|
+
break;
|
|
2902
|
+
const right = left + 1;
|
|
2903
|
+
let best = left;
|
|
2904
|
+
if (right < len && higherPriority(arr[right], arr[left])) {
|
|
2905
|
+
best = right;
|
|
2906
|
+
}
|
|
2907
|
+
if (!higherPriority(arr[best], arr[idx]))
|
|
2908
|
+
break;
|
|
2909
|
+
const tmp = arr[idx];
|
|
2910
|
+
arr[idx] = arr[best];
|
|
2911
|
+
arr[best] = tmp;
|
|
2912
|
+
idx = best;
|
|
2913
|
+
}
|
|
2914
|
+
};
|
|
2915
|
+
const heapPush = (arr, item) => {
|
|
2916
|
+
let idx = arr.length;
|
|
2917
|
+
arr.push(item);
|
|
2918
|
+
while (idx > 0) {
|
|
2919
|
+
const parent = (idx - 1) >> 1;
|
|
2920
|
+
if (!higherPriority(arr[idx], arr[parent]))
|
|
2921
|
+
break;
|
|
2922
|
+
const tmp = arr[parent];
|
|
2923
|
+
arr[parent] = arr[idx];
|
|
2924
|
+
arr[idx] = tmp;
|
|
2925
|
+
idx = parent;
|
|
2926
|
+
}
|
|
2927
|
+
};
|
|
2928
|
+
const heapPop = (arr) => {
|
|
2929
|
+
const top = arr[0];
|
|
2930
|
+
const last = arr.pop();
|
|
2931
|
+
if (arr.length > 0) {
|
|
2932
|
+
arr[0] = last;
|
|
2933
|
+
siftDown(arr, 0);
|
|
2934
|
+
}
|
|
2935
|
+
return top;
|
|
2936
|
+
};
|
|
2937
|
+
for (let idx = (heap.length >> 1) - 1; idx >= 0; idx--) {
|
|
2938
|
+
siftDown(heap, idx);
|
|
2939
|
+
}
|
|
2940
|
+
// Minoux Lazy Greedy Submodular Maximization
|
|
2941
|
+
const targetKeepChars = Math.floor(text.length * (1 - targetDropRatio));
|
|
2942
|
+
const maxReevals = n * 4;
|
|
2943
|
+
let acceptedVersion = 0;
|
|
2944
|
+
let reevals = 0;
|
|
2945
|
+
while (heap.length > 0 && keptChars < targetKeepChars) {
|
|
2946
|
+
const top = heapPop(heap);
|
|
2947
|
+
let curGain = top.rawGain;
|
|
2948
|
+
let curDensity = top.density;
|
|
2949
|
+
if (top.evalVersion !== acceptedVersion && reevals < maxReevals) {
|
|
2950
|
+
curGain = computeGain(top.structScore, top.uniqIds);
|
|
2951
|
+
curDensity = curGain / Math.max(16, top.chars);
|
|
2952
|
+
top.evalVersion = acceptedVersion;
|
|
2953
|
+
reevals += 1;
|
|
2954
|
+
}
|
|
2955
|
+
const isMax = heap.length === 0 || curDensity >= heap[0].density - 1e-9;
|
|
2956
|
+
if (isMax || reevals >= maxReevals) {
|
|
2957
|
+
if (curGain <= -5) {
|
|
2958
|
+
if (isMax)
|
|
2959
|
+
break;
|
|
2960
|
+
continue;
|
|
2961
|
+
}
|
|
2962
|
+
keep[top.idx] = 1;
|
|
2963
|
+
lineScores[top.idx] = curGain;
|
|
2964
|
+
keptChars += top.chars;
|
|
2965
|
+
addCoverage(top.uniqIds);
|
|
2966
|
+
acceptedVersion += 1;
|
|
2967
|
+
}
|
|
2968
|
+
else {
|
|
2969
|
+
top.rawGain = curGain;
|
|
2970
|
+
top.density = curDensity;
|
|
2971
|
+
heapPush(heap, top);
|
|
2972
|
+
}
|
|
2973
|
+
}
|
|
2974
|
+
// Coalesce low-value 1-line kept islands; never drop high-signal headings, errors, stacks, paths, URLs, or backticks.
|
|
2975
|
+
for (let i = 4; i < n - 4; i++) {
|
|
2976
|
+
if (keep[i] === 1 &&
|
|
2977
|
+
keep[i - 1] === 0 &&
|
|
2978
|
+
keep[i + 1] === 0 &&
|
|
2979
|
+
lines[i].length <= 64 &&
|
|
2980
|
+
lineScores[i] < 4) {
|
|
2981
|
+
keep[i] = 0;
|
|
2982
|
+
}
|
|
2983
|
+
}
|
|
2984
|
+
const pageId = pageIdForText(text);
|
|
2985
|
+
const outParts = [];
|
|
2986
|
+
let prunedLines = 0;
|
|
2987
|
+
let i = 0;
|
|
2988
|
+
while (i < n) {
|
|
2989
|
+
if (keep[i] === 1) {
|
|
2990
|
+
outParts.push(lines[i]);
|
|
2991
|
+
i += 1;
|
|
2992
|
+
continue;
|
|
2993
|
+
}
|
|
2994
|
+
const startDrop = i;
|
|
2995
|
+
while (i < n && keep[i] === 0)
|
|
2996
|
+
i += 1;
|
|
2997
|
+
const dropped = i - startDrop;
|
|
2998
|
+
prunedLines += dropped;
|
|
2999
|
+
outParts.push(`[... ${dropped} low-density lines pruned; raw in ${pageId} ...]`);
|
|
3000
|
+
}
|
|
3001
|
+
const out = outParts.join('\n');
|
|
3002
|
+
const savedChars = text.length - out.length;
|
|
3003
|
+
if (prunedLines === 0 || savedChars < 1000 || savedChars < text.length * 0.25) {
|
|
3004
|
+
return { text, changed: false, prunedLines: 0, totalLines: n, savedChars: 0 };
|
|
3005
|
+
}
|
|
3006
|
+
if (opts.store) {
|
|
3007
|
+
const targetSessionKey = opts.sessionKey?.trim() || 'default';
|
|
3008
|
+
const storedPage = opts.store.storePage({
|
|
3009
|
+
sessionKey: targetSessionKey,
|
|
3010
|
+
refId: opts.refId ?? 'prose-blob',
|
|
3011
|
+
toolName: opts.toolName,
|
|
3012
|
+
rawText: text,
|
|
3013
|
+
});
|
|
3014
|
+
if (!opts.store.getPage(storedPage.id, targetSessionKey)) {
|
|
3015
|
+
return { text, changed: false, prunedLines: 0, totalLines: n, savedChars: 0 };
|
|
3016
|
+
}
|
|
3017
|
+
opts.store.recordDensityPrune(savedChars);
|
|
3018
|
+
}
|
|
3019
|
+
return {
|
|
3020
|
+
text: out,
|
|
3021
|
+
changed: true,
|
|
3022
|
+
pageId,
|
|
3023
|
+
prunedLines,
|
|
3024
|
+
totalLines: n,
|
|
3025
|
+
savedChars,
|
|
3026
|
+
};
|
|
3027
|
+
}
|
|
3028
|
+
//# sourceMappingURL=context-mmu.js.map
|