dsh-layers-hippocampus 1.9.22 → 1.9.25
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 +119 -0
- package/index.js +477 -15
- package/package.json +1 -1
- package/src/config.js +47 -1
- package/src/context/inlineFold.js +58 -0
- package/src/context/smartPrune.js +32 -0
- package/src/context/windowGuard.js +26 -0
- package/src/memory.js +86 -18
- package/src/webRoutes.js +8 -0
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,125 @@ 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.9.25] — 2026-12-02
|
|
8
|
+
|
|
9
|
+
**C 批:模块五 v2「逻辑接力」——消费即投递,锚点交给宿主 compaction。**
|
|
10
|
+
|
|
11
|
+
### 0. 现场:交接"完成"了,接力没送达
|
|
12
|
+
|
|
13
|
+
2026-12-02 13:13:09,`f23719e8` 在 61% 触发交接,写下 marker 与摘要事件 `ev_8b1ddf…`;
|
|
14
|
+
13:18:21 新会话 `341231cd` 首轮装配时,marker 被"新会话"判据消费(`consumedAt` 与那条
|
|
15
|
+
`user/message` **同期**),但那条 prompt 的 memory-state 段落里**没有任何 `[Cold-Start …]`**。
|
|
16
|
+
两条老路径互不等待:`observeSessionTokens` / `maintainHandoffMarker` 看到 session id 变了就
|
|
17
|
+
`clearHandoff`;`noteColdStart` 在会话事件里 arm,等 prompt 装配时匹配。先消费后 arm 就永久丢一次,
|
|
18
|
+
而且两边记下的 session id 不一定是同一个(现场留下 `unknown` 与 `session-8d8bc7a6` 两条永不匹配的 pending)。
|
|
19
|
+
|
|
20
|
+
### 1. 装配即投递(`runtime.adoptableHandoff`)
|
|
21
|
+
|
|
22
|
+
`coldStartText()` 不再只认 armed 的 pending:只要存在**别人的、还没投递过的** marker,这一轮
|
|
23
|
+
memory-state 就带上骨架——不依赖任何 arm 顺序。adopt 规则(缺一不可):
|
|
24
|
+
有 `summaryEventId`;不是本会话自己写的(A 批的持久化规则);本会话没收到过;
|
|
25
|
+
若是已消费的 marker,必须是**本会话消费的**且不超过 24 小时(`HANDOFF_DELIVERY_WINDOW_MS`)。
|
|
26
|
+
投递成功即落账:`state: "delivered"` + `deliveredAt`(新状态,`HANDOFF_STATES.DELIVERED`),
|
|
27
|
+
`consumedBy = 当前会话`。`/memory resume`(`armColdStartNow`)仍可显式重放一次。
|
|
28
|
+
|
|
29
|
+
### 2. 锚点:用宿主的 compaction,不自造(`context.anchor`)
|
|
30
|
+
|
|
31
|
+
定调:DSH 的会话是 append-only,插件**不许**物理重写 transcript;官方接缝是可选服务
|
|
32
|
+
`ctx.get('compaction')`——`compactNow()` 把一段 surface 折成**一个摘要节点**(旧区间只是
|
|
33
|
+
shadowed),sessionId 不变。所以插件只做策略层:
|
|
34
|
+
|
|
35
|
+
- `runtime.requestAnchor()`:`anchor.enabled` 默认 **false**;关=不动(`anchor-disabled`),
|
|
36
|
+
服务缺失=`service-unavailable`(退回"新会话 + 投递"老路径),成功则记录
|
|
37
|
+
`compactionId / summarySeq / shadowedRange / shadowedTokenCount`;
|
|
38
|
+
- 交接产出 live marker 时排队(`runtime.pendingAnchor`),在**下一个 `turn/end`** 执行——
|
|
39
|
+
`compactNow` 的契约是"idle agent",不能在流式回合里抢;
|
|
40
|
+
- 折完把骨架重新武装到**同一会话**(`source: "anchor-post-compaction"`),于是锚点之后紧接骨架;
|
|
41
|
+
- 宿主自己的 `ManualCompactionError` 代码(busy / cancelled / changed-span)原样记进
|
|
42
|
+
`runtime.lastAnchor.reason`,`asMemoryError()` 不再把它压成 `MEM_E_IO`;
|
|
43
|
+
- 120 秒 `unref` 超时 + 外部 signal 取消,绝不挂住进程。
|
|
44
|
+
- `context.anchor.enabled` 进 `EDITABLE_CONFIG_KEYS`(设置页可开关);`/stats` 新增 `anchor` 视图。
|
|
45
|
+
|
|
46
|
+
全程:不改 `sessionId`、不追加会话事件、不调 `startSession`、不重写 transcript。
|
|
47
|
+
|
|
48
|
+
### Tests
|
|
49
|
+
|
|
50
|
+
`test/v2002.cbatch.test.js`(7)+ `test/v2003.anchor.test.js`(7)先红后绿;全套 **775/775**。
|
|
51
|
+
|
|
52
|
+
## [1.9.24] — 2026-12-02
|
|
53
|
+
|
|
54
|
+
**B 批:折叠搬出请求路径——事件驱动 + 空闲收敛。**
|
|
55
|
+
|
|
56
|
+
### 事件驱动(模块二)
|
|
57
|
+
|
|
58
|
+
`session/event` 里遇到 `tool/result` 且单条字符数 ≥ `context.inlineFold.thresholdChars`
|
|
59
|
+
(默认 **8000**,`enabled` 默认 **false**)→ `setImmediate` 里用 `liveCompactSession`
|
|
60
|
+
把**那一条**原地换成带 id 的头尾+指针(`maxNodesPerRequest:1`)。不依赖整窗水位,也不必等
|
|
61
|
+
下一次请求;不改 sessionId、不碰最近 N 轮与系统前缀。
|
|
62
|
+
|
|
63
|
+
### 空闲折叠(模块三)
|
|
64
|
+
|
|
65
|
+
每来一条会话事件就起一个 **2 秒 debounce** 的定时器(`unref`):若
|
|
66
|
+
`context.ownership` 允许、`lastPressure` 是 **5 分钟内**的读数、比例 ≥
|
|
67
|
+
`smartPrune.threshold`(0.85)、没有 `foldBusy`、不在 backoff 内 → `smartPruneSession`
|
|
68
|
+
折 1 个节点,**折完的读数才是下一次判据**(A 批已保证 request 路径重测;空闲通道按
|
|
69
|
+
同一规则收敛)。单次释放 < 窗口 2% 立即写入 15 分钟 backoff,防折叠风暴。
|
|
70
|
+
|
|
71
|
+
可观测:`runtime.lastInlineFold` / `runtime.lastIdleFold`(含 `skipped` 原因)。
|
|
72
|
+
|
|
73
|
+
### 开关
|
|
74
|
+
|
|
75
|
+
`context.inlineFold.*`、`features.enableAutoHandoff` 进 `EDITABLE_CONFIG_KEYS`,
|
|
76
|
+
可在设置页/POST 改动而不必改 profile。
|
|
77
|
+
|
|
78
|
+
### Tests
|
|
79
|
+
|
|
80
|
+
`test/v2001.bfold.test.js` 4 例(关=不折、开=只折超阈值 tool/result、空闲门禁四态、
|
|
81
|
+
收敛用重测读数)。全套 **761/761**。
|
|
82
|
+
|
|
83
|
+
## [1.9.23] — 2026-12-02
|
|
84
|
+
|
|
85
|
+
**A 批:交接生命周期、降维骨架、安全隔离、最小释放守卫、两个总开关。**
|
|
86
|
+
|
|
87
|
+
### 1. 交接标记不再被"压力回落"清掉(60% 锯齿的根因)
|
|
88
|
+
|
|
89
|
+
旧逻辑:交接后压力低于 `handoffClearRatio`(0.5) 就清 marker → 折叠把 60% 压到 50% 以下 →
|
|
90
|
+
marker 被消费 → 又涨回 60% → 再交接。**锯齿中心正好 60%**。现在 marker 只在**新会话**
|
|
91
|
+
或 **`/memory resume`** 时被消费(`maintainHandoffMarker` 同会话一律 `held:true`)。
|
|
92
|
+
marker 持久、但**公告不再说谎**:`runtime.handoffRelief()` 用 5 分钟内的新读数判断,
|
|
93
|
+
压力真的回落时 prompt 不再注入 `[交接标记]`,marker 本身保留给 UI 与「续接」。
|
|
94
|
+
|
|
95
|
+
### 2. 交接降维(骨架只由代码拼装)
|
|
96
|
+
|
|
97
|
+
- `context.statePointer.enabled` 默认 **false**:不再往 prompt 注入 `fold=off` 之类的状态行;
|
|
98
|
+
- `_distillHandoffTail` 拼装前用 `stripFoldPointers()` 剔除所有 `[System: 此段包含…]`
|
|
99
|
+
指针——指针是账本,不是人说过的话;
|
|
100
|
+
- 骨架本来就是 100% 本地代码(`firstSentence`/`extractNames`/`extractTasks`),这一版把
|
|
101
|
+
"不喂指针"补上,`requestBudgetMs` 默认已是 **1500ms**,超时降级写入 degraded marker。
|
|
102
|
+
|
|
103
|
+
### 3. 安全隔离与按需恢复
|
|
104
|
+
|
|
105
|
+
- **Constraint Pinning**:`smartPruneSession` 遇到含 `[Hippocampus Policy]` 的消息直接跳过,
|
|
106
|
+
并打断微聚合 run(防止被 50 条微指针吞掉);
|
|
107
|
+
- 新工具 `memory_decompress(eventId)` → `runtime.decompress()`:从索引取回折叠块原文,只读。
|
|
108
|
+
|
|
109
|
+
### 4. 最小释放守卫
|
|
110
|
+
|
|
111
|
+
`foldReleaseGuard()`:单次折叠释放 < 窗口 **2%** 视为无效,写入 15 分钟 backoff,
|
|
112
|
+
期间不再重写 surface(治折叠风暴 + 省 CPU)。
|
|
113
|
+
|
|
114
|
+
### 5. 开关收敛
|
|
115
|
+
|
|
116
|
+
- 不新增 `enableInPlaceCompaction`,复用 `context.ownership`(`off` = 完全不碰 Context);
|
|
117
|
+
- 新增 `features.enableAutoHandoff`(默认 true,只拦自动路径:阈值/once-fold/hard-stop;
|
|
118
|
+
手动、命令与 fail-fast 守卫不受影响);
|
|
119
|
+
- 预置 `context.inlineFold { enabled:false, thresholdChars:8000 }`(B 批的事件驱动折叠用)。
|
|
120
|
+
|
|
121
|
+
### Tests
|
|
122
|
+
|
|
123
|
+
`test/v2000.govbatch.test.js` 7 例先红后绿;配套改:工具数 10→11(+decompress)、
|
|
124
|
+
状态行相关用例显式开启开关、标记生命周期用例改写为新契约。全套 **757/757**。
|
|
125
|
+
|
|
7
126
|
## [1.9.22] — 2026-12-02
|
|
8
127
|
|
|
9
128
|
**侧栏图标又变回按钮了:直接 `register` 在冷启动时会被丢掉。**
|
package/index.js
CHANGED
|
@@ -35,7 +35,7 @@ import { migrateDataDir } from './src/migration.js';
|
|
|
35
35
|
import { MigrationRunner } from './src/migrationRunner.js';
|
|
36
36
|
import { CronScheduler } from './src/scheduler.js';
|
|
37
37
|
import { asMemoryError, ErrorCodes, MemoryError } from './src/errors.js';
|
|
38
|
-
import { Memory, turnFromSessionEvent } from './src/memory.js';
|
|
38
|
+
import { HANDOFF_STATES, Memory, turnFromSessionEvent } from './src/memory.js';
|
|
39
39
|
import { composePrompt, renderActiveTask, renderPointers, renderStateLine } from './src/utils/promptLayout.js';
|
|
40
40
|
import { renderMemoryHints, selectRelevantTags } from './src/utils/memoryHints.js';
|
|
41
41
|
import { HintFeedbackStore } from './src/hintFeedback.js';
|
|
@@ -44,8 +44,10 @@ import { HostBridge } from './src/hostBridge.js';
|
|
|
44
44
|
import { isLowValley, nextLowValleyStart, windowInfo } from './src/priceWindow.js';
|
|
45
45
|
import { DreamTimer } from './src/dreamTimer.js';
|
|
46
46
|
import { probeCompression, resolveEngine } from './src/compression.js';
|
|
47
|
-
import { LIVE_COMPACT_DEFAULTS, liveCompactSession } from './src/context/liveCompact.js';
|
|
48
|
-
|
|
47
|
+
import { LIVE_COMPACT_DEFAULTS, contentChars, liveCompactSession } from './src/context/liveCompact.js';
|
|
48
|
+
// B 批: 事件驱动折叠 / 空闲折叠的两个纯决策。
|
|
49
|
+
import { PRESSURE_FRESH_MS, idleFoldPlan, shouldInlineFold } from './src/context/inlineFold.js';
|
|
50
|
+
import { FOLD_HARD_STOP_RATIO, foldBlocked, foldReleaseGuard, pickWindow, relievedDecision } from './src/context/windowGuard.js';
|
|
49
51
|
import { createHandoffCoordinator, FORCE, HANDOFF_STATUS } from './src/handoff/coordinator.js';
|
|
50
52
|
import { deliverNotice } from './src/handoff/notice.js';
|
|
51
53
|
import { decideOwnership, OWNERSHIP_MODE } from './src/context/ownership.js';
|
|
@@ -86,7 +88,7 @@ export { resolveConfig, DEFAULT_CONFIG };
|
|
|
86
88
|
* of letting a raw 404 reach the user.
|
|
87
89
|
*/
|
|
88
90
|
export const CAPABILITIES = Object.freeze({
|
|
89
|
-
version: '1.9.
|
|
91
|
+
version: '1.9.24',
|
|
90
92
|
spaces: true,
|
|
91
93
|
memories: true,
|
|
92
94
|
transferConsent: true,
|
|
@@ -935,12 +937,25 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
|
|
|
935
937
|
* - a different agent cannot consume someone else's injection silently: the new
|
|
936
938
|
* conversation arms its own pending entry on its first captured turn.
|
|
937
939
|
*/
|
|
938
|
-
runtime.coldStart = { pending: new Map(), injected: new Set(), lastSessionId: null };
|
|
940
|
+
runtime.coldStart = { pending: new Map(), injected: new Set(), lastSessionId: null, lastDelivery: null };
|
|
939
941
|
/** v1.6.5 `/memory mute`: emergency switch that silences [Memory Hints] only. */
|
|
940
942
|
runtime.hintsMuted = false;
|
|
941
943
|
const COLD_START_INJECTED_LIMIT = 64;
|
|
942
944
|
const COLD_START_PENDING_LIMIT = 8;
|
|
943
945
|
const COLD_START_PENDING_TTL_MS = 5 * 60_000;
|
|
946
|
+
/**
|
|
947
|
+
* C batch (2026-12-02): how long a marker that was already consumed stays adoptable
|
|
948
|
+
* by the conversation that did the consuming. The field failure was a consumption at
|
|
949
|
+
* 13:18:21 and an assembly in the same millisecond that carried no block; the window
|
|
950
|
+
* is generous because a host may consume at session start and assemble minutes later.
|
|
951
|
+
*/
|
|
952
|
+
const HANDOFF_DELIVERY_WINDOW_MS = 24 * 60 * 60_000;
|
|
953
|
+
/** C batch: an anchor run may summarise with a model; bound it so a hang cannot leak. */
|
|
954
|
+
const ANCHOR_TIMEOUT_MS = 120_000;
|
|
955
|
+
/** C batch: the last anchor attempt (stats/UI) and the one waiting for a turn boundary. */
|
|
956
|
+
runtime.lastAnchor = null;
|
|
957
|
+
runtime.pendingAnchor = null;
|
|
958
|
+
runtime.anchorBusy = false;
|
|
944
959
|
runtime.lastHintTags = [];
|
|
945
960
|
runtime.resetInjection = (sessionId = runtime.injection.sessionId) => {
|
|
946
961
|
runtime.injection = { sessionId, ids: new Set(), tags: new Set(), handoffAt: null };
|
|
@@ -1210,6 +1225,44 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
|
|
|
1210
1225
|
* Both off → empty string; the static anti-customer-service policy still ships in
|
|
1211
1226
|
* `memory:policy`, so the model never falls back to a canned opener.
|
|
1212
1227
|
*/
|
|
1228
|
+
/**
|
|
1229
|
+
* C batch (2026-12-02) — 逻辑接力: which marker may this conversation adopt?
|
|
1230
|
+
*
|
|
1231
|
+
* The old contract had two independent halves: `noteColdStart` armed a pending entry
|
|
1232
|
+
* from a session/agent event, and a session-id change CONSUMED the marker from the
|
|
1233
|
+
* engine. Neither half waited for the other, so a host that consumed first (or armed
|
|
1234
|
+
* with a different id — the field left `unknown` and a phantom session behind) produced
|
|
1235
|
+
* exactly this: the marker is gone, the new conversation starts blank.
|
|
1236
|
+
*
|
|
1237
|
+
* Adoption removes the ordering requirement entirely: if a marker exists that belongs
|
|
1238
|
+
* to ANOTHER conversation and this one has not received it, the assembly takes it.
|
|
1239
|
+
*
|
|
1240
|
+
* Never adopt:
|
|
1241
|
+
* - a marker with no summary event (nothing to hand over);
|
|
1242
|
+
* - a marker this conversation WROTE (A batch made it durable on purpose);
|
|
1243
|
+
* - a marker another conversation already received;
|
|
1244
|
+
* - a consumed marker that this conversation did not consume, or one consumed long
|
|
1245
|
+
* enough ago that replaying it would be noise.
|
|
1246
|
+
*
|
|
1247
|
+
* @returns {{key:string, epoch:string, source:string}|null}
|
|
1248
|
+
*/
|
|
1249
|
+
runtime.adoptableHandoff = (sessionId, handoff = memory.handoffState()) => {
|
|
1250
|
+
const summaryEventId = handoff?.summaryEventId;
|
|
1251
|
+
if (typeof summaryEventId !== 'string' || summaryEventId.length === 0) return null;
|
|
1252
|
+
if (!sessionId) return null;
|
|
1253
|
+
if (handoff.sessionId && handoff.sessionId === sessionId) return null;
|
|
1254
|
+
const epoch = `${handoff.at ?? 0}:${summaryEventId}`;
|
|
1255
|
+
const key = `${sessionId}|${epoch}`;
|
|
1256
|
+
if (runtime.coldStart.injected.has(key)) return null;
|
|
1257
|
+
if (handoff.active === true) return { key, epoch, source: 'adopted-active' };
|
|
1258
|
+
const consumedBy = String(handoff.consumedBy ?? '');
|
|
1259
|
+
if (consumedBy !== sessionId && !consumedBy.startsWith(`${sessionId}:`)) return null;
|
|
1260
|
+
const consumedAt = Number(handoff.consumedAt);
|
|
1261
|
+
const age = memory.clock.now() - consumedAt;
|
|
1262
|
+
if (!Number.isFinite(consumedAt) || age < 0 || age > HANDOFF_DELIVERY_WINDOW_MS) return null;
|
|
1263
|
+
return { key, epoch, source: 'adopted-consumed' };
|
|
1264
|
+
};
|
|
1265
|
+
|
|
1213
1266
|
runtime.coldStartText = ({ sessionId = null, agentId = null } = {}) => {
|
|
1214
1267
|
if (runtime.phase !== 'ready') return '';
|
|
1215
1268
|
runtime.pruneColdStartPendings();
|
|
@@ -1221,10 +1274,13 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
|
|
|
1221
1274
|
break;
|
|
1222
1275
|
}
|
|
1223
1276
|
}
|
|
1224
|
-
|
|
1277
|
+
// C batch: no armed entry is fine — the assembly itself is the delivery signal.
|
|
1278
|
+
const adopted = pending ? null : runtime.adoptableHandoff(sessionId);
|
|
1279
|
+
if (!pending && !adopted) return '';
|
|
1280
|
+
const deliveryKey = pending ? pending.key : adopted.key;
|
|
1225
1281
|
// Consume on the FIRST matching assembly, even when both switches are off: the
|
|
1226
1282
|
// entry must not linger and fire later on an unrelated conversation.
|
|
1227
|
-
pendings.delete(pending.key);
|
|
1283
|
+
if (pending) pendings.delete(pending.key);
|
|
1228
1284
|
const contextConfig = runtime.config?.context ?? {};
|
|
1229
1285
|
const wantSummary = contextConfig.coldStartInjectSummary === true;
|
|
1230
1286
|
const wantTurns = contextConfig.coldStartInjectRecentTurns === true;
|
|
@@ -1303,11 +1359,40 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
|
|
|
1303
1359
|
if (recent.length > 0) lines.push('[Previous Context Tail]', ...recent);
|
|
1304
1360
|
}
|
|
1305
1361
|
const text = lines.join('\n');
|
|
1306
|
-
runtime.coldStart.injected.add(
|
|
1362
|
+
runtime.coldStart.injected.add(deliveryKey);
|
|
1307
1363
|
if (runtime.coldStart.injected.size > COLD_START_INJECTED_LIMIT) {
|
|
1308
1364
|
const oldest = runtime.coldStart.injected.values().next().value;
|
|
1309
1365
|
runtime.coldStart.injected.delete(oldest);
|
|
1310
1366
|
}
|
|
1367
|
+
// C batch (逻辑接力): the marker is written off by the DELIVERY, not by a session
|
|
1368
|
+
// id change. A marker still ACTIVE here belongs to another conversation that never
|
|
1369
|
+
// received it — adopting it is also what retires it.
|
|
1370
|
+
if (handoff?.active === true && handoff.sessionId !== sessionId) {
|
|
1371
|
+
try {
|
|
1372
|
+
memory.clearHandoff({
|
|
1373
|
+
reason: 'delivered',
|
|
1374
|
+
consumedBy: sessionId,
|
|
1375
|
+
state: HANDOFF_STATES.DELIVERED,
|
|
1376
|
+
});
|
|
1377
|
+
} catch {
|
|
1378
|
+
/* a marker we cannot retire is better than a prompt we cannot assemble */
|
|
1379
|
+
}
|
|
1380
|
+
} else if (adopted && handoff?.state !== HANDOFF_STATES.DELIVERED) {
|
|
1381
|
+
// Adopted from an already-consumed marker: upgrade the record so /stats stops
|
|
1382
|
+
// reporting "consumed" for a relay that has just been delivered.
|
|
1383
|
+
try {
|
|
1384
|
+
memory.markHandoffDelivered({ consumedBy: sessionId });
|
|
1385
|
+
} catch {
|
|
1386
|
+
/* observability only */
|
|
1387
|
+
}
|
|
1388
|
+
}
|
|
1389
|
+
runtime.coldStart.lastDelivery = {
|
|
1390
|
+
sessionId,
|
|
1391
|
+
source: pending?.source ?? adopted?.source ?? 'session',
|
|
1392
|
+
summaryEventId: handoff?.summaryEventId ?? null,
|
|
1393
|
+
at: memory.clock.now(),
|
|
1394
|
+
chars: text.length,
|
|
1395
|
+
};
|
|
1311
1396
|
return text;
|
|
1312
1397
|
} catch {
|
|
1313
1398
|
return '';
|
|
@@ -1407,9 +1492,14 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
|
|
|
1407
1492
|
if (block.kind !== 'briefing') runtime.injection.ids.add(block.id);
|
|
1408
1493
|
}
|
|
1409
1494
|
|
|
1410
|
-
//
|
|
1411
|
-
//
|
|
1412
|
-
|
|
1495
|
+
// A batch (2026-12-02): the MARKER is durable, the ANNOUNCEMENT is not.
|
|
1496
|
+
//
|
|
1497
|
+
// The marker now survives relief on purpose (that is what kills the 60% sawtooth),
|
|
1498
|
+
// but the prompt must still tell the truth: if a fresh host measurement says the
|
|
1499
|
+
// pressure is gone, the "context is near the limit" line is a lie and is withheld.
|
|
1500
|
+
// The marker itself keeps `nextSessionRequired` for the UI and the resume button.
|
|
1501
|
+
const relief = runtime.handoffRelief();
|
|
1502
|
+
const marker = handoff.active && !relief.suppressed
|
|
1413
1503
|
? [
|
|
1414
1504
|
'',
|
|
1415
1505
|
'[交接标记] 上下文已接近原生窗口上限,末尾摘要已存为 L1.5。',
|
|
@@ -1624,7 +1714,22 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
|
|
|
1624
1714
|
|
|
1625
1715
|
const pruneThreshold = Number.isFinite(pruneConfig.threshold) ? pruneConfig.threshold : 0.85;
|
|
1626
1716
|
const pruneAllowed = foldOwned && foldGate.allowed && (state.projectedRatio >= pruneThreshold || onceFoldDue);
|
|
1627
|
-
|
|
1717
|
+
// A batch (2026-12-02): MINIMUM RELEASE GUARD.
|
|
1718
|
+
//
|
|
1719
|
+
// A pass that frees almost nothing still rewrites the surface and re-measures — the
|
|
1720
|
+
// "fold storm" of billion-context #2671. After a useless pass the gate backs off for
|
|
1721
|
+
// a while instead of retrying on every request.
|
|
1722
|
+
const foldBackoff = runtime.foldBackoff ?? null;
|
|
1723
|
+
const foldBackoffActive = foldBackoff !== null && Number(foldBackoff.until) > memory.clock.now();
|
|
1724
|
+
if (pruneConfig.enabled !== false && session && pruneAllowed && foldBackoffActive) {
|
|
1725
|
+
runtime.lastSmartPrune = {
|
|
1726
|
+
source: 'hippocampus',
|
|
1727
|
+
at: memory.clock.now(),
|
|
1728
|
+
skipped: 'backoff',
|
|
1729
|
+
reason: foldBackoff.reason ?? 'below-min-release',
|
|
1730
|
+
until: foldBackoff.until,
|
|
1731
|
+
};
|
|
1732
|
+
} else if (pruneConfig.enabled !== false && session && pruneAllowed) {
|
|
1628
1733
|
try {
|
|
1629
1734
|
runtime.lastSmartPrune = {
|
|
1630
1735
|
source: 'hippocampus',
|
|
@@ -1668,6 +1773,19 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
|
|
|
1668
1773
|
reservedTokens: hostProbes.reservedTokens ?? undefined,
|
|
1669
1774
|
});
|
|
1670
1775
|
runtime.lastSmartPrune.ratioAfter = state.projectedRatio;
|
|
1776
|
+
// Minimum release guard: tokens freed this pass, against the real window.
|
|
1777
|
+
const savedTokens = Math.round(Math.max(0, (runtime.lastSmartPrune.charsBefore ?? 0) - (runtime.lastSmartPrune.charsAfter ?? 0)) / 4);
|
|
1778
|
+
const release = foldReleaseGuard({ savedTokens, window: state.nativeTokenLimit });
|
|
1779
|
+
runtime.lastSmartPrune.savedTokens = savedTokens;
|
|
1780
|
+
runtime.lastSmartPrune.minReleaseTokens = release.minTokens;
|
|
1781
|
+
if (!release.allowed) {
|
|
1782
|
+
// Park the folder for 15 minutes instead of rewriting the surface again on
|
|
1783
|
+
// the very next request.
|
|
1784
|
+
runtime.foldBackoff = { until: memory.clock.now() + 15 * 60_000, reason: release.reason, savedTokens };
|
|
1785
|
+
runtime.lastSmartPrune.skippedNext = release.reason;
|
|
1786
|
+
} else if (runtime.foldBackoff) {
|
|
1787
|
+
runtime.foldBackoff = null;
|
|
1788
|
+
}
|
|
1671
1789
|
}
|
|
1672
1790
|
} catch (error) {
|
|
1673
1791
|
runtime.logger?.warn?.(`hippocampus: smart prune failed: ${asMemoryError(error).code}`);
|
|
@@ -2150,6 +2268,8 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
|
|
|
2150
2268
|
// v1.6.3: cold-start injection observability. Without it the only way to tell
|
|
2151
2269
|
// "armed but never assembled" from "already injected" is to read the prompt.
|
|
2152
2270
|
coldStart: runtime.coldStartView?.() ?? null,
|
|
2271
|
+
// C 批: the anchor (host compaction) attempt that last ran, with its skip reason.
|
|
2272
|
+
anchor: runtime.anchorView?.() ?? null,
|
|
2153
2273
|
panel: {
|
|
2154
2274
|
...status.panel,
|
|
2155
2275
|
// v1.6.7 (M6): the panel's `spaces` block is what the UI renders, so the
|
|
@@ -2243,6 +2363,9 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
|
|
|
2243
2363
|
})),
|
|
2244
2364
|
injected: runtime.coldStart.injected.size,
|
|
2245
2365
|
lastSessionId: runtime.coldStart.lastSessionId,
|
|
2366
|
+
// C batch: the last relay that actually landed, so "交接完成但没人收到" is visible
|
|
2367
|
+
// in /stats instead of having to be inferred from an empty prompt.
|
|
2368
|
+
lastDelivery: runtime.coldStart.lastDelivery ?? null,
|
|
2246
2369
|
});
|
|
2247
2370
|
|
|
2248
2371
|
/**
|
|
@@ -2395,10 +2518,183 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
|
|
|
2395
2518
|
/** v1.5.6: handoff observability (the client shows the marker + summary link). */ /** v1.7.1: the hint feedback loop (tracked / silenced counts and the silenced tags). */
|
|
2396
2519
|
runtime.hintFeedbackView = () => runtime.hintFeedbackFacade().status();
|
|
2397
2520
|
|
|
2521
|
+
/**
|
|
2522
|
+
* A batch (2026-12-02): `features.enableAutoHandoff` is the ONE switch for automatic
|
|
2523
|
+
* handing over. Manual paths (`/memory handoff`, `resume`) and the fail-fast guard are
|
|
2524
|
+
* NOT automatic — a person asking, or a request that provably cannot fit, keeps
|
|
2525
|
+
* working with the switch off.
|
|
2526
|
+
*/
|
|
2527
|
+
const handoffRequestRaw = runtime.handoff.request.bind(runtime.handoff);
|
|
2528
|
+
runtime.handoff.request = (input = {}) => {
|
|
2529
|
+
const source = String(input?.source ?? 'threshold');
|
|
2530
|
+
const manual = source === 'command' || source === 'manual' || source === 'fail-fast';
|
|
2531
|
+
if (!manual && runtime.config?.features?.enableAutoHandoff === false) {
|
|
2532
|
+
return Promise.resolve({ status: 'skipped', reason: 'auto-handoff-disabled', result: null });
|
|
2533
|
+
}
|
|
2534
|
+
return handoffRequestRaw(input).then((outcome) => {
|
|
2535
|
+
// C 批: a handoff that PRODUCED a live marker is exactly when the anchor becomes
|
|
2536
|
+
// meaningful — but compaction wants an idle agent, so it is queued for the next
|
|
2537
|
+
// turn boundary instead of running inside this request.
|
|
2538
|
+
try {
|
|
2539
|
+
const marker = memory.handoffState();
|
|
2540
|
+
const finished = outcome?.status === 'done' || outcome?.status === 'degraded';
|
|
2541
|
+
if (finished && marker?.active === true) {
|
|
2542
|
+
// C 批: with `context.anchor.enabled` off (the default) NOTHING is queued at
|
|
2543
|
+
// all — the ordinary handoff path stays byte-identical to v1.9.24.
|
|
2544
|
+
if (runtime.config?.context?.anchor?.enabled === true) {
|
|
2545
|
+
runtime.pendingAnchor = { at: memory.clock.now(), source };
|
|
2546
|
+
}
|
|
2547
|
+
}
|
|
2548
|
+
} catch {
|
|
2549
|
+
/* opportunistic: the handoff itself already succeeded */
|
|
2550
|
+
}
|
|
2551
|
+
return outcome;
|
|
2552
|
+
});
|
|
2553
|
+
};
|
|
2554
|
+
|
|
2555
|
+
/**
|
|
2556
|
+
* A batch (2026-12-02): `decompress(eventId)` — the read-only way back into a fold.
|
|
2557
|
+
*
|
|
2558
|
+
* A folded turn keeps an id in its pointer (`ev_…` / `turn_<seq>_<role>`). This
|
|
2559
|
+
* resolves that id in the index and returns the original text. No prompt assembly,
|
|
2560
|
+
* no bookkeeping, no surface change: a tool call must never disturb the session.
|
|
2561
|
+
*/
|
|
2562
|
+
runtime.decompress = async ({ eventId } = {}) => {
|
|
2563
|
+
const id = typeof eventId === 'string' ? eventId.trim() : '';
|
|
2564
|
+
if (!id) return { ok: false, reason: 'missing-event-id' };
|
|
2565
|
+
if (runtime.phase !== 'ready') return { ok: false, reason: runtime.phase };
|
|
2566
|
+
try {
|
|
2567
|
+
const events = memory.indexManager.snapshot()?.events ?? [];
|
|
2568
|
+
const event = events.find((entry) => entry?.eventId === id);
|
|
2569
|
+
if (!event || typeof event.content !== 'string') return { ok: false, reason: 'not-found', eventId: id };
|
|
2570
|
+
return {
|
|
2571
|
+
ok: true,
|
|
2572
|
+
eventId: id,
|
|
2573
|
+
tags: (event.tags ?? []).map((tag) => tag.tag ?? tag),
|
|
2574
|
+
text: event.content,
|
|
2575
|
+
};
|
|
2576
|
+
} catch (error) {
|
|
2577
|
+
return { ok: false, reason: asMemoryError(error).code, eventId: id };
|
|
2578
|
+
}
|
|
2579
|
+
};
|
|
2580
|
+
|
|
2581
|
+
/**
|
|
2582
|
+
* C 批 (2026-12-02) —— 模块五 v2「逻辑接力」的**锚点**。
|
|
2583
|
+
*
|
|
2584
|
+
* DSH 的会话是 append-only,插件不能、也不应该"清空并重写 transcript"。官方提供的
|
|
2585
|
+
* 接缝是 `ctx.compaction`(可选服务):`compactNow()` 会把一段连续的 surface 节点
|
|
2586
|
+
* 折叠成**一个摘要节点**,旧区间只是被 shadowed(日志还在,投影变了),sessionId 不变。
|
|
2587
|
+
* 这正是定调里说的"将历史轮次折叠成一个锚点"。
|
|
2588
|
+
*
|
|
2589
|
+
* 分工:宿主负责"怎么折"(它拥有策略、摘要模型与写入);本插件只做策略层——
|
|
2590
|
+
* 什么时候折、折完把什么骨架放在锚点之后。拿不到服务就如实记录 `service-unavailable`,
|
|
2591
|
+
* 退回"新会话 + 骨架投递"的老路径,绝不自己动会话日志。
|
|
2592
|
+
*/
|
|
2593
|
+
runtime.compactionService = () => {
|
|
2594
|
+
try {
|
|
2595
|
+
const service = typeof ctx?.get === 'function' ? ctx.get('compaction') : null;
|
|
2596
|
+
if (!service || typeof service.compactNow !== 'function') return null;
|
|
2597
|
+
return service;
|
|
2598
|
+
} catch {
|
|
2599
|
+
return null;
|
|
2600
|
+
}
|
|
2601
|
+
};
|
|
2602
|
+
|
|
2603
|
+
runtime.anchorView = () => runtime.lastAnchor ?? null;
|
|
2604
|
+
|
|
2605
|
+
runtime.requestAnchor = async ({ agent = null, session = null, signal = null, source = 'handoff' } = {}) => {
|
|
2606
|
+
const target = session ?? agent?.session ?? null;
|
|
2607
|
+
const sessionId = typeof target?.id === 'string' ? target.id : (memory.sessionUsage()?.sessionId ?? null);
|
|
2608
|
+
const base = { at: memory.clock.now(), source, sessionId };
|
|
2609
|
+
const done = (record) => {
|
|
2610
|
+
runtime.lastAnchor = { ...base, ...record };
|
|
2611
|
+
return runtime.lastAnchor;
|
|
2612
|
+
};
|
|
2613
|
+
if (runtime.config?.context?.anchor?.enabled !== true) {
|
|
2614
|
+
return done({ status: 'skipped', reason: 'anchor-disabled' });
|
|
2615
|
+
}
|
|
2616
|
+
if (!target || typeof target !== 'object') return done({ status: 'skipped', reason: 'no-session' });
|
|
2617
|
+
const compaction = runtime.compactionService();
|
|
2618
|
+
if (!compaction) return done({ status: 'skipped', reason: 'service-unavailable' });
|
|
2619
|
+
const controller = new AbortController();
|
|
2620
|
+
const abort = (reason) => controller.abort(reason);
|
|
2621
|
+
const timer = setTimeout(() => abort(new Error('anchor timeout')), ANCHOR_TIMEOUT_MS);
|
|
2622
|
+
if (typeof timer.unref === 'function') timer.unref();
|
|
2623
|
+
const relay = signal && typeof signal.addEventListener === 'function'
|
|
2624
|
+
? () => abort(new Error('anchor cancelled'))
|
|
2625
|
+
: null;
|
|
2626
|
+
if (relay) signal.addEventListener('abort', relay, { once: true });
|
|
2627
|
+
try {
|
|
2628
|
+
const result = await compaction.compactNow(
|
|
2629
|
+
{
|
|
2630
|
+
session: target,
|
|
2631
|
+
options: {},
|
|
2632
|
+
// The contract requires an idle-task runner; we have no maintenance to run,
|
|
2633
|
+
// so it must still forward the signal and resolve with the task's value.
|
|
2634
|
+
runMaintenance: (task) => task(controller.signal),
|
|
2635
|
+
},
|
|
2636
|
+
controller.signal,
|
|
2637
|
+
);
|
|
2638
|
+
if (!result) return done({ status: 'skipped', reason: 'nothing-to-compact' });
|
|
2639
|
+
// The skeleton goes AFTER the anchor: compactNow replaced the span with one node,
|
|
2640
|
+
// so the next prompt starts clean and this is the only thing that still knows
|
|
2641
|
+
// what the person was doing.
|
|
2642
|
+
let armed = null;
|
|
2643
|
+
try {
|
|
2644
|
+
armed = runtime.armColdStartNow({ sessionId, source: 'anchor-post-compaction' });
|
|
2645
|
+
} catch {
|
|
2646
|
+
/* the anchor standing on its own is still a win */
|
|
2647
|
+
}
|
|
2648
|
+
return done({
|
|
2649
|
+
status: 'ok',
|
|
2650
|
+
compactionId: result.compactionId ?? null,
|
|
2651
|
+
summarySeq: result.summarySeq ?? null,
|
|
2652
|
+
shadowedRange: result.shadowedRange ?? null,
|
|
2653
|
+
shadowedTokenCount: result.shadowedTokenCount ?? null,
|
|
2654
|
+
skeletonArmed: armed !== null,
|
|
2655
|
+
});
|
|
2656
|
+
} catch (error) {
|
|
2657
|
+
// The host's ManualCompactionError carries its OWN code (busy / cancelled /
|
|
2658
|
+
// changed-span). asMemoryError() would flatten it into MEM_E_IO and throw away
|
|
2659
|
+
// the only thing an operator can act on, so the original code wins.
|
|
2660
|
+
const rawCode = typeof error?.code === 'string' && error.code.length > 0 ? error.code : null;
|
|
2661
|
+
return done({
|
|
2662
|
+
status: 'failed',
|
|
2663
|
+
reason: rawCode ?? asMemoryError(error).code ?? 'MEM_E_ANCHOR_FAILED',
|
|
2664
|
+
message: String(error?.message ?? error).slice(0, 200),
|
|
2665
|
+
});
|
|
2666
|
+
} finally {
|
|
2667
|
+
clearTimeout(timer);
|
|
2668
|
+
if (relay) signal.removeEventListener('abort', relay);
|
|
2669
|
+
}
|
|
2670
|
+
};
|
|
2671
|
+
|
|
2672
|
+
/**
|
|
2673
|
+
* A batch (2026-12-02): the marker is durable, its ANNOUNCEMENT is not.
|
|
2674
|
+
*
|
|
2675
|
+
* The lifetime rule keeps the marker until a new session consumes it (that is what
|
|
2676
|
+
* kills the 60% sawtooth). The prompt, however, must not keep saying "context is near
|
|
2677
|
+
* the limit" after the host reports 12% — so a FRESH measurement that shows relief
|
|
2678
|
+
* suppresses the sentence while leaving the marker itself intact.
|
|
2679
|
+
*/
|
|
2680
|
+
runtime.handoffRelief = () => {
|
|
2681
|
+
const marker = memory.handoffState();
|
|
2682
|
+
if (!marker || marker.active !== true) return { active: false, suppressed: false, reason: 'inactive' };
|
|
2683
|
+
const pressure = runtime.lastPressure;
|
|
2684
|
+
if (!pressure || !Number.isFinite(pressure.ratio)) return { active: true, suppressed: false, reason: 'no-reading' };
|
|
2685
|
+
const at = Number(pressure.at ?? 0);
|
|
2686
|
+
if (!(at > 0) || memory.clock.now() - at > 5 * 60_000) return { active: true, suppressed: false, reason: 'stale-reading' };
|
|
2687
|
+
const decision = relievedDecision({
|
|
2688
|
+
markerRatio: marker.ratio ?? null,
|
|
2689
|
+
projectedRatio: pressure.ratio,
|
|
2690
|
+
threshold: runtime.config?.context?.handoffClearRatio ?? 0.5,
|
|
2691
|
+
});
|
|
2692
|
+
return { active: true, suppressed: decision.relieved === true, ratio: pressure.ratio, reason: decision.reason };
|
|
2693
|
+
};
|
|
2694
|
+
|
|
2398
2695
|
runtime.handoffView = () => {
|
|
2399
2696
|
const handoff = memory.handoffState();
|
|
2400
|
-
const summaryEventId = handoff?.summaryEventId ?? null;
|
|
2401
|
-
return {
|
|
2697
|
+
const summaryEventId = handoff?.summaryEventId ?? null; return {
|
|
2402
2698
|
active: handoff?.active === true,
|
|
2403
2699
|
at: handoff?.at ?? null,
|
|
2404
2700
|
summaryEventId,
|
|
@@ -3305,8 +3601,133 @@ export async function apply(ctx, rawConfig = {}) {
|
|
|
3305
3601
|
// `dsh-session` publishes `session/event` as (session, event). Subscribing at
|
|
3306
3602
|
// the root context is what reaches sessions created by the agent's fiber; the
|
|
3307
3603
|
// raw store's own gating/budgets still decide what lands on disk.
|
|
3604
|
+
// ---- B batch (2026-12-02): 事件驱动折叠 + 空闲折叠 ----------------------
|
|
3605
|
+
//
|
|
3606
|
+
// 折叠不再只活在请求路径上:
|
|
3607
|
+
// - 一条 tool/result 超过 context.inlineFold.thresholdChars(默认 8000,默认关)
|
|
3608
|
+
// 就在会话事件流里立即原地折叠——不看整窗水位,也不必等下一次请求;
|
|
3609
|
+
// - 没有新请求时,靠同一条事件流把水位收敛回目标,避免"闲置会话永远卡在超额"。
|
|
3610
|
+
// 两条通道都受 `context.ownership` 与 backoff 约束,绝不改 sessionId。
|
|
3611
|
+
runtime.lastInlineFold = null;
|
|
3612
|
+
runtime.lastIdleFold = null;
|
|
3613
|
+
runtime.foldBusy = false;
|
|
3614
|
+
let idleFoldTimer = null;
|
|
3615
|
+
const inlineFoldConfig = () => runtime.config?.context?.inlineFold ?? {};
|
|
3616
|
+
const freshPressure = () => {
|
|
3617
|
+
const pressure = runtime.lastPressure;
|
|
3618
|
+
if (!pressure || !Number.isFinite(pressure.ratio)) return { fresh: false, ratio: null };
|
|
3619
|
+
const at = Number(pressure.at ?? 0);
|
|
3620
|
+
return { fresh: at > 0 && memory.clock.now() - at <= PRESSURE_FRESH_MS, ratio: pressure.ratio };
|
|
3621
|
+
};
|
|
3622
|
+
|
|
3623
|
+
const maybeInlineFold = (session, event) => {
|
|
3624
|
+
const config = inlineFoldConfig();
|
|
3625
|
+
if (config.enabled !== true) return;
|
|
3626
|
+
const message = event?.data?.message ?? null;
|
|
3627
|
+
const chars = message ? contentChars(message.content) : 0;
|
|
3628
|
+
const decision = shouldInlineFold({
|
|
3629
|
+
enabled: true,
|
|
3630
|
+
type: event?.type ?? null,
|
|
3631
|
+
chars,
|
|
3632
|
+
thresholdChars: config.thresholdChars,
|
|
3633
|
+
});
|
|
3634
|
+
if (!decision.fold) return;
|
|
3635
|
+
// setImmediate: the capture listener must return immediately; folding one node
|
|
3636
|
+
// rewrites a surface and must not run inside the event dispatch.
|
|
3637
|
+
setImmediate(() => {
|
|
3638
|
+
try {
|
|
3639
|
+
const report = liveCompactSession(session, {
|
|
3640
|
+
thresholdChars: decision.thresholdChars,
|
|
3641
|
+
headChars: LIVE_COMPACT_DEFAULTS.headChars,
|
|
3642
|
+
tailChars: LIVE_COMPACT_DEFAULTS.tailChars,
|
|
3643
|
+
maxNodesPerRequest: 1,
|
|
3644
|
+
logger: runtime.logger,
|
|
3645
|
+
});
|
|
3646
|
+
runtime.lastInlineFold = { at: memory.clock.now(), source: 'event', ...report };
|
|
3647
|
+
} catch (error) {
|
|
3648
|
+
runtime.logger?.warn?.(`hippocampus: inline fold failed: ${asMemoryError(error).code}`);
|
|
3649
|
+
}
|
|
3650
|
+
});
|
|
3651
|
+
};
|
|
3652
|
+
|
|
3653
|
+
const runIdleFold = (session) => {
|
|
3654
|
+
if (runtime.phase !== 'ready' || !session) return;
|
|
3655
|
+
const ownership = typeof runtime.ownershipOf === 'function' ? runtime.ownershipOf() : null;
|
|
3656
|
+
if (ownership && ownership.smartPrune !== 'on') {
|
|
3657
|
+
runtime.lastIdleFold = { at: memory.clock.now(), skipped: 'yielded', reason: ownership.reason };
|
|
3658
|
+
return;
|
|
3659
|
+
}
|
|
3660
|
+
const { fresh, ratio } = freshPressure();
|
|
3661
|
+
const decision = idleFoldPlan({
|
|
3662
|
+
ratio,
|
|
3663
|
+
threshold: runtime.config?.context?.smartPrune?.threshold ?? 0.85,
|
|
3664
|
+
backoffUntil: runtime.foldBackoff?.until ?? null,
|
|
3665
|
+
now: memory.clock.now(),
|
|
3666
|
+
busy: runtime.foldBusy === true,
|
|
3667
|
+
pressureFresh: fresh,
|
|
3668
|
+
});
|
|
3669
|
+
if (!decision.fold) {
|
|
3670
|
+
runtime.lastIdleFold = { at: memory.clock.now(), skipped: decision.reason };
|
|
3671
|
+
return;
|
|
3672
|
+
}
|
|
3673
|
+
runtime.foldBusy = true;
|
|
3674
|
+
try {
|
|
3675
|
+
const report = smartPruneSession(session, {
|
|
3676
|
+
keepRecentTurns: runtime.config?.context?.smartPrune?.keepRecentTurns ?? 3,
|
|
3677
|
+
minChars: runtime.config?.context?.smartPrune?.minChars ?? FOLD_MIN_CHARS,
|
|
3678
|
+
maxNodes: 1,
|
|
3679
|
+
logger: runtime.logger,
|
|
3680
|
+
});
|
|
3681
|
+
const savedTokens = Math.round(Math.max(0, (report.charsBefore ?? 0) - (report.charsAfter ?? 0)) / 4);
|
|
3682
|
+
const release = foldReleaseGuard({ savedTokens, window: runtime.lastPressure?.window ?? null });
|
|
3683
|
+
if (!release.allowed) {
|
|
3684
|
+
runtime.foldBackoff = { until: memory.clock.now() + 15 * 60_000, reason: release.reason, savedTokens };
|
|
3685
|
+
}
|
|
3686
|
+
runtime.lastIdleFold = {
|
|
3687
|
+
at: memory.clock.now(),
|
|
3688
|
+
source: 'idle',
|
|
3689
|
+
savedTokens,
|
|
3690
|
+
release: release.reason,
|
|
3691
|
+
...report,
|
|
3692
|
+
};
|
|
3693
|
+
} catch (error) {
|
|
3694
|
+
runtime.logger?.warn?.(`hippocampus: idle fold failed: ${asMemoryError(error).code}`);
|
|
3695
|
+
} finally {
|
|
3696
|
+
runtime.foldBusy = false;
|
|
3697
|
+
}
|
|
3698
|
+
};
|
|
3699
|
+
|
|
3700
|
+
const scheduleIdleFold = (session) => {
|
|
3701
|
+
if (idleFoldTimer) return;
|
|
3702
|
+
// 2s debounce: a request usually follows a turn, and folding right before it
|
|
3703
|
+
// would compete with the request-path fold for the same surface.
|
|
3704
|
+
idleFoldTimer = setTimeout(() => {
|
|
3705
|
+
idleFoldTimer = null;
|
|
3706
|
+
try {
|
|
3707
|
+
runIdleFold(session);
|
|
3708
|
+
} catch {
|
|
3709
|
+
/* folding must never break the event stream */
|
|
3710
|
+
}
|
|
3711
|
+
}, 2000);
|
|
3712
|
+
if (typeof idleFoldTimer.unref === 'function') idleFoldTimer.unref();
|
|
3713
|
+
};
|
|
3714
|
+
|
|
3308
3715
|
const captureListener = (session, event) => {
|
|
3309
3716
|
if (!runtime.memory || runtime.phase !== 'ready') return;
|
|
3717
|
+
// C 批: the anchor runs at a turn BOUNDARY. `ctx.compaction.compactNow` is documented
|
|
3718
|
+
// for an IDLE agent, so running it inside the handoff request would either be
|
|
3719
|
+
// refused as busy or fight the turn that is still streaming.
|
|
3720
|
+
if (event?.type === 'turn/end' && runtime.pendingAnchor && !runtime.anchorBusy) {
|
|
3721
|
+
const pending = runtime.pendingAnchor;
|
|
3722
|
+
runtime.pendingAnchor = null;
|
|
3723
|
+
runtime.anchorBusy = true;
|
|
3724
|
+
runtime
|
|
3725
|
+
.requestAnchor({ session, source: pending.source ?? 'handoff' })
|
|
3726
|
+
.catch(() => null)
|
|
3727
|
+
.finally(() => {
|
|
3728
|
+
runtime.anchorBusy = false;
|
|
3729
|
+
});
|
|
3730
|
+
}
|
|
3310
3731
|
// v1.6.3: a NEW conversation id is the reliable "the user started a conversation"
|
|
3311
3732
|
// signal on every host (a user-created and a resumed session both arrive here).
|
|
3312
3733
|
// Arming on the first captured turn also beats any sibling agent assembling a
|
|
@@ -3332,6 +3753,12 @@ export async function apply(ctx, rawConfig = {}) {
|
|
|
3332
3753
|
} catch {
|
|
3333
3754
|
/* hint relevance must never affect capture */
|
|
3334
3755
|
}
|
|
3756
|
+
try {
|
|
3757
|
+
maybeInlineFold(session, event);
|
|
3758
|
+
scheduleIdleFold(session);
|
|
3759
|
+
} catch (error) {
|
|
3760
|
+
/* folding must never break capture */
|
|
3761
|
+
}
|
|
3335
3762
|
runtime.memory
|
|
3336
3763
|
.captureSessionEvent(session, event)
|
|
3337
3764
|
.then((result) => {
|
|
@@ -3579,6 +4006,27 @@ export async function apply(ctx, rawConfig = {}) {
|
|
|
3579
4006
|
}),
|
|
3580
4007
|
);
|
|
3581
4008
|
|
|
4009
|
+
// A batch (2026-12-02): the model's way BACK into a fold (pi-fold's `expand`).
|
|
4010
|
+
// Read-only: it resolves the id a fold pointer names and returns the original text.
|
|
4011
|
+
register(
|
|
4012
|
+
defineTool({
|
|
4013
|
+
name: `${config.toolPrefix}_decompress`,
|
|
4014
|
+
description:
|
|
4015
|
+
'Expand ONE folded context block: pass the eventId a fold pointer names and get the original text back. ' +
|
|
4016
|
+
'Read-only — assembles no prompt and never touches the session surface.',
|
|
4017
|
+
parameters: {
|
|
4018
|
+
eventId: { type: 'string', description: 'The id named by the fold pointer (ev_… or turn_<seq>_<role>)', required: true },
|
|
4019
|
+
},
|
|
4020
|
+
output: { schema: { type: 'string' }, render: (_args, value) => toolResult(value) },
|
|
4021
|
+
execute: async (args = {}) =>
|
|
4022
|
+
stillStarting('decompress', async () => {
|
|
4023
|
+
runtime.touch();
|
|
4024
|
+
const result = await runtime.decompress({ eventId: args.eventId });
|
|
4025
|
+
return JSON.stringify(result);
|
|
4026
|
+
}),
|
|
4027
|
+
}),
|
|
4028
|
+
);
|
|
4029
|
+
|
|
3582
4030
|
register(
|
|
3583
4031
|
defineTool({
|
|
3584
4032
|
name: `${config.toolPrefix}_capture`,
|
|
@@ -4196,8 +4644,22 @@ export async function apply(ctx, rawConfig = {}) {
|
|
|
4196
4644
|
// Re-arm the cold-start injection for THIS conversation even if it was already
|
|
4197
4645
|
// delivered once — an explicit command outranks the once-per-epoch dedupe.
|
|
4198
4646
|
runtime.armColdStartNow({ sessionId, agentId, source: 'command-resume' });
|
|
4647
|
+
// A batch (2026-12-02): an explicit `/memory resume` is one of the two events
|
|
4648
|
+
// allowed to consume the marker (the other is a new session). Consuming it here
|
|
4649
|
+
// means "I have taken delivery", so the 60% announcement stops without waiting
|
|
4650
|
+
// for pressure to fall.
|
|
4651
|
+
let consumed = false;
|
|
4652
|
+
try {
|
|
4653
|
+
const marker = runtime.memory?.handoffState?.();
|
|
4654
|
+
if (marker?.active === true) {
|
|
4655
|
+
runtime.memory.clearHandoff({ reason: 'command-resume', consumedBy: sessionId ?? 'command' });
|
|
4656
|
+
consumed = true;
|
|
4657
|
+
}
|
|
4658
|
+
} catch {
|
|
4659
|
+
/* a marker that cannot be consumed is reported by the panel, never fatal */
|
|
4660
|
+
}
|
|
4199
4661
|
const head = summary.found
|
|
4200
|
-
? `已注入上一次交接摘要(${summary.summaryEventId}${summary.active ? ',交接标记仍 active' : ''})。`
|
|
4662
|
+
? `已注入上一次交接摘要(${summary.summaryEventId}${consumed ? ',交接标记已消费' : summary.active ? ',交接标记仍 active' : ''})。`
|
|
4201
4663
|
: `交接摘要事件 ${summary.summaryEventId} 暂不在索引中(可能尚未重建),已请求重新注入。`;
|
|
4202
4664
|
const tail = summary.tailTurns?.length ? `\n附带上一次对话最后 ${summary.tailTurns.length} 轮原话。` : '';
|
|
4203
4665
|
return ok(head + tail);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-layers-hippocampus",
|
|
3
|
-
"version": "1.9.
|
|
3
|
+
"version": "1.9.25",
|
|
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
|
@@ -57,6 +57,7 @@ export const TOOL_SUFFIXES = Object.freeze([
|
|
|
57
57
|
'remember',
|
|
58
58
|
'checkpoint',
|
|
59
59
|
'recall',
|
|
60
|
+
'decompress',
|
|
60
61
|
'capture',
|
|
61
62
|
'bulk_ingest',
|
|
62
63
|
'reinforce',
|
|
@@ -260,7 +261,20 @@ export const DEFAULT_CONFIG = Object.freeze({
|
|
|
260
261
|
hintsIdleSilenceAfter: 8,
|
|
261
262
|
// The `[Task State]` line (task mode only). `maxChars` is a hard cap: this line
|
|
262
263
|
// sits in the volatile tail and must never grow into a status dump.
|
|
263
|
-
statePointer: { enabled:
|
|
264
|
+
statePointer: { enabled: false, maxChars: 300 },
|
|
265
|
+
// A 批 (2026-12-02): event-driven inline folding. PARKED on purpose: the engine
|
|
266
|
+
// wiring lands first, `enabled:false` keeps every existing conversation exactly as
|
|
267
|
+
// it behaves today until an operator opts in.
|
|
268
|
+
inlineFold: { enabled: false, thresholdChars: 8000 },
|
|
269
|
+
// C 批 (2026-12-02) —— 模块五 v2「逻辑接力」的锚点。
|
|
270
|
+
//
|
|
271
|
+
// DSH 把 compaction 暴露成可选的 Capability Seam(`ctx.get('compaction')`,
|
|
272
|
+
// `compactNow/compactIfNeeded/compactRegion`):一次成功的 compaction 会把选中的
|
|
273
|
+
// surface 区间替换成 ONE summary node,日志仍然 append-only(旧区间只是被
|
|
274
|
+
// shadowed),sessionId 不变。这正是"锚点",不需要也不允许插件去物理重写 transcript。
|
|
275
|
+
//
|
|
276
|
+
// 默认 false:它要花钱(摘要模型)且会改写当前会话的可见历史,必须先经人同意。
|
|
277
|
+
anchor: { enabled: false, mode: 'compaction' },
|
|
264
278
|
coldStartInjectRecentTurns: true,
|
|
265
279
|
// REMOVED in v1.5.3: `minInjectConfidence`. It never demonstrably saved tokens
|
|
266
280
|
// (0.6 vs 0 produced byte-identical payloads) and every hit-shaping pass is a
|
|
@@ -399,6 +413,10 @@ export const DEFAULT_CONFIG = Object.freeze({
|
|
|
399
413
|
multiSpace: true,
|
|
400
414
|
crossSpaceTransfer: true,
|
|
401
415
|
crossSpaceRecall: false,
|
|
416
|
+
// A 批 (2026-12-02): the ONE switch for AUTOMATIC handoffs. Manual paths
|
|
417
|
+
// (`/memory handoff`, the resume command) and the fail-fast guard are not
|
|
418
|
+
// "automatic" and keep working with this off.
|
|
419
|
+
enableAutoHandoff: true,
|
|
402
420
|
}),
|
|
403
421
|
// v1.5.6 L2 multi-merge: condense duplicate same-tag episodes into one record,
|
|
404
422
|
// pinned and ordinary groups strictly separated. Offline (maintain) only.
|
|
@@ -963,11 +981,35 @@ function buildResolvedConfig(raw = {}, { env = process.env } = {}) {
|
|
|
963
981
|
statePointerIn.enabled === undefined ? defaults.context.statePointer.enabled : statePointerIn.enabled,
|
|
964
982
|
'context.statePointer.enabled',
|
|
965
983
|
);
|
|
984
|
+
// A 批: inline folding is parked by default (see DEFAULT_CONFIG.context.inlineFold).
|
|
985
|
+
const inlineFoldIn = isPlainObject(contextIn.inlineFold) ? contextIn.inlineFold : {};
|
|
986
|
+
const inlineFoldEnabled = requireBoolean(
|
|
987
|
+
inlineFoldIn.enabled === undefined ? defaults.context.inlineFold.enabled : inlineFoldIn.enabled,
|
|
988
|
+
'context.inlineFold.enabled',
|
|
989
|
+
);
|
|
990
|
+
const inlineFoldThresholdChars = requireInteger(
|
|
991
|
+
inlineFoldIn.thresholdChars === undefined
|
|
992
|
+
? defaults.context.inlineFold.thresholdChars
|
|
993
|
+
: inlineFoldIn.thresholdChars,
|
|
994
|
+
'context.inlineFold.thresholdChars',
|
|
995
|
+
{ min: 500, max: 200_000 },
|
|
996
|
+
);
|
|
966
997
|
const statePointerMaxChars = requireInteger(
|
|
967
998
|
statePointerIn.maxChars === undefined ? defaults.context.statePointer.maxChars : statePointerIn.maxChars,
|
|
968
999
|
'context.statePointer.maxChars',
|
|
969
1000
|
{ min: 60, max: 2000 },
|
|
970
1001
|
);
|
|
1002
|
+
// C 批: the anchor is the host's own compaction service (see DEFAULT_CONFIG).
|
|
1003
|
+
const anchorIn = isPlainObject(contextIn.anchor) ? contextIn.anchor : {};
|
|
1004
|
+
const anchorEnabled = requireBoolean(
|
|
1005
|
+
anchorIn.enabled === undefined ? defaults.context.anchor.enabled : anchorIn.enabled,
|
|
1006
|
+
'context.anchor.enabled',
|
|
1007
|
+
);
|
|
1008
|
+
const anchorMode = requireEnum(
|
|
1009
|
+
anchorIn.mode === undefined ? defaults.context.anchor.mode : anchorIn.mode,
|
|
1010
|
+
'context.anchor.mode',
|
|
1011
|
+
['compaction'],
|
|
1012
|
+
);
|
|
971
1013
|
// REMOVED KEY (v1.5.3), loud on purpose: nested groups normally ignore unknown
|
|
972
1014
|
// keys, but silently ignoring a removed confidence knob would let a profile run
|
|
973
1015
|
// with a false belief about token behaviour. Fail fast with the exact path.
|
|
@@ -1491,6 +1533,8 @@ function buildResolvedConfig(raw = {}, { env = process.env } = {}) {
|
|
|
1491
1533
|
multiSpace: featureMultiSpace,
|
|
1492
1534
|
crossSpaceTransfer: featureCrossSpaceTransfer,
|
|
1493
1535
|
crossSpaceRecall: featureCrossSpaceRecall,
|
|
1536
|
+
// A 批: default ON; `false` is the ecosystem opt-out from automatic handing over.
|
|
1537
|
+
enableAutoHandoff: featuresIn.enableAutoHandoff === undefined ? defaults.features.enableAutoHandoff : requireBoolean(featuresIn.enableAutoHandoff, 'features.enableAutoHandoff'),
|
|
1494
1538
|
});
|
|
1495
1539
|
|
|
1496
1540
|
// ---- L2 multi-merge (v1.5.6) -------------------------------------------
|
|
@@ -1754,6 +1798,8 @@ function buildResolvedConfig(raw = {}, { env = process.env } = {}) {
|
|
|
1754
1798
|
mode: contextMode,
|
|
1755
1799
|
hintsIdleSilenceAfter: contextHintsIdleSilenceAfter,
|
|
1756
1800
|
statePointer: { enabled: statePointerEnabled, maxChars: statePointerMaxChars },
|
|
1801
|
+
inlineFold: { enabled: inlineFoldEnabled, thresholdChars: inlineFoldThresholdChars },
|
|
1802
|
+
anchor: { enabled: anchorEnabled, mode: anchorMode },
|
|
1757
1803
|
coldStartInjectRecentTurns: contextColdStartInjectRecentTurns,
|
|
1758
1804
|
// v1.5.0 routing knobs below; v1.5.3 removed minInjectConfidence entirely.
|
|
1759
1805
|
autoSpaceFollow: contextAutoSpaceFollow,
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* B 批(2026-12-02)—— 折叠从"请求路径"搬到事件与空闲两条通道。
|
|
3
|
+
*
|
|
4
|
+
* 这两条通道各自只需要一个纯决策:
|
|
5
|
+
* - 事件驱动(模块二):一条 tool/result 超阈值就立刻原地折叠,不看整窗水位;
|
|
6
|
+
* - 空闲折叠(模块三):没有新请求时,靠会话事件流把水位收敛回目标值,
|
|
7
|
+
* 而不是"只在请求路径折"——闲置会话永远卡在超额,活跃会话每 4.5 分钟卡一次。
|
|
8
|
+
*
|
|
9
|
+
* 决策是纯函数:接线(surface replace / setImmediate / backoff 写入)在 index.js,
|
|
10
|
+
* 这样"该不该折"可以脱离浏览器与宿主单测。
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
export const INLINE_FOLD_DEFAULTS = Object.freeze({ enabled: false, thresholdChars: 8000 });
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* 一条工具结果是否该被立即折叠?
|
|
17
|
+
*
|
|
18
|
+
* @param {{ enabled?: boolean, type?: string|null, chars?: number, thresholdChars?: number }} input
|
|
19
|
+
* @returns {{ fold: boolean, reason: string, chars?: number, thresholdChars?: number }}
|
|
20
|
+
*/
|
|
21
|
+
export function shouldInlineFold({ enabled = false, type = null, chars = 0, thresholdChars = 0 } = {}) {
|
|
22
|
+
if (enabled !== true) return { fold: false, reason: 'disabled' };
|
|
23
|
+
if (type !== 'tool/result') return { fold: false, reason: 'not-a-tool-result' };
|
|
24
|
+
const size = Number.isFinite(chars) && chars > 0 ? chars : 0;
|
|
25
|
+
const limit =
|
|
26
|
+
Number.isFinite(thresholdChars) && thresholdChars > 0 ? thresholdChars : INLINE_FOLD_DEFAULTS.thresholdChars;
|
|
27
|
+
if (size < limit) return { fold: false, reason: 'below-threshold' };
|
|
28
|
+
return { fold: true, reason: 'oversized-tool-result', chars: size, thresholdChars: limit };
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** How old a host pressure reading may be and still justify an idle fold. */
|
|
32
|
+
export const PRESSURE_FRESH_MS = 5 * 60_000;
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* 空闲折叠的门:忙、读数不新、有 backoff、低于阈值,都不折。
|
|
36
|
+
*
|
|
37
|
+
* @param {{ ratio?: number|null, threshold?: number, backoffUntil?: number|null, now?: number,
|
|
38
|
+
* busy?: boolean, pressureFresh?: boolean }} input
|
|
39
|
+
* @returns {{ fold: boolean, reason: string }}
|
|
40
|
+
*/
|
|
41
|
+
export function idleFoldPlan({
|
|
42
|
+
ratio = null,
|
|
43
|
+
threshold = 0.85,
|
|
44
|
+
backoffUntil = null,
|
|
45
|
+
now = 0,
|
|
46
|
+
busy = false,
|
|
47
|
+
pressureFresh = false,
|
|
48
|
+
} = {}) {
|
|
49
|
+
if (busy) return { fold: false, reason: 'busy' };
|
|
50
|
+
if (pressureFresh !== true) return { fold: false, reason: 'stale-pressure' };
|
|
51
|
+
if (!Number.isFinite(ratio)) return { fold: false, reason: 'no-pressure' };
|
|
52
|
+
if (backoffUntil !== null && Number.isFinite(Number(backoffUntil)) && Number(backoffUntil) > Number(now)) {
|
|
53
|
+
return { fold: false, reason: 'backoff' };
|
|
54
|
+
}
|
|
55
|
+
const limit = Number.isFinite(threshold) && threshold > 0 ? threshold : 0.85;
|
|
56
|
+
if (ratio < limit) return { fold: false, reason: 'below-threshold' };
|
|
57
|
+
return { fold: true, reason: 'idle-fold-due' };
|
|
58
|
+
}
|
|
@@ -24,6 +24,22 @@
|
|
|
24
24
|
*/
|
|
25
25
|
|
|
26
26
|
export const FOLD_MARKER = '[System: 此段包含';
|
|
27
|
+
/**
|
|
28
|
+
* A 批 (2026-12-02): CONSTRAINT PINNING.
|
|
29
|
+
*
|
|
30
|
+
* Governance Decay (2026) measured what lossy compression does to safety rules: 0%
|
|
31
|
+
* violations while the policy is visible in context, 30–59% once it is folded away.
|
|
32
|
+
* A message carrying this marker is therefore never a fold candidate — the rule stays
|
|
33
|
+
* verbatim for as long as the conversation lives, at the cost of its tokens.
|
|
34
|
+
*/
|
|
35
|
+
export const POLICY_MARKER = '[Hippocampus Policy]';
|
|
36
|
+
|
|
37
|
+
/** Drop every text that is one of OUR fold pointers (never feed them back to a model). */
|
|
38
|
+
export function stripFoldPointers(texts) {
|
|
39
|
+
return (Array.isArray(texts) ? texts : []).filter(
|
|
40
|
+
(text) => typeof text === 'string' && text.length > 0 && !text.startsWith(FOLD_MARKER) && !text.includes(FOLD_MARKER),
|
|
41
|
+
);
|
|
42
|
+
}
|
|
27
43
|
/** Below this, folding a node saves nothing worth the risk. */
|
|
28
44
|
export const FOLD_MIN_CHARS = 1200;
|
|
29
45
|
/** Hard ceiling on how much one request may fold, so pruning cannot snowball. */
|
|
@@ -47,6 +63,15 @@ function tokensOfChars(chars) {
|
|
|
47
63
|
return Math.ceil(Number(chars) / 4);
|
|
48
64
|
}
|
|
49
65
|
|
|
66
|
+
/** The plain text of one message (policy pinning needs to READ it, not measure it). */
|
|
67
|
+
function textOfMessage(message) {
|
|
68
|
+
const blocks = Array.isArray(message?.content) ? message.content : [];
|
|
69
|
+
return blocks
|
|
70
|
+
.filter((block) => block && block.type === 'text')
|
|
71
|
+
.map((block) => String(block.text ?? ''))
|
|
72
|
+
.join('\n');
|
|
73
|
+
}
|
|
74
|
+
|
|
50
75
|
/**
|
|
51
76
|
* The aggregate pointer. Wording is deliberately different from `foldPointer`: this
|
|
52
77
|
* one stands for a BLOCK of turns, and saying "N 轮简短交互" is what tells a reader
|
|
@@ -169,6 +194,13 @@ export function planSmartPrune(session, options = {}) {
|
|
|
169
194
|
continue;
|
|
170
195
|
}
|
|
171
196
|
const chars = textOfBlocks(message.content);
|
|
197
|
+
// A batch: CONSTRAINT PINNING — a message carrying the policy marker is never
|
|
198
|
+
// folded, and it also BREAKS the aggregate run so it cannot be swallowed by a
|
|
199
|
+
// micro-pointer either.
|
|
200
|
+
if (textOfMessage(message).includes(POLICY_MARKER)) {
|
|
201
|
+
closeRun();
|
|
202
|
+
continue;
|
|
203
|
+
}
|
|
172
204
|
const alreadyMicro = isFoldPointer(message);
|
|
173
205
|
if (alreadyMicro) {
|
|
174
206
|
closeRun();
|
|
@@ -184,6 +184,32 @@ export function foldBlocked({ projectedRatio = 0, hardStop = FOLD_HARD_STOP_RATI
|
|
|
184
184
|
/** How far pressure must fall below the marker's own ratio to count as relief. */
|
|
185
185
|
export const RELIEF_COLLAPSE_DELTA = 0.3;
|
|
186
186
|
|
|
187
|
+
/**
|
|
188
|
+
* A 批 (2026-12-02): the smallest fold that is worth its own churn.
|
|
189
|
+
*
|
|
190
|
+
* Field report (billion-context #2671): folding in a loop that frees almost nothing
|
|
191
|
+
* burns CPU and rewrites the surface on every request — a "fold storm" — while the
|
|
192
|
+
* window looks unchanged. A single pass must free at least this share of the window
|
|
193
|
+
* or it is refused and backed off.
|
|
194
|
+
*/
|
|
195
|
+
export const FOLD_MIN_RELEASE_RATIO = 0.02;
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* Is this fold pass worth keeping? No window means no veto (a test double or an old
|
|
199
|
+
* host must not be blocked by a number we do not have).
|
|
200
|
+
*
|
|
201
|
+
* @param {{ savedTokens?: number, window?: number|null }} input
|
|
202
|
+
* @returns {{ allowed: boolean, reason: string, minTokens: number }}
|
|
203
|
+
*/
|
|
204
|
+
export function foldReleaseGuard({ savedTokens = 0, window = null } = {}) {
|
|
205
|
+
const saved = Number.isFinite(savedTokens) && savedTokens > 0 ? savedTokens : 0;
|
|
206
|
+
const limit = Number.isFinite(window) && window > 0 ? window : null;
|
|
207
|
+
if (limit === null) return { allowed: true, reason: 'no-window', minTokens: 0 };
|
|
208
|
+
const minTokens = Math.max(1, Math.round(limit * FOLD_MIN_RELEASE_RATIO));
|
|
209
|
+
if (saved < minTokens) return { allowed: false, reason: 'below-min-release', minTokens };
|
|
210
|
+
return { allowed: true, reason: 'above-min-release', minTokens };
|
|
211
|
+
}
|
|
212
|
+
|
|
187
213
|
/**
|
|
188
214
|
* @param {{ markerRatio?: number|null, projectedRatio?: number, threshold?: number }} input
|
|
189
215
|
* @returns {{ relieved: boolean, reason: string }}
|
package/src/memory.js
CHANGED
|
@@ -54,7 +54,7 @@ import { SemanticStore } from './semantic/semanticStore.js';
|
|
|
54
54
|
import { TempSemanticStore } from './semantic/tempSemantic.js';
|
|
55
55
|
import { ContextEngine } from './context/contextEngine.js';
|
|
56
56
|
import { HANDOFF_CLEAR_RATIO, relievedDecision, rehandoffDecision } from './context/windowGuard.js';
|
|
57
|
-
import { FOLD_MARKER } from './context/smartPrune.js';
|
|
57
|
+
import { FOLD_MARKER, stripFoldPointers } from './context/smartPrune.js';
|
|
58
58
|
import { DEFAULT_SPACE_ID, SpaceRouter, normaliseSpaceId, validateNewSpaceId } from './spaces/singleSpace.js';
|
|
59
59
|
import { nextRun, parseCron } from './cron.js';
|
|
60
60
|
|
|
@@ -195,7 +195,16 @@ export const HANDOFF_TIMEOUT_MS = 5000;
|
|
|
195
195
|
export const HANDOFF_TAIL_TURNS = 5;
|
|
196
196
|
export const RECENT_TURN_LIMIT = 12;
|
|
197
197
|
export const RECENT_TURN_MAX_CHARS = 400;
|
|
198
|
-
export const HANDOFF_STATES = Object.freeze({
|
|
198
|
+
export const HANDOFF_STATES = Object.freeze({
|
|
199
|
+
ACTIVE: 'active',
|
|
200
|
+
FAILED: 'failed',
|
|
201
|
+
CONSUMED: 'consumed',
|
|
202
|
+
// C batch (2026-12-02): "consumed" was a lie whenever the block never reached a
|
|
203
|
+
// prompt — the marker disappeared while the next conversation started blank.
|
|
204
|
+
// A marker whose skeleton was actually injected is DELIVERED; a marker that was
|
|
205
|
+
// merely superseded by another session id keeps its own state (see Memory#deferHandoff).
|
|
206
|
+
DELIVERED: 'delivered',
|
|
207
|
+
});
|
|
199
208
|
/** Any summary whose text starts with this is a handoff summary, never evidence. */
|
|
200
209
|
export const HANDOFF_TEXT_PREFIX = '交接摘要';
|
|
201
210
|
const HANDOFF_TEXT_RE = /^\s*交接摘要/;
|
|
@@ -2113,17 +2122,13 @@ export class Memory {
|
|
|
2113
2122
|
if (!decision.relieved) {
|
|
2114
2123
|
return { marker, cleared: false, relieved: false, ratio: projectedRatio, reason: decision.reason };
|
|
2115
2124
|
}
|
|
2116
|
-
//
|
|
2117
|
-
//
|
|
2118
|
-
// Relief used to be applied by EVERY request, and folding is what produces the
|
|
2119
|
-
// relief. So the machine ran: pressure crosses the threshold -> a marker is
|
|
2120
|
-
// written at ~71% -> folding drops the same conversation to ~46% -> relief fires
|
|
2121
|
-
// -> the marker is consumed -> pressure grows again. The marker never stayed
|
|
2122
|
-
// active long enough for the re-handoff branch to ever be reached, which is
|
|
2123
|
-
// exactly "handoff never triggers no matter what I set".
|
|
2125
|
+
// A 批 (2026-12-02): THE MARKER IS NOT CLEARED BY RELIEF ANY MORE.
|
|
2124
2126
|
//
|
|
2125
|
-
//
|
|
2126
|
-
//
|
|
2127
|
+
// Relief clears itself: folding lowers the ratio, the ratio looks small, the marker
|
|
2128
|
+
// is consumed, the conversation grows back to the trigger — and the machine hands
|
|
2129
|
+
// over again at the same 60%, forever. The sawtooth is not a threshold bug, it is a
|
|
2130
|
+
// LIFETIME bug: once handed over, a conversation stays handed over until a
|
|
2131
|
+
// DIFFERENT session (or `/memory resume`) says otherwise.
|
|
2127
2132
|
if (allowRelieve !== true) {
|
|
2128
2133
|
return {
|
|
2129
2134
|
marker,
|
|
@@ -2135,24 +2140,83 @@ export class Memory {
|
|
|
2135
2140
|
};
|
|
2136
2141
|
}
|
|
2137
2142
|
const consumedBy = usage?.sessionId ?? null;
|
|
2143
|
+
const sameSession = !marker.sessionId || !consumedBy || marker.sessionId === consumedBy;
|
|
2144
|
+
if (sameSession) {
|
|
2145
|
+
return {
|
|
2146
|
+
marker,
|
|
2147
|
+
cleared: false,
|
|
2148
|
+
relieved: false,
|
|
2149
|
+
ratio: projectedRatio,
|
|
2150
|
+
reason: `${decision.reason}:marker-held`,
|
|
2151
|
+
held: true,
|
|
2152
|
+
};
|
|
2153
|
+
}
|
|
2138
2154
|
let cleared = marker;
|
|
2139
2155
|
try {
|
|
2140
2156
|
cleared = this.clearHandoff({
|
|
2141
|
-
reason: `
|
|
2142
|
-
consumedBy: `${consumedBy
|
|
2157
|
+
reason: `session-changed:${decision.reason}`,
|
|
2158
|
+
consumedBy: `${consumedBy}:ratio=${projectedRatio}`,
|
|
2143
2159
|
});
|
|
2144
2160
|
} catch {
|
|
2145
2161
|
/* a stale marker is bad, but failing the prompt would be worse */
|
|
2146
|
-
return {
|
|
2162
|
+
return {
|
|
2163
|
+
marker,
|
|
2164
|
+
cleared: false,
|
|
2165
|
+
relieved: false,
|
|
2166
|
+
ratio: projectedRatio,
|
|
2167
|
+
reason: `${decision.reason}:write-failed`,
|
|
2168
|
+
};
|
|
2147
2169
|
}
|
|
2148
|
-
return {
|
|
2170
|
+
return {
|
|
2171
|
+
marker: cleared,
|
|
2172
|
+
cleared: true,
|
|
2173
|
+
relieved: true,
|
|
2174
|
+
ratio: projectedRatio,
|
|
2175
|
+
reason: `${decision.reason}:session-changed`,
|
|
2176
|
+
};
|
|
2177
|
+
}
|
|
2178
|
+
|
|
2179
|
+
/**
|
|
2180
|
+
* C batch (2026-12-02): stamp a marker as DELIVERED after its skeleton actually
|
|
2181
|
+
* reached a prompt. Works on a consumed marker too — that is the whole point: the
|
|
2182
|
+
* field case consumed the marker at 13:18:21 and delivered nothing, and "consumed"
|
|
2183
|
+
* alone cannot tell a successful relay from a lost one.
|
|
2184
|
+
*/
|
|
2185
|
+
markHandoffDelivered({ consumedBy = null, reason = 'delivered' } = {}) {
|
|
2186
|
+
const current = readJson(this.handoffPath(), null);
|
|
2187
|
+
if (!current) return { active: false, delivered: false };
|
|
2188
|
+
const now = this.clock.now();
|
|
2189
|
+
const next = {
|
|
2190
|
+
...current,
|
|
2191
|
+
active: false,
|
|
2192
|
+
state: HANDOFF_STATES.DELIVERED,
|
|
2193
|
+
consumedAt: current.consumedAt ?? now,
|
|
2194
|
+
consumedBy: consumedBy ?? current.consumedBy ?? null,
|
|
2195
|
+
reason,
|
|
2196
|
+
deliveredAt: now,
|
|
2197
|
+
};
|
|
2198
|
+
ensureDir(this.paths.state);
|
|
2199
|
+
writeJsonAtomic(this.handoffPath(), next);
|
|
2200
|
+
this._markBriefingDirty();
|
|
2201
|
+
return { ...next, active: false, delivered: true };
|
|
2149
2202
|
}
|
|
2150
2203
|
|
|
2151
2204
|
/** Mark a handoff consumed (new session, or an explicit clear). */
|
|
2152
|
-
clearHandoff({ reason = 'manual', consumedBy = null } = {}) {
|
|
2205
|
+
clearHandoff({ reason = 'manual', consumedBy = null, state = HANDOFF_STATES.CONSUMED } = {}) {
|
|
2153
2206
|
const current = readJson(this.handoffPath(), null);
|
|
2154
2207
|
if (!current || current.active !== true) return { active: false, cleared: false };
|
|
2155
|
-
const
|
|
2208
|
+
const now = this.clock.now();
|
|
2209
|
+
const next = {
|
|
2210
|
+
...current,
|
|
2211
|
+
active: false,
|
|
2212
|
+
state,
|
|
2213
|
+
consumedAt: now,
|
|
2214
|
+
consumedBy,
|
|
2215
|
+
reason,
|
|
2216
|
+
// C batch: keep WHEN the skeleton landed next to WHO it landed on. "consumed"
|
|
2217
|
+
// without a deliveredAt is exactly the state that hid today's lost relay.
|
|
2218
|
+
deliveredAt: state === HANDOFF_STATES.DELIVERED ? now : (current.deliveredAt ?? null),
|
|
2219
|
+
};
|
|
2156
2220
|
ensureDir(this.paths.state);
|
|
2157
2221
|
writeJsonAtomic(this.handoffPath(), next);
|
|
2158
2222
|
this._markBriefingDirty();
|
|
@@ -2459,6 +2523,10 @@ export class Memory {
|
|
|
2459
2523
|
sourceTexts = events.map((event) => event.content);
|
|
2460
2524
|
}
|
|
2461
2525
|
if (sourceTexts.length === 0) return { folded: 0, reason: 'no-eligible-content' };
|
|
2526
|
+
// A batch: the skeleton is assembled by CODE, and code must never re-read its own
|
|
2527
|
+
// fold pointers — a pointer is bookkeeping, not something a person said.
|
|
2528
|
+
sourceTexts = stripFoldPointers(sourceTexts);
|
|
2529
|
+
if (sourceTexts.length === 0) return { folded: 0, reason: 'only-fold-pointers' };
|
|
2462
2530
|
|
|
2463
2531
|
const points = sourceTexts.map((text) => firstSentence(text)).filter(Boolean).slice(-5);
|
|
2464
2532
|
const names = extractNames(sourceTexts.join('\n'));
|
package/src/webRoutes.js
CHANGED
|
@@ -125,6 +125,14 @@ export const EDITABLE_CONFIG_KEYS = Object.freeze([
|
|
|
125
125
|
'context.mode',
|
|
126
126
|
'context.hintsIdleSilenceAfter',
|
|
127
127
|
'context.statePointer.enabled',
|
|
128
|
+
// A/B 批 (2026-12-02): the governance switches, writable from the settings page so an
|
|
129
|
+
// operator can stop folding / stop auto-handoff without editing the profile file.
|
|
130
|
+
'context.inlineFold.enabled',
|
|
131
|
+
'context.inlineFold.thresholdChars',
|
|
132
|
+
// C 批 (2026-12-02): the anchor is the HOST compaction service. Parked by default;
|
|
133
|
+
// an operator turns it on from the settings page and can turn it off again.
|
|
134
|
+
'context.anchor.enabled',
|
|
135
|
+
'features.enableAutoHandoff',
|
|
128
136
|
// v1.7.3 physical pruning (module 1).
|
|
129
137
|
'context.smartPrune.enabled',
|
|
130
138
|
'context.smartPrune.threshold',
|