dsh-layers-hippocampus 1.6.3 → 1.6.4

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 CHANGED
@@ -4,11 +4,66 @@ All notable changes to `dsh-layers-hippocampus` are documented here.
4
4
  The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
5
5
  and the project adheres to [Semantic Versioning](https://semver.org/).
6
6
 
7
+ ## [1.6.4] — 2026-11-14
8
+
9
+ **修复 1M 上下文溢出(`CONTEXT_WINDOW_EXCEEDED`):交接判定的分母、分子与状态机三处
10
+ 同时失效,外加单轮超大工具输出没有任何熔断。这是一次独立的安全发版——1.6.3 从未
11
+ 发布过,它的全部内容已并入本版。**
12
+
13
+ - **Fixed — 分母错源:接入宿主真实模型窗口**。新增 `src/context/windowGuard.js` 的
14
+ `resolveWindow()`:**宿主适配器上报的窗口优先**(`llm.resolveModelInfo().context.contextWindow`,
15
+ 也接受 `tokenMeter.contextPressure().contextWindow`),`context.nativeTokenLimit` 降级为
16
+ 用户覆盖,只在宿主不可用时兜底。`panel.session.windowSource` 暴露本次用的是
17
+ `host` / `config` / `default`,事后可审计。此前本机 profile 写的 `8000` 被当成模型窗口,
18
+ 模型真实窗口是 **1,048,576**。
19
+ - **Fixed — 分子不再靠猜:`used + reserved` 公式**。判定改为
20
+ `used_tokens + reserved_completion_tokens >= window × threshold`。
21
+ 已用优先取宿主 `tokenMeter` 的测量值(含系统提示、工具 schema、历史重放),
22
+ `Math.ceil(字符数 ÷ 4)` 的自估降为下限;`reserved` 取本次请求真实的 `maxTokens`
23
+ (默认 256,000)。事故数字 854,668 + 256,000 = 1,110,668 > 1,048,576 现在能直接判出来。
24
+ - **Fixed — Fail-Fast 兜底**。新增 `agent/request` 中间件:拿到最终请求配置后重新判定,
25
+ **必定放不进窗口的请求在本地就被拦下**,抛 `MEM_E_CONTEXT_EXCEEDED`,details 里带
26
+ `usedTokens / reservedTokens / projectedTokens / window / windowSource / ratio`,
27
+ 并明确写出 “Nothing was sent to the provider”。宿主缺少 `llm` / `tokenMeter` 服务时
28
+ **绝不阻断**(降级为原有行为)。
29
+ - **Fixed — 交接状态机死锁(“80% 了却不交接”)**。`checkHandoff()` 里
30
+ `if (marker.active) return base;` 会让首次交接后的同一会话**永远**不再交接
31
+ (1.6.3 移除自动开新会话后,session id 不再变化,marker 就永久 active)。
32
+ 改为 `rehandoffDecision()`:同会话压力再涨 ≥5 个百分点(`pressure-growth`)或投影
33
+ ≥95% 硬上限(`near-hard-limit`)时清掉旧 marker 重新蒸馏;不同会话仍走原有消费路径。
34
+ - **Added — Live Compact:单轮超大工具输出熔断**。新增 `src/context/liveCompact.js`:
35
+ 单个 `tool/result` 的文本超过 `context.liveCompact.thresholdChars`(默认 200,000 字符)时,
36
+ 保留头 4,000 / 尾 2,000 字符,中间压成一行指针
37
+ (`[[hippocampus:live-compact: removed N chars … (seq=…, call=…, tool=…)]`),
38
+ 原文仍可用 `deep_raw` 取回。走宿主 surface 协议
39
+ (`append('compaction/prune')` + `append('tool/result', { surfaceOp: { op: 'replace' } })`),
40
+ 宿主自带 `toolResultPruner` 时优先委托给它。指针化按 code point 切,不会劈开代理对。
41
+ - **Tests**:新增 `test/v164.windowGuard.test.js`(11 例)锁定本次修复:宿主窗口优先于配置覆盖、
42
+ 引擎 `windowSource` 可审计、`used + reserved` 判定(含那组真实数字 854,668 + 256,000)、
43
+ `nativeState` 优先采用宿主测量值、`rehandoffDecision` 的四种判定、
44
+ 超大工具结果的指针化(含代理对不被劈开、`surfaceOp replace` 的实际形状)、
45
+ 同会话内 marker 仍 active 时 `checkHandoff` 会续交、以及
46
+ `guardRequest` 在「必超限」时抛 `MEM_E_CONTEXT_EXCEEDED` / 在「放得下」时放行 /
47
+ 在没有宿主服务时绝不阻断(降级为原有行为)。
48
+ 全量 **494/494**(79 个测试文件)。
49
+
7
50
  ## [1.6.3] — 2026-11-13
8
51
 
9
52
  **配置加载器加固:把 1.6.2 的“旧配置启动阻断”事故固化为引擎能力——先迁移、再严格校验、
10
53
  必要时安全降级,绝不让 DSH 客户端卡在“正在启动…”。**
11
54
 
55
+ - **Added — 冷启动注入可观测性**:`/stats` 新增 `coldStart{ pending[], injected, lastSessionId }`,
56
+ `panel.startup` / `panel.configVersion` / `panel.configWarnings` 与
57
+ `CAPABILITIES.startup` 同源(此前 `toMemoryOptions()` 没把迁移结果传给引擎,panel 报
58
+ `migrated:false` 而 capabilities 报 `true`)。
59
+ - **Fixed — 复习队列只报不消费(积压到 337 条)**:`maintain()` 现在按
60
+ `review.consumeBatchSize`(默认 40,上限 200/轮)分批消费到期行,批间
61
+ `await setImmediate` 让出主线程;每批一次 `reviews.advanceMany()` 落盘(不是每条一次写),
62
+ 并对该批做一次 `reinforce` 权重强化。`review.autoConsume` 可整体关闭。
63
+ - **Fixed — 1.6.2 遗留的两个启动/保留缺陷**:旧 profile(`retentionDays: 30` 且没有
64
+ `archiveAfterDays`)由 `migrateConfig` 派生 `29` 而不是启动失败;`prune()` 现在也会按
65
+ 月清理过期的 `.jsonl.br/.zst/.gz` 冷归档(此前只删明文,归档变相突破保留期)。
66
+
12
67
  - **Added — 配置 schema 版本与迁移机制**:`src/config.js` 新增
13
68
  `CONFIG_SCHEMA_VERSION = 3`;配置对象可携带 `configVersion`。加载顺序变为
14
69
  **`migrateConfig()` → 严格校验**:迁移阶段只做“补值 + 告警”,从不抛错,也绝不覆盖
package/README.md CHANGED
@@ -7,7 +7,7 @@
7
7
 
8
8
  | | |
9
9
  | --- | --- |
10
- | 版本 | **1.6.3** |
10
+ | 版本 | **1.6.4** |
11
11
  | 包名 | `dsh-layers-hippocampus` |
12
12
  | 仓库 | <https://github.com/382quaii/dsh-Layers-Hippocampus> |
13
13
  | 许可证 | MIT |
@@ -82,7 +82,21 @@
82
82
  「前几轮原话」取自交接标记里的 `tailTurns`(最后 ≤5 轮原话),摘要之外还能接上具体语境。
83
83
  静态「状态唤醒」策略常驻,两个开关都关时也不会退化成客服腔。
84
84
  - 交接**不会**自动弹出新对话:交接发生在对话中间,宿主在标记后继续同一对话;是否需要另开
85
- 新对话由用户自己决定(v1.5.6 的 `context.autoNewSession*` 已在 1.6.3 移除)。
85
+ 新对话由用户自己决定(v1.5.6 的 `context.autoNewSession*` 已在 1.6.4 移除)。
86
+ - **窗口分母来自宿主,而不是配置文件**(1.6.4):真实上限取
87
+ `llm.resolveModelInfo().context.contextWindow`(或 `tokenMeter.contextPressure().contextWindow`),
88
+ `context.nativeTokenLimit` 降级为“用户覆盖”,只在宿主无法上报时兜底;
89
+ `panel.session.windowSource` 会显示这次用的是 `host` / `config` / `default`。
90
+ - **交接判定 = 已用 + 预留输出**:`used_tokens + reserved_completion_tokens >= window × threshold`。
91
+ 已用优先取宿主 `tokenMeter` 的测量值(含系统提示、工具 schema、历史),不再是
92
+ `字符数 ÷ 4`。**必定放不进窗口的请求会在本地 fail-fast**,抛 `MEM_E_CONTEXT_EXCEEDED`
93
+ 并说明 used / reserved / window,不会发出去再被 API 拒绝。
94
+ - **同会话可续交**:交接后同一对话若压力继续上涨(比上次交接时高 ≥5 个百分点,或投影
95
+ ≥95% 硬上限),会重新蒸馏交接摘要,不会出现“第一次交接后就再也不交接”。
96
+ - **单轮超大工具输出熔断(Live Compact)**:单个 `tool/result` 超过
97
+ `context.liveCompact.thresholdChars`(默认 200,000 字符)时,保留头 4000 / 尾 2000 字符,
98
+ 中间压成一行指向 raw 日志的指针(带 `seq` / `call` / `tool` 坐标),原文仍可用
99
+ `deep_raw` 取回。宿主自带 `toolResultPruner` 时优先交给它。
86
100
 
87
101
  ### 打破线性增长:压缩 / 编码 / 语义三层
88
102
 
@@ -150,7 +164,7 @@ raw 层提供三档,覆盖从“只留关键”到“全留”:
150
164
  pnpm add dsh-layers-hippocampus
151
165
 
152
166
  # 或从 GitHub 指定 tag
153
- pnpm add "github:382quaii/dsh-Layers-Hippocampus#v1.6.3"
167
+ pnpm add "github:382quaii/dsh-Layers-Hippocampus#v1.6.4"
154
168
  ```
155
169
 
156
170
  ### 2. 挂到 profile
@@ -203,7 +217,7 @@ node scripts/wait-for-routes.mjs
203
217
  `panel.configWarnings` 里看到——插件绝不会静默地以与你写的不一样的配置运行。
204
218
 
205
219
  > 2026-11-13 的生产事故正是这一层缺失造成的:新默认值与旧 profile 冲突,`apply()`
206
- > 抛错导致插件整体不加载,UI 只能看到 HTTP 404。1.6.3 起该路径由
220
+ > 抛错导致插件整体不加载,UI 只能看到 HTTP 404。该路径自 1.6.4 起由
207
221
  > `test/v163.migration.test.js` 锁定。
208
222
 
209
223
  ### 5. 设置页的两种视图
@@ -221,7 +235,7 @@ node scripts/wait-for-routes.mjs
221
235
  ### 6. 验证
222
236
 
223
237
  ```bash
224
- npm test # 进程内全量用例(483 个)
238
+ npm test # 进程内全量用例(494 个)
225
239
  npm run check # 语法检查 + 全量测试
226
240
  ```
227
241
 
@@ -1,6 +1,6 @@
1
1
  # @local/dsh-memory — 分层长期记忆 Host 插件
2
2
 
3
- > 版本:**1.6.3** | 全量用例:**483/483** | 运行时依赖:**零**
3
+ > 版本:**1.6.4** | 全量用例:**494/494** | 运行时依赖:**零**
4
4
 
5
5
  给 DSH 智能体一份"活得比会话久"的记忆:**追加式原始日志是唯一真相源**,标签索引、日记、活跃集合全部是可丢弃、可重建的读模型,语义摘要独立于原始日志生死。
6
6
 
@@ -681,7 +681,7 @@ window.__ModuleLoader__.load({
681
681
 
682
682
  运行器带**看门狗**:默认 **60s**(`MEM_TEST_TIMEOUT_MS` 可调)仍未退出,就打印**卡住时正在导入/执行的文件、最后完成的测试名与完成数、活动资源、尚未触发的定时器**,然后 `process.exit(1)`。它不会用 `process.exit(0)` 掩盖超时——挂起即失败。`MEM_TEST_TRACE=1` 可看文件级进度,`MEM_TEST_ONLY=<子串>` 只跑一组。
683
683
 
684
- 483 个用例(78 个文件)覆盖:
684
+ 494 个用例(79 个文件)覆盖:
685
685
 
686
686
  - 索引与标签:重建 digest 一致、行号漂移防护(eventId 不变、行号变)、同义合并、活跃集 cap 挤出、规则变更不改清单、空活跃集降级、top-k 有界有序去重。
687
687
  - 衰减与删除:30 天半衰期、reinforce 移动锚点(不存字段)、仅文本粗筛、标签过滤、维护代切换且旧代可读、boot 检查、压缩不丢记录、并发维护串行化、四阶段删除、archive 可回滚 vs purge 不可、strict 巩固暂停与恢复、任务重放幂等、错误 id 零变更。
package/index.js CHANGED
@@ -41,6 +41,7 @@ import { HostBridge } from './src/hostBridge.js';
41
41
  import { isLowValley, nextLowValleyStart, windowInfo } from './src/priceWindow.js';
42
42
  import { DreamTimer } from './src/dreamTimer.js';
43
43
  import { probeCompression, resolveEngine } from './src/compression.js';
44
+ import { LIVE_COMPACT_DEFAULTS, liveCompactSession } from './src/context/liveCompact.js';
44
45
  import { MEMORY_API, registerMemoryRoutes } from './src/webRoutes.js';
45
46
 
46
47
  export const name = 'memory';
@@ -61,7 +62,7 @@ export { resolveConfig, DEFAULT_CONFIG };
61
62
  * of letting a raw 404 reach the user.
62
63
  */
63
64
  export const CAPABILITIES = Object.freeze({
64
- version: '1.6.3',
65
+ version: '1.6.4',
65
66
  spaces: true,
66
67
  memories: true,
67
68
  transferConsent: true,
@@ -190,6 +191,30 @@ function defineTool(definition) {
190
191
  * because it owns the plugin's lifecycle contracts; the store itself is src/.
191
192
  */
192
193
  export function createRuntime({ ctx = null, config, options, clock, raw = null, orchestrator = null, timers = null }) {
194
+ // v1.6.3: the HOST is the authority on the model window and on measured prompt
195
+ // pressure. The engine probes are SYNCHRONOUS (they are called while computing a
196
+ // status/decide value), so these hold the most recent HOST-observed numbers; the
197
+ // `agent/request` middleware refreshes them before every call.
198
+ const hostProbes = {
199
+ /** @type {{ provider: string, model: string, window: number } | null} */
200
+ window: null,
201
+ /** Prompt tokens the host measured for the live request (pressure, no output). */
202
+ usedTokens: null,
203
+ /** Completion tokens the pending request reserves (its max_tokens). */
204
+ reservedTokens: null,
205
+ updatedAt: null,
206
+ lastError: null,
207
+ };
208
+ const withHostProbes = (targetOptions) => ({
209
+ ...targetOptions,
210
+ config: {
211
+ ...targetOptions.config,
212
+ getHostWindow: () => hostProbes.window?.window ?? null,
213
+ getHostUsedTokens: () => hostProbes.usedTokens,
214
+ getReservedTokens: () => hostProbes.reservedTokens,
215
+ },
216
+ });
217
+ options = withHostProbes(options);
193
218
  // v1.5.6 physical split: multi-space lives in dsh-orchestrator. `orchestrator` is a
194
219
  // test/embedding override; the Host supplies the real service through `ctx.get`.
195
220
  const orchestratorService = () => orchestrator ?? ctx?.get?.('orchestrator') ?? null;
@@ -722,6 +747,148 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
722
747
  return `Memory state: ${runtime.phase}${error} (not ready: memory tools answer MEM_E_NOT_READY).`;
723
748
  };
724
749
 
750
+ /**
751
+ * v1.6.3 — the per-request gate. Runs BEFORE the provider call (the `agent/request`
752
+ * listener above) and does three things, in this order:
753
+ *
754
+ * 1. **Live Compact**: one oversized `tool/result` is pointerized (head + tail kept,
755
+ * middle replaced by a pointer carrying the durable raw coordinates). This is the
756
+ * only defence against a SINGLE turn that adds hundreds of thousands of tokens —
757
+ * no threshold-based maintenance tick can react fast enough.
758
+ * 2. **Refresh the host probes** so the engine's denominator (real model window) and
759
+ * numerator (host-measured pressure) stop being guesses.
760
+ * 3. **Fail fast** when `used + reserved` already exceeds the model window. The API
761
+ * would reject the same request a moment later, after the tokens were spent and
762
+ * without telling the state machine anything; a handoff is attempted first so the
763
+ * next turn starts from a distilled tail instead of the same brick wall.
764
+ *
765
+ * Everything here is best-effort EXCEPT the deliberate `MEM_E_CONTEXT_EXCEEDED`.
766
+ *
767
+ * @param {{ agent?: object, config?: object, signal?: object }} input
768
+ */
769
+ runtime.guardRequest = async ({ agent = null, config: requestConfig = null, signal = null } = {}) => {
770
+ const session = agent?.session ?? null;
771
+ // ---- 1. Live Compact ---------------------------------------------------
772
+ const liveConfig = runtime.config?.context?.liveCompact ?? {};
773
+ if (liveConfig.enabled !== false && session) {
774
+ // The HOST owns the canonical pruner (`tool-result-pruner`, replay-safe, wired
775
+ // into the ptc preset). Delegate when present; only fall back to our own
776
+ // surface surgery when the host has no pruner at all.
777
+ const hostPruner = (() => {
778
+ try {
779
+ return ctx?.get?.('toolResultPruner') ?? null;
780
+ } catch {
781
+ return null;
782
+ }
783
+ })();
784
+ if (hostPruner && typeof hostPruner.pruneSession === 'function') {
785
+ try {
786
+ await hostPruner.pruneSession(session);
787
+ runtime.lastLiveCompact = { source: 'host', at: memory.clock.now() };
788
+ } catch (error) {
789
+ runtime.logger?.warn?.(`hippocampus: host live-compact failed: ${asMemoryError(error).code}`);
790
+ }
791
+ } else {
792
+ runtime.lastLiveCompact = {
793
+ source: 'hippocampus',
794
+ at: memory.clock.now(),
795
+ ...liveCompactSession(session, {
796
+ thresholdChars: liveConfig.thresholdChars ?? LIVE_COMPACT_DEFAULTS.thresholdChars,
797
+ headChars: liveConfig.headChars ?? LIVE_COMPACT_DEFAULTS.headChars,
798
+ tailChars: liveConfig.tailChars ?? LIVE_COMPACT_DEFAULTS.tailChars,
799
+ maxNodesPerRequest: liveConfig.maxNodesPerRequest ?? LIVE_COMPACT_DEFAULTS.maxNodesPerRequest,
800
+ logger: runtime.logger,
801
+ }),
802
+ };
803
+ }
804
+ }
805
+
806
+ // ---- 2. refresh the probes --------------------------------------------
807
+ const provider = requestConfig?.provider ?? null;
808
+ const model = requestConfig?.model ?? null;
809
+ const reserved = Number.isFinite(requestConfig?.maxTokens) ? requestConfig.maxTokens : null;
810
+ if (provider && model) {
811
+ const llm = (() => {
812
+ try {
813
+ return ctx?.get?.('llm') ?? null;
814
+ } catch {
815
+ return null;
816
+ }
817
+ })();
818
+ if (llm && typeof llm.resolveModelInfo === 'function') {
819
+ try {
820
+ const info = await llm.resolveModelInfo(provider, model, signal ?? undefined);
821
+ const window = info?.context?.contextWindow ?? null;
822
+ if (Number.isFinite(window) && window > 0) {
823
+ hostProbes.window = { provider, model, window: Math.round(window) };
824
+ }
825
+ if (Number.isFinite(info?.defaultMaxTokens)) {
826
+ // The adapter's own default is what an unspecified request asks for.
827
+ hostProbes.reservedTokens = reserved ?? info.defaultMaxTokens;
828
+ }
829
+ } catch (error) {
830
+ hostProbes.lastError = asMemoryError(error).code;
831
+ }
832
+ }
833
+ }
834
+ if (reserved !== null) hostProbes.reservedTokens = reserved;
835
+ const tokenMeter = (() => {
836
+ try {
837
+ return ctx?.get?.('tokenMeter') ?? null;
838
+ } catch {
839
+ return null;
840
+ }
841
+ })();
842
+ if (tokenMeter && session && typeof tokenMeter.contextPressure === 'function') {
843
+ try {
844
+ const pressure = tokenMeter.contextPressure(session) ?? {};
845
+ // `pressureTokens` is input + cache read/write; `projectedTokens` may already
846
+ // include the pending completion. Prefer the larger — under-reporting is what
847
+ // let 854k tokens look small.
848
+ const candidates = [pressure.pressureTokens, pressure.projectedTokens].filter((value) => Number.isFinite(value));
849
+ if (candidates.length > 0) hostProbes.usedTokens = Math.max(...candidates);
850
+ if (Number.isFinite(pressure.contextWindow) && pressure.contextWindow > 0 && !hostProbes.window) {
851
+ hostProbes.window = { provider: provider ?? 'host', model: model ?? 'host', window: Math.round(pressure.contextWindow) };
852
+ }
853
+ } catch (error) {
854
+ hostProbes.lastError = asMemoryError(error).code;
855
+ }
856
+ }
857
+ hostProbes.updatedAt = memory.clock.now();
858
+
859
+ // ---- 3. fail fast on a request that CANNOT fit -------------------------
860
+ const state = memory.context.nativeState({
861
+ usedTokens: hostProbes.usedTokens ?? undefined,
862
+ reservedTokens: hostProbes.reservedTokens ?? undefined,
863
+ });
864
+ if (!state.hardExceeded) return state;
865
+ // Try to hand off first: even though it cannot shrink THIS request, it leaves a
866
+ // distilled tail for the next one instead of repeating the same failure.
867
+ let handoff = null;
868
+ try {
869
+ handoff = await memory.checkHandoff({ now: memory.clock.now() });
870
+ } catch {
871
+ /* the fail-fast below is the contract; a failed handoff only degrades recovery */
872
+ }
873
+ throw new MemoryError(
874
+ ErrorCodes.CONTEXT_EXCEEDED,
875
+ `request does not fit the model window: ${state.projectedTokens} tokens (prompt ${state.tokens} + reserved ${state.reservedTokens}) ` +
876
+ `>= ${state.nativeTokenLimit} (window source: ${state.windowSource}). ` +
877
+ 'Nothing was sent to the provider. Compact the conversation (host compaction) or start a new one; ' +
878
+ 'the handoff summary for the tail is available for the next conversation.',
879
+ {
880
+ usedTokens: state.tokens,
881
+ reservedTokens: state.reservedTokens,
882
+ projectedTokens: state.projectedTokens,
883
+ window: state.nativeTokenLimit,
884
+ windowSource: state.windowSource,
885
+ ratio: state.ratio,
886
+ handoff: handoff?.handoff?.summaryEventId ?? null,
887
+ liveCompact: runtime.lastLiveCompact ?? null,
888
+ },
889
+ );
890
+ };
891
+
725
892
  /**
726
893
  * The ONE maintenance entry point. Concurrency is refused, not queued: two
727
894
  * rebuilds racing would publish out of order, and a queue would silently run a
@@ -1811,6 +1978,27 @@ export async function apply(ctx, rawConfig = {}) {
1811
1978
  disposers.push(() => bus.off?.('session/event', captureListener));
1812
1979
  }
1813
1980
 
1981
+ // ---- v1.6.3: the request gate (Live Compact + fail-fast) ----------------
1982
+ // Runs as a plain (non-prepend) listener so it observes the FINAL routed config:
1983
+ // `await next()` returns `{provider, model, maxTokens}` for THIS call, and the
1984
+ // provider call happens after the chain resolves — throwing here aborts the
1985
+ // request instead of letting it be rejected by the API after the tokens are spent.
1986
+ const requestGuard = async ({ agent, signal }, next) => {
1987
+ const requestConfig = await next();
1988
+ if (!requestConfig || signal?.aborted) return requestConfig;
1989
+ try {
1990
+ await runtime.guardRequest({ agent, config: requestConfig, signal });
1991
+ } catch (error) {
1992
+ if (error instanceof MemoryError) throw error;
1993
+ runtime.logger?.warn?.(`hippocampus: request guard skipped: ${asMemoryError(error).code}: ${error?.message ?? error}`);
1994
+ }
1995
+ return requestConfig;
1996
+ };
1997
+ if (typeof bus.on === 'function') {
1998
+ bus.on('agent/request', requestGuard);
1999
+ disposers.push(() => bus.off?.('agent/request', requestGuard));
2000
+ }
2001
+
1814
2002
  const guard = (operation) => {
1815
2003
  if (runtime.phase === 'ready') return null;
1816
2004
  if (operation === 'recall' && runtime.legacy) return null; // served from legacy
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-layers-hippocampus",
3
- "version": "1.6.3",
3
+ "version": "1.6.4",
4
4
  "private": false,
5
5
  "description": "Layered long-term memory for DeepSeek Harness: append-only event log, rebuildable tag index, day diaries, independent semantic layer, L2.5 trend quarantine, offline knowledge graph and a Web UI panel.",
6
6
  "type": "module",
package/src/config.js CHANGED
@@ -206,7 +206,6 @@ export const DEFAULT_CONFIG = Object.freeze({
206
206
  // v1.6.0 cold-start injection switches (user request 2026-11-06):
207
207
  // - summary: inject the previous handoff summary so the first turn inherits context
208
208
  // - recentTurns: inject the last few turns of the handed-off conversation
209
- // - recentTurns: inject the last few turns of the handed-off conversation
210
209
  // (v1.6.3 default ON: a new conversation must not start "blind")
211
210
  coldStartInjectSummary: true,
212
211
  coldStartInjectRecentTurns: true,
@@ -220,7 +219,23 @@ export const DEFAULT_CONFIG = Object.freeze({
220
219
  autoSpaceFollow: false,
221
220
  autoRolloverEnabled: true,
222
221
  autoRolloverThreshold: 0.85,
222
+ // v1.6.3: USER OVERRIDE ONLY. The model's real context window comes from the host
223
+ // adapter (`llm.resolveModelInfo().context.contextWindow`); this value is used only
224
+ // when the host cannot report one (headless/legacy host). Treating it as the model
225
+ // window is what made every pressure ratio meaningless (8000 vs 1,048,576).
223
226
  nativeTokenLimit: 8000,
227
+ // v1.6.3 Live Compact: pointerize ONE oversized tool result before the request goes
228
+ // out. A single turn can otherwise add hundreds of thousands of tokens with no
229
+ // maintenance tick in between. `thresholdChars` is deliberately large so ordinary
230
+ // tool output is untouched; the host's own `tool-result-pruner` (ptc preset,
231
+ // 8192/4096/1024) stays the first line of defence when it exists.
232
+ liveCompact: {
233
+ enabled: true,
234
+ thresholdChars: 200_000,
235
+ headChars: 4_000,
236
+ tailChars: 2_000,
237
+ maxNodesPerRequest: 4,
238
+ },
224
239
  // Security (v1.5.1): moving memories across spaces is NEVER an autonomous
225
240
  // decision. While true, the engine refuses a model-initiated transfer unless
226
241
  // the tool call carries `user_approved: true`; the UI route is the human
@@ -818,6 +833,33 @@ function buildResolvedConfig(raw = {}, { env = process.env } = {}) {
818
833
  'context.nativeTokenLimit',
819
834
  { min: 512, max: 1_000_000 },
820
835
  );
836
+ // v1.6.3 Live Compact tunables. `thresholdChars` is compared against the total
837
+ // characters of ONE tool result's text blocks.
838
+ const liveCompactIn = contextIn.liveCompact ?? {};
839
+ const liveCompactEnabled = requireBoolean(
840
+ liveCompactIn.enabled === undefined ? defaults.context.liveCompact.enabled : liveCompactIn.enabled,
841
+ 'context.liveCompact.enabled',
842
+ );
843
+ const liveCompactThresholdChars = requireInteger(
844
+ liveCompactIn.thresholdChars === undefined ? defaults.context.liveCompact.thresholdChars : liveCompactIn.thresholdChars,
845
+ 'context.liveCompact.thresholdChars',
846
+ { min: 1000, max: 50_000_000 },
847
+ );
848
+ const liveCompactHeadChars = requireInteger(
849
+ liveCompactIn.headChars === undefined ? defaults.context.liveCompact.headChars : liveCompactIn.headChars,
850
+ 'context.liveCompact.headChars',
851
+ { min: 0, max: 1_000_000 },
852
+ );
853
+ const liveCompactTailChars = requireInteger(
854
+ liveCompactIn.tailChars === undefined ? defaults.context.liveCompact.tailChars : liveCompactIn.tailChars,
855
+ 'context.liveCompact.tailChars',
856
+ { min: 0, max: 1_000_000 },
857
+ );
858
+ const liveCompactMaxNodesPerRequest = requireInteger(
859
+ liveCompactIn.maxNodesPerRequest === undefined ? defaults.context.liveCompact.maxNodesPerRequest : liveCompactIn.maxNodesPerRequest,
860
+ 'context.liveCompact.maxNodesPerRequest',
861
+ { min: 1, max: 64 },
862
+ );
821
863
  // Security red line (v1.5.1): default TRUE. Only an explicit operator choice may
822
864
  // disable the consent gate; a malformed value is a config error, never "false".
823
865
  const contextRequireExplicitConsentForTransfer = requireBoolean(
@@ -1351,6 +1393,13 @@ function buildResolvedConfig(raw = {}, { env = process.env } = {}) {
1351
1393
  autoRolloverEnabled: contextAutoRolloverEnabled,
1352
1394
  autoRolloverThreshold: contextAutoRolloverThreshold,
1353
1395
  nativeTokenLimit: contextNativeTokenLimit,
1396
+ liveCompact: {
1397
+ enabled: liveCompactEnabled,
1398
+ thresholdChars: liveCompactThresholdChars,
1399
+ headChars: liveCompactHeadChars,
1400
+ tailChars: liveCompactTailChars,
1401
+ maxNodesPerRequest: liveCompactMaxNodesPerRequest,
1402
+ },
1354
1403
  requireExplicitConsentForTransfer: contextRequireExplicitConsentForTransfer,
1355
1404
  },
1356
1405
  temp: { ttlDays: tempTtlDays, promotionWindowDays: tempPromotionWindowDays },
@@ -14,6 +14,7 @@
14
14
  */
15
15
  import { decayFactor } from '../decay.js';
16
16
  import { readJson, round, snippet, writeJsonAtomic } from '../util.js';
17
+ import { requestPressure, resolveWindow } from './windowGuard.js';
17
18
 
18
19
  /** Cheap, stable estimate. Do not pretend it is an exact tokeniser. */
19
20
  export function estimateTokens(text) {
@@ -29,6 +30,9 @@ export class ContextEngine {
29
30
  * @param {number} [options.autoRolloverThreshold] fraction of native window that triggers a handoff
30
31
  * @param {boolean} [options.autoRolloverEnabled] false disables handoff and enables forced eviction
31
32
  * @param {Function} [options.getSessionTokens] () => tokens consumed by the live session
33
+ * @param {Function} [options.getHostWindow] () => model-native window from the HOST adapter (v1.6.3)
34
+ * @param {Function} [options.getHostUsedTokens] () => host-measured prompt pressure (v1.6.3)
35
+ * @param {Function} [options.getReservedTokens] () => completion budget the next request reserves (v1.6.3)
32
36
  */
33
37
  constructor({
34
38
  clock,
@@ -41,6 +45,9 @@ export class ContextEngine {
41
45
  autoRolloverThreshold,
42
46
  autoRolloverEnabled,
43
47
  getSessionTokens,
48
+ getHostWindow = null,
49
+ getHostUsedTokens = null,
50
+ getReservedTokens = null,
44
51
  } = {}) {
45
52
  this.clock = clock;
46
53
  this.getPolicy = getPolicy;
@@ -55,6 +62,15 @@ export class ContextEngine {
55
62
  this.rolloverThresholdOverride = Number.isFinite(autoRolloverThreshold) ? autoRolloverThreshold : null;
56
63
  this.rolloverEnabledOverride = typeof autoRolloverEnabled === 'boolean' ? autoRolloverEnabled : null;
57
64
  this.getSessionTokens = typeof getSessionTokens === 'function' ? getSessionTokens : null;
65
+ // v1.6.3: the HOST is the authority on the model's real window and on how full the
66
+ // prompt already is. These probes are optional so the engine still works headless
67
+ // (tests, legacy hosts) — but when present they override the hand-written
68
+ // `context.nativeTokenLimit`, which used to be treated as if it were the model
69
+ // window (a profile with 8000 against a 1,048,576-token model made every ratio
70
+ // meaningless).
71
+ this.getHostWindow = typeof getHostWindow === 'function' ? getHostWindow : null;
72
+ this.getHostUsedTokens = typeof getHostUsedTokens === 'function' ? getHostUsedTokens : null;
73
+ this.getReservedTokens = typeof getReservedTokens === 'function' ? getReservedTokens : null;
58
74
  this.statsFile = statsFile;
59
75
  /** @type {Array<object>} insertion-ordered block table */
60
76
  this.blocks = [];
@@ -90,9 +106,37 @@ export class ContextEngine {
90
106
  };
91
107
  }
92
108
 
93
- get nativeTokenLimit() {
109
+ /**
110
+ * v1.6.3: the model's REAL context window, resolved host-first.
111
+ *
112
+ * Precedence: host adapter (`llm.resolveModelInfo().context.contextWindow`) >
113
+ * explicit user override (`context.nativeTokenLimit`) > 8000 legacy fallback.
114
+ * The user override is still honoured when the host cannot report a window (an
115
+ * old host or a provider without a catalogue), but it can no longer masquerade as
116
+ * the model's limit when the host knows better.
117
+ *
118
+ * @returns {{ window: number, source: 'host'|'config'|'default', hostWindow: number|null, configuredWindow: number|null }}
119
+ */
120
+ get window() {
94
121
  const pol = this.getPolicy?.()?.context ?? {};
95
- return this.nativeTokenLimitOverride ?? pol.nativeTokenLimit ?? 8000;
122
+ let hostWindow = null;
123
+ if (this.getHostWindow) {
124
+ try {
125
+ hostWindow = this.getHostWindow();
126
+ } catch {
127
+ hostWindow = null;
128
+ }
129
+ }
130
+ return resolveWindow({
131
+ hostWindow,
132
+ configuredWindow: this.nativeTokenLimitOverride ?? pol.nativeTokenLimit ?? null,
133
+ fallback: 8000,
134
+ });
135
+ }
136
+
137
+ /** Back-compat: the number only. Prefer `window` when the source matters. */
138
+ get nativeTokenLimit() {
139
+ return this.window.window;
96
140
  }
97
141
 
98
142
  get rolloverThreshold() {
@@ -108,49 +152,88 @@ export class ContextEngine {
108
152
  /**
109
153
  * The native/layered decision, derived purely from measurements.
110
154
  *
111
- * `tokens` is the effective occupancy: the larger of the blocks this engine
112
- * tracks and the live session size. A session can be inside the native window
113
- * while the engine's own block table is empty (or vice versa), so neither number
114
- * alone is the honest answer. `getSessionTokens` is the injection point; a
115
- * caller may also pass `sessionTokens` per call.
155
+ * v1.6.3 rewrite ("fix the denominator AND the formula"):
116
156
  *
117
- * mode 'native': the model's own window can hold this session; no folding is
118
- * allowed (there is nothing to fold into yet). mode 'layered': the session has
119
- * outgrown the native window, so the layered memory pipeline may take over.
157
+ * - the denominator is `this.window` — the HOST's real model window when the
158
+ * host can report one, not the hand-written `context.nativeTokenLimit`;
159
+ * - occupancy prefers the HOST's measured prompt pressure (`tokenMeter`, which
160
+ * includes system prompt + tool schemas + full history) over our own
161
+ * character/4 estimate of captured turns;
162
+ * - the decision is made on `used + reserved`, where `reserved` is the completion
163
+ * budget the next request will actually ask for. A request whose prompt fits the
164
+ * window but whose `max_tokens` pushes the SUM past the limit is rejected by the
165
+ * provider — that is exactly the 854,668 + 256,000 > 1,048,576 failure.
120
166
  *
121
- * `remainingTokens` is headroom to the HANDOFF point (threshold * native), not
122
- * to the hard limit: crossing the hard limit is already too late to hand off.
167
+ * `remainingTokens` is headroom to the HANDOFF point (threshold * window), not to
168
+ * the hard limit: crossing the hard limit is already too late to hand off.
123
169
  *
124
- * @param {{ now?: number, sessionTokens?: number }} [options]
170
+ * @param {{ now?: number, sessionTokens?: number, usedTokens?: number, reservedTokens?: number }} [options]
125
171
  */
126
- nativeState({ now = this.clock.now(), sessionTokens } = {}) {
172
+ nativeState({ now = this.clock.now(), sessionTokens, usedTokens, reservedTokens } = {}) {
127
173
  void now; // part of the API so callers can pin one timestamp across a snapshot
128
- const limit = this.nativeTokenLimit;
174
+ const resolved = this.window;
175
+ const limit = resolved.window;
129
176
  const threshold = this.rolloverThreshold;
130
177
  const enabled = this.rolloverEnabled;
131
178
  const reported = Number.isFinite(sessionTokens) ? sessionTokens : this.getSessionTokens?.();
132
179
  const session = Number.isFinite(reported) ? reported : 0;
133
- const tokens = Math.max(this.tokens(), session);
134
- const ratio = round(limit > 0 ? tokens / limit : 0, 4);
135
- const handoffThresholdTokens = Math.round(threshold * limit);
180
+
181
+ // Host-measured pressure wins; the block table and the session estimate are the
182
+ // floor (never report less than what we can see ourselves).
183
+ let hostUsed = Number.isFinite(usedTokens) ? usedTokens : null;
184
+ if (hostUsed === null && this.getHostUsedTokens) {
185
+ try {
186
+ const probed = this.getHostUsedTokens();
187
+ hostUsed = Number.isFinite(probed) ? probed : null;
188
+ } catch {
189
+ hostUsed = null;
190
+ }
191
+ }
192
+ const tokens = Math.max(this.tokens(), session, hostUsed ?? 0);
193
+
194
+ let reserved = Number.isFinite(reservedTokens) ? reservedTokens : null;
195
+ if (reserved === null && this.getReservedTokens) {
196
+ try {
197
+ const probed = this.getReservedTokens();
198
+ reserved = Number.isFinite(probed) ? probed : null;
199
+ } catch {
200
+ reserved = null;
201
+ }
202
+ }
203
+ const pressure = requestPressure({
204
+ usedTokens: tokens,
205
+ reservedTokens: reserved ?? 0,
206
+ window: limit,
207
+ threshold,
208
+ });
209
+ const ratio = pressure.ratio;
210
+ const handoffThresholdTokens = pressure.handoffAtTokens;
136
211
  return {
137
212
  mode: tokens < limit ? 'native' : 'layered',
138
213
  tokens,
139
- // Effective occupancy (max of block table and session). `effectiveTokens` is
140
- // the canonical name; `sessionTokens` is kept as an alias so existing callers
141
- // that read the session-side name keep working.
214
+ // Effective occupancy (max of block table, session estimate and host pressure).
142
215
  effectiveTokens: tokens,
143
216
  sessionTokens: tokens,
144
217
  nativeTokenLimit: limit,
218
+ /** Where the window came from: host adapter, user override, or the legacy default. */
219
+ windowSource: resolved.source,
220
+ hostWindow: resolved.hostWindow,
221
+ configuredWindow: resolved.configuredWindow,
145
222
  ratio,
223
+ // The honest decision input: the prompt PLUS what the answer is allowed to be.
224
+ reservedTokens: pressure.reservedTokens,
225
+ projectedTokens: pressure.projectedTokens,
226
+ projectedRatio: pressure.projectedRatio,
227
+ /** True when `used + reserved` is already at/over the hard window: must not be sent. */
228
+ hardExceeded: pressure.hardExceeded,
146
229
  rolloverThreshold: threshold,
147
230
  rolloverEnabled: enabled,
148
- rolloverDue: enabled && ratio >= threshold,
231
+ rolloverDue: enabled && pressure.handoffDue,
149
232
  remainingTokens: Math.max(0, Math.ceil(threshold * limit - tokens)),
150
233
  // Rollover disabled means no handoff can move the session; once the native
151
234
  // window is effectively exhausted (95%) eviction is the only honest option
152
235
  // left, and it must be FORCED rather than silently ignored.
153
- forceEvictionDue: !enabled && ratio >= 0.95,
236
+ forceEvictionDue: !enabled && (ratio >= 0.95 || pressure.hardExceeded),
154
237
  handoffThresholdTokens,
155
238
  };
156
239
  }
@@ -0,0 +1,201 @@
1
+ /**
2
+ * v1.6.3 — Live Compact: turn ONE oversized tool result into a POINTER.
3
+ *
4
+ * The failure this prevents is sudden, not gradual: a single `read_file` /
5
+ * `bash` / web fetch can return hundreds of thousands of characters in one turn,
6
+ * and that turn's request then blows the window before any "pressure" threshold
7
+ * gets a chance to fire. Waiting for the next maintenance tick is useless — the
8
+ * request is composed now.
9
+ *
10
+ * Policy (deliberately conservative):
11
+ * - only `tool/result` surface nodes are touched;
12
+ * - only when the node alone exceeds `liveCompact.thresholdChars`;
13
+ * - the head and the tail are kept verbatim, the middle becomes ONE pointer line
14
+ * carrying the durable identity (session seq / callId) so the model can ask
15
+ * for the full text again via `deep_raw` instead of carrying it forever;
16
+ * - the replacement is appended through the HOST's own surface mechanism
17
+ * (`session.append(..., { surfaceOp: { op: 'replace' } })`), never by editing
18
+ * history in place. If the host rejects it we log and continue: an un-pruned
19
+ * request is better than a broken turn.
20
+ *
21
+ * Zero dependencies: `freezeMessage` is not imported. The host freezes what it
22
+ * accepts; a plain frozen-by-us object is enough for the surface protocol.
23
+ */
24
+
25
+ /** Marker inserted where the removed middle was. Machine-greppable on purpose. */
26
+ export const POINTER_MARKER = '[[hippocampus:live-compact';
27
+
28
+ /** Defaults; overridable through `context.liveCompact.*`. */
29
+ export const LIVE_COMPACT_DEFAULTS = Object.freeze({
30
+ enabled: true,
31
+ thresholdChars: 200_000,
32
+ headChars: 4_000,
33
+ tailChars: 2_000,
34
+ maxNodesPerRequest: 4,
35
+ });
36
+
37
+ /** Total code-point length of the text blocks of one tool result. */
38
+ export function contentChars(content) {
39
+ let chars = 0;
40
+ for (const block of Array.isArray(content) ? content : []) {
41
+ if (block && block.type === 'text' && typeof block.text === 'string') chars += block.text.length;
42
+ }
43
+ return chars;
44
+ }
45
+
46
+ /**
47
+ * Replace the middle of a text with a pointer, keeping head and tail.
48
+ *
49
+ * Slicing is by code point so a surrogate pair is never split. The pointer names
50
+ * the durable coordinates a later `deep_raw` lookup needs.
51
+ *
52
+ * @param {string} text
53
+ * @param {{ headChars?: number, tailChars?: number, ref?: { seq?: number, callId?: string, tool?: string, eventId?: string } }} [options]
54
+ * @returns {{ text: string, removedChars: number }}
55
+ */
56
+ export function pointerizeText(text, { headChars = 4000, tailChars = 2000, ref = {} } = {}) {
57
+ const points = Array.from(String(text ?? ''));
58
+ const head = Math.max(0, Math.trunc(headChars));
59
+ const tail = Math.max(0, Math.trunc(tailChars));
60
+ if (points.length <= head + tail + 200) return { text: String(text ?? ''), removedChars: 0 };
61
+ const removed = points.length - head - tail;
62
+ const pointer = `\n\n${pointerLine({ removedChars: removed, ref })}\n\n`;
63
+ return {
64
+ text: points.slice(0, head).join('') + pointer + points.slice(points.length - tail).join(''),
65
+ removedChars: removed,
66
+ };
67
+ }
68
+
69
+ /**
70
+ * Plan the pointerization of one tool result's content blocks.
71
+ *
72
+ * The global head/tail character budgets are distributed across the text blocks in
73
+ * order: a block keeps its intersection with `[0, headChars)` and with
74
+ * `[total - tailChars, total)`, and drops whatever falls in between. Non-text
75
+ * blocks (images, files) are always preserved — they are not text flood. One
76
+ * pointer block is inserted at the first dropped position.
77
+ *
78
+ * @param {Array<object>} content tool result content blocks
79
+ * @param {{ thresholdChars?: number, headChars?: number, tailChars?: number, ref?: object }} [options]
80
+ * @returns {{ changed: boolean, content: Array<object>, charsBefore: number, charsAfter: number }}
81
+ */
82
+ export function planPointerization(content, { thresholdChars = 200_000, headChars = 4000, tailChars = 2000, ref = {} } = {}) {
83
+ const blocks = Array.isArray(content) ? content : [];
84
+ const before = contentChars(blocks);
85
+ if (before <= thresholdChars) return { changed: false, content: blocks, charsBefore: before, charsAfter: before };
86
+
87
+ const head = Math.max(0, Math.trunc(headChars));
88
+ const tail = Math.max(0, Math.trunc(tailChars));
89
+ const tailStart = Math.max(0, before - tail);
90
+ const pointerText = pointerLine({
91
+ removedChars: Math.max(0, tailStart - head),
92
+ ref,
93
+ });
94
+
95
+ const out = [];
96
+ let consumed = 0;
97
+ let pointerInserted = false;
98
+ for (const block of blocks) {
99
+ if (!block || block.type !== 'text' || typeof block.text !== 'string') {
100
+ out.push(block);
101
+ continue;
102
+ }
103
+ const points = Array.from(block.text);
104
+ const start = consumed;
105
+ const end = start + points.length;
106
+ consumed = end;
107
+
108
+ const headEnd = Math.min(end, head);
109
+ if (headEnd > start) out.push({ ...block, text: points.slice(0, headEnd - start).join('') });
110
+
111
+ if (!pointerInserted && end > head) {
112
+ out.push({ type: 'text', text: pointerText });
113
+ pointerInserted = true;
114
+ }
115
+
116
+ const tailBegin = Math.max(start, tailStart);
117
+ if (end > tailBegin) out.push({ ...block, text: points.slice(tailBegin - start).join('') });
118
+ }
119
+ if (!pointerInserted) out.push({ type: 'text', text: pointerText });
120
+
121
+ const after = contentChars(out);
122
+ if (after >= before) return { changed: false, content: blocks, charsBefore: before, charsAfter: before };
123
+ return { changed: true, content: out, charsBefore: before, charsAfter: after };
124
+ }
125
+
126
+ /** The one machine-greppable pointer line a pruned result carries. */
127
+ function pointerLine({ removedChars, ref = {} }) {
128
+ const where = [
129
+ ref.seq === undefined ? null : `seq=${ref.seq}`,
130
+ ref.callId ? `call=${ref.callId}` : null,
131
+ ref.tool ? `tool=${ref.tool}` : null,
132
+ ].filter(Boolean);
133
+ return (
134
+ `${POINTER_MARKER}: removed ${removedChars} chars of the middle; ` +
135
+ `the full text is still in the raw log (${where.join(', ') || 'raw log'}) — ` +
136
+ 'call the hippocampus deep_raw tool with those coordinates if you need it again]]'
137
+ );
138
+ }
139
+
140
+ /**
141
+ * Apply Live Compact to a live session surface.
142
+ *
143
+ * Returns a report instead of throwing: this runs on the request path, where a
144
+ * failure must degrade (send the un-pruned request) rather than break the turn.
145
+ *
146
+ * @param {object} session host Session (surface + append + deriveEventMessage)
147
+ * @param {{ thresholdChars?: number, headChars?: number, tailChars?: number, maxNodesPerRequest?: number, logger?: object }} [options]
148
+ */
149
+ export function liveCompactSession(session, options = {}) {
150
+ const {
151
+ thresholdChars = LIVE_COMPACT_DEFAULTS.thresholdChars,
152
+ headChars = LIVE_COMPACT_DEFAULTS.headChars,
153
+ tailChars = LIVE_COMPACT_DEFAULTS.tailChars,
154
+ maxNodesPerRequest = LIVE_COMPACT_DEFAULTS.maxNodesPerRequest,
155
+ logger = null,
156
+ } = options;
157
+ const report = { scanned: 0, pruned: 0, charsRemoved: 0, nodes: [], failed: null };
158
+ if (!session || typeof session.append !== 'function' || !session.surface || typeof session.eventAt !== 'function') {
159
+ return report;
160
+ }
161
+ try {
162
+ const seqs = [...(session.surface.nodes ?? [])];
163
+ for (const seq of seqs) {
164
+ if (report.pruned >= maxNodesPerRequest) break;
165
+ const event = session.eventAt(seq);
166
+ if (!event || event.type !== 'tool/result') continue;
167
+ report.scanned += 1;
168
+ const original = typeof session.deriveEventMessage === 'function' ? session.deriveEventMessage(event) : null;
169
+ if (!original || !Array.isArray(original.content)) continue;
170
+ const plan = planPointerization(original.content, {
171
+ thresholdChars,
172
+ headChars,
173
+ tailChars,
174
+ ref: { seq, callId: original?.source?.callId, tool: original?.source?.tool },
175
+ });
176
+ if (!plan.changed) continue;
177
+ try {
178
+ session.append('compaction/prune', {
179
+ shadowedRange: { start: seq, end: seq },
180
+ shadowedSeqs: [seq],
181
+ shadowedTokenCount: Math.ceil(plan.charsBefore / 4),
182
+ });
183
+ const replacement = session.append(
184
+ 'tool/result',
185
+ { ...event.data, message: { ...original, content: plan.content } },
186
+ { surfaceOp: { op: 'replace', startSeq: seq, endSeq: seq }, sourceEventSeqs: [seq] },
187
+ );
188
+ report.pruned += 1;
189
+ report.charsRemoved += plan.charsBefore - plan.charsAfter;
190
+ report.nodes.push({ originalSeq: seq, replacementSeq: replacement?.seq ?? null, charsBefore: plan.charsBefore, charsAfter: plan.charsAfter });
191
+ } catch (error) {
192
+ report.failed = error?.message ?? String(error);
193
+ logger?.warn?.(`hippocampus: live-compact could not replace seq ${seq}: ${report.failed}`);
194
+ }
195
+ }
196
+ } catch (error) {
197
+ report.failed = error?.message ?? String(error);
198
+ logger?.warn?.(`hippocampus: live-compact failed: ${report.failed}`);
199
+ }
200
+ return report;
201
+ }
@@ -0,0 +1,118 @@
1
+ /**
2
+ * v1.6.3 — real context-window guard (pure functions).
3
+ *
4
+ * The 2026-11-14 incident: a request carried 854,668 message tokens and reserved
5
+ * 256,000 completion tokens (`DEFAULT_MAX_TOKENS` of the llm-deepseek provider).
6
+ * 854,668 + 256,000 = 1,110,668 > 1,048,576, so the provider answered
7
+ * `CONTEXT_WINDOW_EXCEEDED` — after the prompt was already paid for. The memory
8
+ * plugin had been measuring the session against `context.nativeTokenLimit: 8000`
9
+ * (a hand-written config value), i.e. against the wrong denominator entirely, and
10
+ * it never reserved room for the completion.
11
+ *
12
+ * This module is deliberately dependency-free and synchronous: it takes numbers in
13
+ * and returns a decision. The HOST half (service probes) lives in index.js; the
14
+ * engine asks for those numbers through injected callbacks.
15
+ */
16
+
17
+ /** Where the effective window came from. Surfaced so a panel can explain itself. */
18
+ export const WINDOW_SOURCE = Object.freeze({ HOST: 'host', CONFIG: 'config', DEFAULT: 'default' });
19
+
20
+ /**
21
+ * Pick the denominator for every pressure calculation.
22
+ *
23
+ * Precedence: the model's REAL window (host adapter) always wins; the config value
24
+ * is demoted to a user override that only applies when the host cannot answer (an
25
+ * older host, a test double, a headless CLI). This is the whole point of the fix:
26
+ * `context.nativeTokenLimit` must never be able to masquerade as the real window.
27
+ *
28
+ * @param {{ hostWindow?: number|null, configuredWindow?: number|null, fallback?: number }} input
29
+ * @returns {{ window: number, source: string, hostWindow: number|null, configuredWindow: number|null }}
30
+ */
31
+ export function resolveWindow({ hostWindow = null, configuredWindow = null, fallback = 8000 } = {}) {
32
+ const host = positive(hostWindow);
33
+ const configured = positive(configuredWindow);
34
+ const base = positive(fallback) ?? 8000;
35
+ const window = host ?? configured ?? base;
36
+ const source = host !== null ? WINDOW_SOURCE.HOST : configured !== null ? WINDOW_SOURCE.CONFIG : WINDOW_SOURCE.DEFAULT;
37
+ return { window, source, hostWindow: host, configuredWindow: configured };
38
+ }
39
+
40
+ /**
41
+ * The ONE request-pressure calculation.
42
+ *
43
+ * `projected` is what the provider will actually be billed for: the prompt plus the
44
+ * output budget the request reserves. Measuring only the prompt is what let a
45
+ * "comfortable" 60% prompt turn into an over-window request.
46
+ *
47
+ * @param {object} input
48
+ * @param {number} input.usedTokens prompt-side occupancy (host-reported when available)
49
+ * @param {number} [input.reservedTokens] completion budget the request reserves
50
+ * @param {number} input.window real model window
51
+ * @param {number} [input.threshold] handoff trigger fraction (default 0.85)
52
+ * @returns {object} an immutable decision record
53
+ */
54
+ export function requestPressure({ usedTokens, reservedTokens = 0, window, threshold = 0.85 }) {
55
+ const used = clampCount(usedTokens);
56
+ const reserved = clampCount(reservedTokens);
57
+ const limit = positive(window) ?? 8000;
58
+ const ratio = round4(used / limit);
59
+ const projected = used + reserved;
60
+ const projectedRatio = round4(projected / limit);
61
+ const trigger = Number.isFinite(threshold) && threshold > 0 && threshold <= 1 ? threshold : 0.85;
62
+ const handoffAt = Math.round(trigger * limit);
63
+ return {
64
+ usedTokens: used,
65
+ reservedTokens: reserved,
66
+ projectedTokens: projected,
67
+ window: limit,
68
+ threshold: trigger,
69
+ ratio,
70
+ projectedRatio,
71
+ handoffAtTokens: handoffAt,
72
+ /** The handoff point is reached by prompt + reserved output. */
73
+ handoffDue: projected >= handoffAt,
74
+ /** The request provably cannot fit: block it locally instead of paying for a rejection. */
75
+ hardExceeded: projected >= limit,
76
+ /** Room left before the handoff point (never negative). */
77
+ remainingTokens: Math.max(0, handoffAt - projected),
78
+ /** Room left before the hard limit (never negative). */
79
+ remainingToLimit: Math.max(0, limit - projected),
80
+ };
81
+ }
82
+
83
+ function positive(value) {
84
+ return Number.isFinite(value) && value > 0 ? Math.round(value) : null;
85
+ }
86
+
87
+ function clampCount(value) {
88
+ return Number.isFinite(value) && value > 0 ? Math.round(value) : 0;
89
+ }
90
+
91
+ function round4(value) {
92
+ return Math.round(value * 10_000) / 10_000;
93
+ }
94
+
95
+ /**
96
+ * How much a handoff marker may be "topped up" before it must be re-distilled.
97
+ *
98
+ * v1.6.3 removed the `autoNewSession` controller, so a conversation keeps its
99
+ * session id across a handoff. The old `if (marker.active) return` therefore froze
100
+ * the state machine forever after the FIRST handoff. Re-handing-off inside the same
101
+ * conversation is allowed once pressure grew this much past the marker's own ratio
102
+ * (5 percentage points) — enough to mean "real growth", small enough to stay useful.
103
+ */
104
+ export const REHANDOFF_DELTA = 0.05;
105
+
106
+ /**
107
+ * Decide whether an ACTIVE marker must be re-distilled in the same conversation.
108
+ *
109
+ * @param {{ markerRatio?: number|null, projectedRatio: number, sameSession: boolean }} input
110
+ * @returns {{ rehandoff: boolean, reason: string }}
111
+ */
112
+ export function rehandoffDecision({ markerRatio = null, projectedRatio = 0, sameSession = true }) {
113
+ if (!sameSession) return { rehandoff: false, reason: 'different-session' };
114
+ const base = Number.isFinite(markerRatio) && markerRatio > 0 ? markerRatio : 0;
115
+ if (projectedRatio >= 0.95) return { rehandoff: true, reason: 'near-hard-limit' };
116
+ if (projectedRatio - base >= REHANDOFF_DELTA) return { rehandoff: true, reason: 'pressure-growth' };
117
+ return { rehandoff: false, reason: 'below-delta' };
118
+ }
package/src/errors.js CHANGED
@@ -134,6 +134,16 @@ export const ErrorCodes = Object.freeze({
134
134
  * deterministic fallback tag instead of failing the maintenance pass.
135
135
  */
136
136
  SEMANTIC_TAG_REQUIRED: 'MEM_E_SEMANTIC_TAG_REQUIRED',
137
+
138
+ // ---- v1.6.3 context-window guard (Live Compact) ------------------------
139
+ /**
140
+ * The next request provably cannot fit the model's REAL context window
141
+ * (`used + reservedCompletion > window`). Thrown from the `agent/request`
142
+ * middleware BEFORE the request is sent, so the user sees a local, explicit
143
+ * failure instead of the provider answering `CONTEXT_WINDOW_EXCEEDED` after
144
+ * paying for the prompt.
145
+ */
146
+ CONTEXT_EXCEEDED: 'MEM_E_CONTEXT_EXCEEDED',
137
147
  });
138
148
 
139
149
  export class MemoryError extends Error {
package/src/memory.js CHANGED
@@ -51,6 +51,7 @@ import {
51
51
  import { SemanticStore } from './semantic/semanticStore.js';
52
52
  import { TempSemanticStore } from './semantic/tempSemantic.js';
53
53
  import { ContextEngine } from './context/contextEngine.js';
54
+ import { rehandoffDecision } from './context/windowGuard.js';
54
55
  import { DEFAULT_SPACE_ID, SpaceRouter, normaliseSpaceId, validateNewSpaceId } from './spaces/singleSpace.js';
55
56
  import { nextRun, parseCron } from './cron.js';
56
57
 
@@ -452,13 +453,19 @@ export class Memory {
452
453
  maxTokens: config.context?.maxTokens,
453
454
  threshold: config.context?.threshold,
454
455
  target: config.context?.target,
455
- // v1.5.0: pure physical-layer context accounting. `nativeTokenLimit` is the
456
- // model's native window (Qwen mode): below it nothing is folded; the rollover
457
- // threshold is measured against it, not against the memory-block budget.
456
+ // v1.5.0: pure physical-layer context accounting. `nativeTokenLimit` is a USER
457
+ // OVERRIDE only (v1.6.3): the model's real window comes from the host adapter
458
+ // through `getHostWindow` (see index.js), and this value is the fallback when
459
+ // the host cannot report one.
458
460
  nativeTokenLimit: config.context?.nativeTokenLimit,
459
461
  autoRolloverThreshold: config.context?.autoRolloverThreshold,
460
462
  autoRolloverEnabled: config.context?.autoRolloverEnabled,
461
463
  getSessionTokens: () => this.sessionUsage().tokens,
464
+ // v1.6.3: the three host probes. All optional: a headless/legacy host leaves them
465
+ // null and the engine degrades to the configured window and its own estimate.
466
+ getHostWindow: typeof config.getHostWindow === 'function' ? config.getHostWindow : null,
467
+ getHostUsedTokens: typeof config.getHostUsedTokens === 'function' ? config.getHostUsedTokens : null,
468
+ getReservedTokens: typeof config.getReservedTokens === 'function' ? config.getReservedTokens : null,
462
469
  statsFile: path.join(this.paths.state, 'context.json'),
463
470
  });
464
471
  this.deletePipeline = new DeletePipeline({
@@ -1866,7 +1873,28 @@ export class Memory {
1866
1873
  return { ...base, handoff: this.handoffState(), forcedEviction };
1867
1874
  }
1868
1875
  if (!native.rolloverDue) return base;
1869
- if (marker.active) return base;
1876
+ // v1.6.3: a marker that is still ACTIVE in the SAME session used to return early
1877
+ // forever. With the client-side "open a new conversation" controller removed, the
1878
+ // session id no longer changes on handoff — so the first handoff permanently bricked
1879
+ // the state machine and every later threshold crossing was silently ignored
1880
+ // ("80% never triggered autoHandoff").
1881
+ //
1882
+ // Now an active marker re-handoffs when the pressure has materially GROWN past the
1883
+ // previous handoff's ratio (or we are about to hit the hard limit). The previous
1884
+ // marker is consumed first, so the new one describes the current tail, not the tail
1885
+ // that was already distilled.
1886
+ let rehandoff = null;
1887
+ if (marker.active) {
1888
+ const sameSession = !marker.sessionId || !usage.sessionId || marker.sessionId === usage.sessionId;
1889
+ rehandoff = rehandoffDecision({
1890
+ markerRatio: Number.isFinite(marker.ratio) ? marker.ratio : null,
1891
+ projectedRatio: Number.isFinite(native.projectedRatio) ? native.projectedRatio : native.ratio,
1892
+ sameSession,
1893
+ });
1894
+ if (!rehandoff.rehandoff) return { ...base, rehandoff };
1895
+ this.clearHandoff({ reason: 'rehandoff', consumedBy: usage.sessionId });
1896
+ marker = this.handoffState();
1897
+ }
1870
1898
 
1871
1899
  let distilled = null;
1872
1900
  let failure = null;
@@ -1921,7 +1949,7 @@ export class Memory {
1921
1949
  ensureDir(this.paths.state);
1922
1950
  writeJsonAtomic(this.handoffPath(), next);
1923
1951
  this._markBriefingDirty();
1924
- return { ...base, handoff: next, distilled, failure };
1952
+ return { ...base, handoff: next, distilled, failure, rehandoff };
1925
1953
  } catch (error) {
1926
1954
  // Marker write must never reject the caller. Report a degraded result and let
1927
1955
  // the host proceed; the next session still resets its own baseline.
@@ -2741,6 +2769,13 @@ export class Memory {
2741
2769
  mode: native.mode,
2742
2770
  tokens: native.tokens,
2743
2771
  nativeTokenLimit: native.nativeTokenLimit,
2772
+ // v1.6.3: make the denominator auditable — a window that came from the config
2773
+ // override instead of the host adapter is exactly what hid the 1M overflow.
2774
+ windowSource: native.windowSource ?? null,
2775
+ hostWindow: native.hostWindow ?? null,
2776
+ projectedTokens: native.projectedTokens ?? null,
2777
+ reservedTokens: native.reservedTokens ?? null,
2778
+ hardExceeded: native.hardExceeded === true,
2744
2779
  threshold: native.rolloverThreshold,
2745
2780
  ratio: native.ratio,
2746
2781
  remainingTokens: native.remainingTokens,