dsh-layers-hippocampus 1.9.5 → 1.9.9
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 +96 -0
- package/README.md +2 -2
- package/index.js +244 -53
- package/package.json +1 -1
- package/src/context/ownership.js +103 -0
- package/src/context/peerProbe.js +97 -0
- package/src/context/smartPrune.js +5 -5
- package/src/handoff/coordinator.js +417 -0
- package/src/memory.js +51 -0
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,102 @@ 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.9] — 2026-12-01
|
|
8
|
+
|
|
9
|
+
**谁是折叠的唯一负责人:探测到外部折叠者就让出,但绝不让出交接。**
|
|
10
|
+
|
|
11
|
+
本机同时有 `dsh-context-fold`、宿主 `tool-result-pruner`、`compaction-basic` 与海马体四方
|
|
12
|
+
改写同一个 context surface,各有各自的阈值。任何一方折叠后,其余各方的压力比描述的都是一个
|
|
13
|
+
已经不存在的表面 —— 这正是「到 90% 也不交接」的机制。
|
|
14
|
+
|
|
15
|
+
- **Added — `src/context/peerProbe.js`**:读 loader(`configEditor.entries()`)与宿主服务
|
|
16
|
+
(`toolResultPruner`、`compaction`),报告 `foreignFolders` / `hostPruner` /
|
|
17
|
+
`hostCompaction` / `probed`。禁用行、`mode: off`、`pruner.enabled: false` 都不算折叠者。
|
|
18
|
+
任一环节抛错只降级为 `probed: false`,绝不抛给调用方。
|
|
19
|
+
- **Added — `src/context/ownership.js`(纯函数仲裁)**:`auto`(默认)/ `lone` / `shared`。
|
|
20
|
+
`auto` 下:探测到外部折叠者 → `smartPrune` 与 `liveCompact` 全关、**交接保留**;
|
|
21
|
+
仅宿主 pruner → 只关 `liveCompact`(它只重写单个超大工具结果,不折轮次);
|
|
22
|
+
宿主 compaction 启用 → 两者全关;探测不可用 → **保持原行为并报告 `probe-unavailable`**
|
|
23
|
+
(只在「探测到」时让出,避免在没有 `configEditor` 的宿主上静默丢掉折叠)。
|
|
24
|
+
- **Changed — 让出 = 不调用**:`onceFoldDue`、`liveCompact`、`smartPrune` 三处全部前置
|
|
25
|
+
`ownership` 门;让出时**一次性折叠额度不被消费**,切回 `lone` 可立刻生效。
|
|
26
|
+
- **Changed — 可见性**:`[Task State]` 增加 `fold=on` / `fold=off(<reason>)`;状态面板与
|
|
27
|
+
`/memory status` 增加「折叠归属」一行;维护 tick 重新探测。
|
|
28
|
+
- **Config — `context.ownership`**:`auto|lone|shared`,从 RAW 配置读取(resolved 配置只保留
|
|
29
|
+
已知键,未知嵌套键被忽略而不报错)。
|
|
30
|
+
- **Tests — `test/v199.ownership.test.js`(16 例)**:仲裁矩阵 7 例、loader 探测 3 例、
|
|
31
|
+
以及 6 例集成断言 —— 让出时零折叠调用、额度不消费、peer 消失后恢复折叠、`lone` 强行折叠
|
|
32
|
+
并报冲突、86% 硬停时交接照常、状态行/面板暴露决策。
|
|
33
|
+
|
|
34
|
+
## [1.9.8] — 2026-12-01
|
|
35
|
+
|
|
36
|
+
**交接六路径收拢为一个协调器:一次事件只蒸馏一次。**
|
|
37
|
+
|
|
38
|
+
改造前:`recordToolCall`、`_maybeAutoHandoff`、once-fold、硬停、fail-fast、`/memory handoff`
|
|
39
|
+
六条路径各自直接调用 `checkHandoff()`,只有 `_maybeAutoHandoff` 带并发保护。同一 tick 内两次
|
|
40
|
+
触发 = 两次 `_distillHandoffTail`、两次 `clearHandoff()` + 原子写、最多两次阻塞蒸馏 ——
|
|
41
|
+
2026-12-01 那次「没崩溃却不回话」在结构上由它解释。
|
|
42
|
+
|
|
43
|
+
- **Added — `src/handoff/coordinator.js`**:`request()`(可 await)与 `offer()`(工具边界,
|
|
44
|
+
busy 即丢)。准入顺序 R1 单飞 → R2 时间防抖(默认 `0`,关闭)→ R3 阈值 → R4 再交接增量 →
|
|
45
|
+
R5 压力带去重。默认 `maxPending: 0`(纯合并,不再排第二次蒸馏);`maxPending: 1` 可选一深
|
|
46
|
+
队列,latest-wins。
|
|
47
|
+
- **Added — 按路径预算**:请求路径 `1500ms`、fail-fast `800ms`、命令 `10000ms`。超时后调用方
|
|
48
|
+
拿到 `budget-exceeded` 并放行请求,蒸馏继续在后台跑完,marker 留给下一轮。这是「不回话」
|
|
49
|
+
的直接解药:**provider 调用不再等一次蒸馏**。
|
|
50
|
+
- **Changed — `force` 语义收窄**:`'none' | 'early' | 'manual'`。`'early'` 只绕过阈值,
|
|
51
|
+
**不再**绕过再交接增量(活的 marker 不会被强制调用重新蒸馏);只有人类敲的
|
|
52
|
+
`/memory handoff` 用 `'manual'`。布尔 `force: true` 仍被接受,但降级为 `'early'`。
|
|
53
|
+
- **Changed — 引擎侧 `_maybeAutoHandoff` 委托**:宿主装配了协调器就交给它;`_handoffInFlight`
|
|
54
|
+
只留给没有宿主的独立嵌入者(引擎测试夹具)。
|
|
55
|
+
- **Tests — `test/v198.coordinator.test.js`(15 例)**:六触发一蒸馏、`offer()` 丢弃、
|
|
56
|
+
预算早退且后台继续、阈值/增量/`manual` 三档语义、legacy 布尔降级、时间防抖、
|
|
57
|
+
压力带去重、失败即值不抛、watchdog 释放锁、脏 policy 回退默认、`maxPending` 队列。
|
|
58
|
+
- **Tests — `test/v198.source.scan.test.js`(5 例)**:裸 `checkHandoff` 只允许引擎兜底与
|
|
59
|
+
`index.js` 装配各 1 处;协调器不得 import 引擎或 Node 内置模块;`index.js` 不得出现布尔
|
|
60
|
+
force;`_handoffInFlight` 只能留在引擎;每个调用点必须带 `source` 标签。
|
|
61
|
+
|
|
62
|
+
## [1.9.7] — 2026-12-01
|
|
63
|
+
|
|
64
|
+
**85% 以上「每个请求都强制交接一次」——这看起来不像交接,像 agent 不回话了。**
|
|
65
|
+
|
|
66
|
+
- **Fixed — 强制交接没有防抖(`index.js`)**。`force: true`(1.9.4 引入)故意绕过再交接增量门,
|
|
67
|
+
而触发条件 `!foldGate.allowed` 在 85% 以上**对每个请求都为真**。两者相乘的结果是:
|
|
68
|
+
越过 85% 之后,**每一轮**都要同步做一次交接蒸馏(最多 `HANDOFF_TIMEOUT_MS` = 5 秒的阻塞 LLM 调用)。
|
|
69
|
+
用户看到的现象不是「发生了一次交接」,而是「它不回了」。
|
|
70
|
+
现在强制分支复用未强制分支同一条纪律:**再交接需要压力再涨 5 个百分点**
|
|
71
|
+
(`FORCED_HANDOFF_DELTA = 0.05`,记在 `runtime.lastForcedRatio`)。
|
|
72
|
+
- **Tests — 3 个新用例(`test/v197.forced.debounce.test.js`)**:
|
|
73
|
+
86% 连续两次请求只蒸馏一次;压力再涨 3 个百分点仍不重复、涨 6 个百分点才再交接;
|
|
74
|
+
50% 时强制分支完全不走、也不消耗增量预算。
|
|
75
|
+
|
|
76
|
+
> **证据边界**:这条修复来自读代码确认的真实缺陷(每请求一次阻塞蒸馏),
|
|
77
|
+
> 但**不能证明**它就是 2026-12-01「进程没崩却不回话」的原因——
|
|
78
|
+
> 那次没有崩溃转储,也没有 agent-loop 级别的日志。当时代谢占用在 65% 附近,
|
|
79
|
+
> 尚未越过 85% 的触发线。把它当「已确证缺陷的修复」,不当「事故定论」。
|
|
80
|
+
## [1.9.6] — 2026-12-01
|
|
81
|
+
|
|
82
|
+
**折叠指针被当成了「人说的话」,这才是「反复缩小」与「交接摘要只剩三行通知」的共同根因。**
|
|
83
|
+
|
|
84
|
+
现场证据(`state/handoff.json`,2026-12-01 12:48):`tailTurns` 三条全是
|
|
85
|
+
`[System: 此段包含1 轮…已折叠。原文 ID: raw:turn_14_user]`,没有一句真实对话。
|
|
86
|
+
|
|
87
|
+
- **Fixed — 指针挤占保护窗口(`src/context/smartPrune.js`)**。折叠产物是以 `user/message` 类型
|
|
88
|
+
写回表面的,而 `planSmartPrune` 用「从后往前数 N 个 user/message」定位保护窗口——
|
|
89
|
+
于是「最近 3 轮」变成了**三个指针**,真正的最近消息落到保护窗口**之前**,下一轮就被折掉,
|
|
90
|
+
折完又多一个指针……**自我强化**。这正是「反复缩小」停不下来的机制。
|
|
91
|
+
新增 `isFoldPointer()`:数保护窗口与挑选候选时都跳过指针。
|
|
92
|
+
- **Fixed — 交接摘要被指针污染(`src/memory.js`)**。`_recordRecentTurn` 无条件记录 surface 文本,
|
|
93
|
+
折叠后记下的就是通知本身。现在以 `FOLD_MARKER` 开头的文本不入 tail,
|
|
94
|
+
所以交接标记带的是「最后真正说了什么」,而不是三条「此段已折叠」。
|
|
95
|
+
- **Tests — 6 个新用例(`test/v196.pointer.tail.test.js`)**:尾部三个指针不再遮住真实最近三轮、
|
|
96
|
+
指针自身不会被再折、`_recordRecentTurn` 拒绝指针、空白仍被丢弃、
|
|
97
|
+
**同样的表面两次规划结果一致**(不漂移=不失控)、只有指针在尾部时最新的真实轮次也不会被折。
|
|
98
|
+
|
|
99
|
+
> 说明:2026-12-01 那次 DSH 进程退出的**直接原因没有证据**——系统里没有崩溃转储,
|
|
100
|
+
> Windows 应用日志只有 SideBySide 配置警告,Electron 侧也没有 error 记录。
|
|
101
|
+
> 上面修的是在事故现场**确证存在**的两个 bug(指针挤占保护窗口是自我强化的折叠循环),
|
|
102
|
+
> 不宣称它们就是进程退出的原因。
|
|
7
103
|
## [1.9.5] — 2026-11-30
|
|
8
104
|
|
|
9
105
|
**恢复「到点真的缩小上下文」,但只允许缩一次。**
|
package/README.md
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
|
|
8
8
|
| | |
|
|
9
9
|
| --- | --- |
|
|
10
|
-
| 版本 | **1.9.
|
|
10
|
+
| 版本 | **1.9.7** |
|
|
11
11
|
| 包名 | `dsh-layers-hippocampus` |
|
|
12
12
|
| 仓库 | <https://github.com/382quaii/dsh-Layers-Hippocampus> |
|
|
13
13
|
| 许可证 | MIT |
|
|
@@ -296,7 +296,7 @@ clear_dropbox('D:/mem/sessions/abc');
|
|
|
296
296
|
pnpm add dsh-layers-hippocampus
|
|
297
297
|
|
|
298
298
|
# 或从 GitHub 指定 tag
|
|
299
|
-
pnpm add "github:382quaii/dsh-Layers-Hippocampus#v1.9.
|
|
299
|
+
pnpm add "github:382quaii/dsh-Layers-Hippocampus#v1.9.7"
|
|
300
300
|
```
|
|
301
301
|
|
|
302
302
|
### 2. 挂到 profile
|
package/index.js
CHANGED
|
@@ -46,6 +46,11 @@ import { DreamTimer } from './src/dreamTimer.js';
|
|
|
46
46
|
import { probeCompression, resolveEngine } from './src/compression.js';
|
|
47
47
|
import { LIVE_COMPACT_DEFAULTS, liveCompactSession } from './src/context/liveCompact.js';
|
|
48
48
|
import { FOLD_HARD_STOP_RATIO, foldBlocked } from './src/context/windowGuard.js';
|
|
49
|
+
import { createHandoffCoordinator, FORCE, HANDOFF_STATUS } from './src/handoff/coordinator.js';
|
|
50
|
+
import { decideOwnership, OWNERSHIP_MODE } from './src/context/ownership.js';
|
|
51
|
+
import { probeContextPeers } from './src/context/peerProbe.js';
|
|
52
|
+
// v1.9.7: how much pressure must grow before the stop line hands off AGAIN.
|
|
53
|
+
const FORCED_HANDOFF_DELTA = 0.05;
|
|
49
54
|
|
|
50
55
|
// v1.7.4: how long a host-measured pressure reading may be reused while deciding
|
|
51
56
|
// whether a handoff marker still tells the truth. Requests are seconds apart, so five
|
|
@@ -80,7 +85,7 @@ export { resolveConfig, DEFAULT_CONFIG };
|
|
|
80
85
|
* of letting a raw 404 reach the user.
|
|
81
86
|
*/
|
|
82
87
|
export const CAPABILITIES = Object.freeze({
|
|
83
|
-
version: '1.9.
|
|
88
|
+
version: '1.9.9',
|
|
84
89
|
spaces: true,
|
|
85
90
|
memories: true,
|
|
86
91
|
transferConsent: true,
|
|
@@ -440,6 +445,86 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
|
|
|
440
445
|
};
|
|
441
446
|
runtimeRef = runtime;
|
|
442
447
|
|
|
448
|
+
/**
|
|
449
|
+
* v1.9.8 — the ONE handoff entry point (see src/handoff/coordinator.js).
|
|
450
|
+
*
|
|
451
|
+
* Six paths used to call `memory.checkHandoff()` directly and only one of them had a
|
|
452
|
+
* guard, so two distillations could run for one event. Every path below now goes
|
|
453
|
+
* through `runtime.handoff`; the engine keeps only the execution.
|
|
454
|
+
*
|
|
455
|
+
* `probe`/`run` read `runtime.memory` at CALL time, so the bootstrap retry that
|
|
456
|
+
* rebuilds the facade does not need a new coordinator.
|
|
457
|
+
*/
|
|
458
|
+
runtime.handoff = createHandoffCoordinator({
|
|
459
|
+
clock: { now: () => (Number.isFinite(runtime.memory?.clock?.now?.()) ? runtime.memory.clock.now() : Date.now()) },
|
|
460
|
+
logger: ctx?.logger ?? null,
|
|
461
|
+
// Live policy: a config patch must take effect without a restart. Unknown or
|
|
462
|
+
// non-numeric keys are filtered by the coordinator, so an absent section is fine.
|
|
463
|
+
policy: () => runtime.config?.handoff ?? {},
|
|
464
|
+
probe: () => {
|
|
465
|
+
const mem = runtime.memory;
|
|
466
|
+
if (!mem) return null;
|
|
467
|
+
const usage = mem.sessionUsage();
|
|
468
|
+
const native = mem.context.nativeState({ sessionTokens: usage.tokens });
|
|
469
|
+
return {
|
|
470
|
+
sessionId: usage.sessionId ?? null,
|
|
471
|
+
projectedRatio: native.projectedRatio,
|
|
472
|
+
rolloverDue: native.rolloverDue === true,
|
|
473
|
+
hardExceeded: native.hardExceeded === true,
|
|
474
|
+
marker: mem.handoffState(),
|
|
475
|
+
};
|
|
476
|
+
},
|
|
477
|
+
// The ONLY bare checkHandoff call outside the engine. `'early'`/`'manual'` were
|
|
478
|
+
// already validated against the re-handoff delta by the coordinator, so the engine
|
|
479
|
+
// boolean (which bypasses every gate) is only set for those two verbs.
|
|
480
|
+
run: ({ force }) =>
|
|
481
|
+
runtime.memory.checkHandoff({
|
|
482
|
+
now: runtime.memory.clock.now(),
|
|
483
|
+
force: force === FORCE.EARLY || force === FORCE.MANUAL,
|
|
484
|
+
}),
|
|
485
|
+
});
|
|
486
|
+
memory.setHandoffCoordinator?.(runtime.handoff);
|
|
487
|
+
|
|
488
|
+
/**
|
|
489
|
+
* v1.9.9 — who is allowed to fold this conversation?
|
|
490
|
+
*
|
|
491
|
+
* `auto` yields folding as soon as another component is mounted and able to fold:
|
|
492
|
+
* two folders invalidate each other's pressure ratio. Yielding must mean NOT CALLING
|
|
493
|
+
* the folder (see the guardRequest gates below), never "folding more gently".
|
|
494
|
+
*
|
|
495
|
+
* The mode lives in the RAW config (`context.ownership`): the resolved config only
|
|
496
|
+
* carries keys the package knows about, while `resolveConfig` ignores an unknown
|
|
497
|
+
* nested key instead of rejecting it. Reading the raw value keeps the switch usable
|
|
498
|
+
* without a schema change, and a missing key means `auto`.
|
|
499
|
+
*/
|
|
500
|
+
const OWNERSHIP_TTL_MS = 30_000;
|
|
501
|
+
runtime.refreshOwnership = () => {
|
|
502
|
+
let peers = null;
|
|
503
|
+
try {
|
|
504
|
+
peers = probeContextPeers({ ctx, logger: ctx?.logger ?? null });
|
|
505
|
+
} catch (error) {
|
|
506
|
+
// A probe that throws means "unknown", NOT "nobody else is here".
|
|
507
|
+
peers = { probed: false, foreignFolders: [], hostPruner: false, hostCompaction: 'unknown' };
|
|
508
|
+
ctx?.logger?.warn?.(`hippocampus/ownership: probe failed: ${error?.message ?? error}`);
|
|
509
|
+
}
|
|
510
|
+
let mode = OWNERSHIP_MODE.AUTO;
|
|
511
|
+
try {
|
|
512
|
+
mode = runtime.rawConfig?.context?.ownership ?? runtime.config?.context?.ownership ?? OWNERSHIP_MODE.AUTO;
|
|
513
|
+
} catch {
|
|
514
|
+
/* a broken raw config must not decide ownership */
|
|
515
|
+
}
|
|
516
|
+
const decided = decideOwnership({ mode, peers });
|
|
517
|
+
runtime.ownership = { ...decided, peers, at: runtime.memory?.clock?.now?.() ?? Date.now() };
|
|
518
|
+
return runtime.ownership;
|
|
519
|
+
};
|
|
520
|
+
runtime.ownershipOf = (force = false) => {
|
|
521
|
+
const now = runtime.memory?.clock?.now?.() ?? Date.now();
|
|
522
|
+
if (!force && runtime.ownership && now - runtime.ownership.at < OWNERSHIP_TTL_MS) return runtime.ownership;
|
|
523
|
+
return runtime.refreshOwnership();
|
|
524
|
+
};
|
|
525
|
+
// Decide once now so every caller (prompt, status, guard) sees a value, never `null`.
|
|
526
|
+
runtime.refreshOwnership();
|
|
527
|
+
|
|
443
528
|
/** Rebind the rings to the current dataDir / persistence flag (cosmetic state). */
|
|
444
529
|
runtime.resetActivityStores = () => {
|
|
445
530
|
activityStores.clear();
|
|
@@ -557,15 +642,13 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
|
|
|
557
642
|
// v1.5.0: every tool boundary is a natural pseudo-turn. Evaluate the rollover
|
|
558
643
|
// costlessly; only a due handoff performs I/O, and it must never surface as a
|
|
559
644
|
// tool failure (fire-and-forget).
|
|
645
|
+
//
|
|
646
|
+
// v1.9.8: the evaluation itself moved into the coordinator. `offer()` reads the
|
|
647
|
+
// live probe, applies every gate, and DROPS when a run is already in flight — so
|
|
648
|
+
// ten tool calls in one turn cost ten cheap decisions, not ten distillations.
|
|
560
649
|
if (runtime.phase === 'ready') {
|
|
561
650
|
try {
|
|
562
|
-
|
|
563
|
-
const native = memory.context.nativeState({ sessionTokens: usage.tokens });
|
|
564
|
-
if (native.rolloverDue || native.forceEvictionDue) {
|
|
565
|
-
memory
|
|
566
|
-
.checkHandoff()
|
|
567
|
-
.catch((error) => ctx?.logger?.warn?.(`hippocampus: handoff failed: ${asMemoryError(error).code}`));
|
|
568
|
-
}
|
|
651
|
+
runtime.handoff.offer({ source: 'tool-boundary' });
|
|
569
652
|
} catch {
|
|
570
653
|
/* accounting failure must never break a tool result */
|
|
571
654
|
}
|
|
@@ -696,6 +779,15 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
|
|
|
696
779
|
} catch {
|
|
697
780
|
/* ignore */
|
|
698
781
|
}
|
|
782
|
+
try {
|
|
783
|
+
// v1.9.9: folding ownership is a fact about THIS turn's behaviour, so it belongs
|
|
784
|
+
// in the one line that answers "where am I now". A yielded fold that nobody can
|
|
785
|
+
// see is indistinguishable from a broken one.
|
|
786
|
+
const ownership = runtime.ownershipOf?.();
|
|
787
|
+
if (ownership) fields.fold = ownership.smartPrune === 'on' ? 'fold=on' : `fold=off(${ownership.reason})`;
|
|
788
|
+
} catch {
|
|
789
|
+
/* ignore */
|
|
790
|
+
}
|
|
699
791
|
const text = renderStateLine(fields, { maxChars: budget });
|
|
700
792
|
runtime.statePointerCache = { at: now, text };
|
|
701
793
|
return text;
|
|
@@ -1331,6 +1423,15 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
|
|
|
1331
1423
|
// outright and the handoff is forced — enforced BEFORE any folder runs, because
|
|
1332
1424
|
// those folders are what would otherwise keep the ratio down.
|
|
1333
1425
|
const gateRatio = Number.isFinite(state.projectedRatio) ? state.projectedRatio : 0;
|
|
1426
|
+
// ---- v1.9.9 ownership gate (C1) ---------------------------------------
|
|
1427
|
+
// Exactly ONE component may fold this surface. When another component is mounted
|
|
1428
|
+
// and able to fold, folding is REFUSED here — not made gentler. A second folder
|
|
1429
|
+
// resets the very ratio the handoff decision below is computed from, which is how
|
|
1430
|
+
// a conversation reaches 90% and still never hands over. The handoff is never
|
|
1431
|
+
// yielded: that is the half this plugin keeps.
|
|
1432
|
+
const ownership = runtime.ownershipOf();
|
|
1433
|
+
const foldOwned = ownership.smartPrune === 'on';
|
|
1434
|
+
const liveCompactOwned = ownership.liveCompact === 'on';
|
|
1334
1435
|
// ---- 0.1 the ONE-SHOT fold (v1.9.5) ------------------------------------
|
|
1335
1436
|
// Folding exists so a conversation can actually get smaller — but folding on
|
|
1336
1437
|
// every request is the "context drops from 10% to 7% over and over" bug that
|
|
@@ -1342,6 +1443,7 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
|
|
|
1342
1443
|
const sessionKey = session?.id ?? memory.sessionUsage()?.sessionId ?? null;
|
|
1343
1444
|
if (!runtime.onceFoldedSessions) runtime.onceFoldedSessions = new Set();
|
|
1344
1445
|
const onceFoldDue =
|
|
1446
|
+
foldOwned &&
|
|
1345
1447
|
onceFoldAt > 0 &&
|
|
1346
1448
|
Number.isFinite(gateRatio) &&
|
|
1347
1449
|
gateRatio >= onceFoldAt &&
|
|
@@ -1359,7 +1461,7 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
|
|
|
1359
1461
|
}
|
|
1360
1462
|
|
|
1361
1463
|
const liveConfig = runtime.config?.context?.liveCompact ?? {};
|
|
1362
|
-
if (liveConfig.enabled !== false && session && foldGate.allowed) {
|
|
1464
|
+
if (liveCompactOwned && liveConfig.enabled !== false && session && foldGate.allowed) {
|
|
1363
1465
|
try {
|
|
1364
1466
|
runtime.lastLiveCompact = {
|
|
1365
1467
|
source: 'hippocampus',
|
|
@@ -1378,7 +1480,7 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
|
|
|
1378
1480
|
}
|
|
1379
1481
|
|
|
1380
1482
|
const pruneThreshold = Number.isFinite(pruneConfig.threshold) ? pruneConfig.threshold : 0.85;
|
|
1381
|
-
const pruneAllowed = foldGate.allowed && (state.projectedRatio >= pruneThreshold || onceFoldDue);
|
|
1483
|
+
const pruneAllowed = foldOwned && foldGate.allowed && (state.projectedRatio >= pruneThreshold || onceFoldDue);
|
|
1382
1484
|
if (pruneConfig.enabled !== false && session && pruneAllowed) {
|
|
1383
1485
|
try {
|
|
1384
1486
|
runtime.lastSmartPrune = {
|
|
@@ -1455,26 +1557,32 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
|
|
|
1455
1557
|
// session's single chance to shrink (caught by v195's "cannot be consumed" test).
|
|
1456
1558
|
if (onceFoldDue && foldGate.allowed) {
|
|
1457
1559
|
if (sessionKey !== null) runtime.onceFoldedSessions.add(sessionKey);
|
|
1458
|
-
|
|
1459
|
-
|
|
1460
|
-
|
|
1461
|
-
|
|
1462
|
-
|
|
1463
|
-
|
|
1464
|
-
|
|
1465
|
-
|
|
1466
|
-
|
|
1467
|
-
|
|
1468
|
-
|
|
1469
|
-
|
|
1470
|
-
|
|
1471
|
-
|
|
1472
|
-
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
|
|
1476
|
-
|
|
1477
|
-
|
|
1560
|
+
// v1.9.8: through the coordinator, with the REQUEST-path budget. If distillation
|
|
1561
|
+
// outlives it, this request goes out anyway and the marker lands for the next
|
|
1562
|
+
// turn — blocking the provider call is what used to read as "no reply".
|
|
1563
|
+
const outcome = await runtime.handoff.request({
|
|
1564
|
+
source: 'once-fold',
|
|
1565
|
+
force: FORCE.EARLY,
|
|
1566
|
+
budgetMs: runtime.handoff.policy().requestBudgetMs,
|
|
1567
|
+
context: {
|
|
1568
|
+
sessionId: sessionKey,
|
|
1569
|
+
projectedRatio: gateRatio,
|
|
1570
|
+
rolloverDue: true,
|
|
1571
|
+
marker: memory.handoffState(),
|
|
1572
|
+
},
|
|
1573
|
+
});
|
|
1574
|
+
const handed = outcome.result ?? null;
|
|
1575
|
+
const record = {
|
|
1576
|
+
at: memory.clock.now(),
|
|
1577
|
+
ratio: gateRatio,
|
|
1578
|
+
onceFoldAt,
|
|
1579
|
+
folded: runtime.lastSmartPrune?.folded ?? 0,
|
|
1580
|
+
handoffActive: handed?.handoff?.active === true,
|
|
1581
|
+
degraded: handed?.handoff?.degraded === true,
|
|
1582
|
+
status: outcome.status,
|
|
1583
|
+
};
|
|
1584
|
+
if (outcome.error) record.error = outcome.error.code;
|
|
1585
|
+
runtime.lastOnceFoldHandoff = record;
|
|
1478
1586
|
}
|
|
1479
1587
|
|
|
1480
1588
|
// ---- 2.7 forced handoff at the folding hard stop (v1.9.4) -------------
|
|
@@ -1482,24 +1590,41 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
|
|
|
1482
1590
|
// is at 85% of its window: hand off NOW instead of waiting for the 60% trigger,
|
|
1483
1591
|
// which folding may have made unreachable. `force` bypasses the threshold gates;
|
|
1484
1592
|
// a failure here is reported, never thrown (a handoff must not fail a request).
|
|
1485
|
-
|
|
1486
|
-
|
|
1487
|
-
|
|
1488
|
-
|
|
1489
|
-
|
|
1490
|
-
|
|
1491
|
-
|
|
1492
|
-
|
|
1493
|
-
|
|
1494
|
-
|
|
1495
|
-
|
|
1496
|
-
|
|
1497
|
-
|
|
1498
|
-
|
|
1499
|
-
|
|
1500
|
-
|
|
1501
|
-
|
|
1502
|
-
|
|
1593
|
+
//
|
|
1594
|
+
// v1.9.7: AND IT MUST NOT REPEAT ON EVERY REQUEST. `force` bypasses the
|
|
1595
|
+
// re-handoff delta, so `!foldGate.allowed` (true for EVERY request at >=85%)
|
|
1596
|
+
// meant a fresh distillation -- up to HANDOFF_TIMEOUT_MS of blocking LLM work --
|
|
1597
|
+
// on every single turn. From the outside that reads as "the agent stopped
|
|
1598
|
+
// answering", not as a handoff. Reuse the same 5-point delta the unforced path
|
|
1599
|
+
// uses: hand off once, then again only after pressure really grows.
|
|
1600
|
+
const lastForcedRatio = Number.isFinite(runtime.lastForcedRatio) ? runtime.lastForcedRatio : 0;
|
|
1601
|
+
const forceDue = gateRatio >= lastForcedRatio + FORCED_HANDOFF_DELTA;
|
|
1602
|
+
if (!foldGate.allowed && forceDue) {
|
|
1603
|
+
runtime.lastForcedRatio = gateRatio;
|
|
1604
|
+
// v1.9.8: `'early'` bypasses the THRESHOLD only. The coordinator still applies
|
|
1605
|
+
// the re-handoff delta, so a forced call cannot re-distil a live marker.
|
|
1606
|
+
const outcome = await runtime.handoff.request({
|
|
1607
|
+
source: 'hard-stop',
|
|
1608
|
+
force: FORCE.EARLY,
|
|
1609
|
+
budgetMs: runtime.handoff.policy().requestBudgetMs,
|
|
1610
|
+
context: {
|
|
1611
|
+
sessionId: sessionKey,
|
|
1612
|
+
projectedRatio: gateRatio,
|
|
1613
|
+
rolloverDue: true,
|
|
1614
|
+
marker: memory.handoffState(),
|
|
1615
|
+
},
|
|
1616
|
+
});
|
|
1617
|
+
const forced = outcome.result ?? null;
|
|
1618
|
+
const record = {
|
|
1619
|
+
at: memory.clock.now(),
|
|
1620
|
+
ratio: gateRatio,
|
|
1621
|
+
active: forced?.handoff?.active === true,
|
|
1622
|
+
degraded: forced?.handoff?.degraded === true,
|
|
1623
|
+
reason: forced?.forced === true ? 'hard-stop' : 'already-handled',
|
|
1624
|
+
status: outcome.status,
|
|
1625
|
+
};
|
|
1626
|
+
if (outcome.error) record.error = outcome.error.code;
|
|
1627
|
+
runtime.lastForcedHandoff = record;
|
|
1503
1628
|
}
|
|
1504
1629
|
|
|
1505
1630
|
// ---- 3. fail fast on a request that CANNOT fit -------------------------
|
|
@@ -1508,7 +1633,22 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
|
|
|
1508
1633
|
// distilled tail for the next one instead of repeating the same failure.
|
|
1509
1634
|
let handoff = null;
|
|
1510
1635
|
try {
|
|
1511
|
-
|
|
1636
|
+
// v1.9.8: the fail-fast path has its OWN budget — the request is already known
|
|
1637
|
+
// not to fit, so waiting the full request budget would only delay the error by
|
|
1638
|
+
// another 700ms. The run itself keeps going in the background.
|
|
1639
|
+
const outcome = await runtime.handoff.request({
|
|
1640
|
+
source: 'fail-fast',
|
|
1641
|
+
force: FORCE.NONE,
|
|
1642
|
+
budgetMs: runtime.handoff.policy().failFastBudgetMs,
|
|
1643
|
+
context: {
|
|
1644
|
+
sessionId: sessionKey,
|
|
1645
|
+
projectedRatio: gateRatio,
|
|
1646
|
+
rolloverDue: true,
|
|
1647
|
+
hardExceeded: true,
|
|
1648
|
+
marker: memory.handoffState(),
|
|
1649
|
+
},
|
|
1650
|
+
});
|
|
1651
|
+
handoff = outcome.result ?? null;
|
|
1512
1652
|
} catch {
|
|
1513
1653
|
/* the fail-fast below is the contract; a failed handoff only degrades recovery */
|
|
1514
1654
|
}
|
|
@@ -1546,6 +1686,14 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
|
|
|
1546
1686
|
runtime.maintenanceInFlight = true;
|
|
1547
1687
|
runtime.maintenanceSource = source;
|
|
1548
1688
|
runtime.touch();
|
|
1689
|
+
// v1.9.9: the maintenance tick is the routine re-probe of who else is folding. A
|
|
1690
|
+
// profile can lose context-fold (or gain host compaction) between two startups, and
|
|
1691
|
+
// a stale ownership decision would keep yielding folding for the whole process.
|
|
1692
|
+
try {
|
|
1693
|
+
runtime.refreshOwnership();
|
|
1694
|
+
} catch {
|
|
1695
|
+
/* a failed probe keeps the previous decision and the conservative default */
|
|
1696
|
+
}
|
|
1549
1697
|
try {
|
|
1550
1698
|
const report = await memory.maintain({ reason: source });
|
|
1551
1699
|
// v1.5.5: the offline Dream leg runs AFTER the read model has converged and
|
|
@@ -1695,8 +1843,16 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
|
|
|
1695
1843
|
};
|
|
1696
1844
|
|
|
1697
1845
|
runtime.status = async () => {
|
|
1698
|
-
if (runtime.phase
|
|
1699
|
-
|
|
1846
|
+
if (runtime.phase !== 'ready') throw runtime.notReady('status');
|
|
1847
|
+
const panel = { ...(await memory.status()) };
|
|
1848
|
+
// v1.9.9: "who is folding" is the first question a surprising ratio raises, and a
|
|
1849
|
+
// silent yield is indistinguishable from a broken fold. The panel answers it.
|
|
1850
|
+
try {
|
|
1851
|
+
panel.ownership = runtime.ownershipOf(true);
|
|
1852
|
+
} catch {
|
|
1853
|
+
/* the panel must survive a failed probe */
|
|
1854
|
+
}
|
|
1855
|
+
return panel;
|
|
1700
1856
|
};
|
|
1701
1857
|
|
|
1702
1858
|
runtime.start = () => {
|
|
@@ -2345,6 +2501,9 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
|
|
|
2345
2501
|
}
|
|
2346
2502
|
memory = new Memory({ dataDir: next.dataDir, policy: nextOptions.policy, config: nextOptions.config, clock, activity: activityFor(null), ...multiSpaceExtras() });
|
|
2347
2503
|
runtime.memory = memory;
|
|
2504
|
+
// v1.9.8: a rebuilt facade must keep the same gate, or `_maybeAutoHandoff` would
|
|
2505
|
+
// silently fall back to its own lock after a bootstrap retry / migration reload.
|
|
2506
|
+
memory.setHandoffCoordinator?.(runtime.handoff);
|
|
2348
2507
|
runtime.config = next;
|
|
2349
2508
|
runtime.rawConfig = merged;
|
|
2350
2509
|
// The rings are bound to physical dirs; after the swap they must follow the new
|
|
@@ -2417,6 +2576,9 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
|
|
|
2417
2576
|
}
|
|
2418
2577
|
memory = new Memory({ dataDir: config.dataDir, policy: options.policy, config: options.config, clock, activity: runtime.activity, ...multiSpaceExtras() });
|
|
2419
2578
|
runtime.memory = memory;
|
|
2579
|
+
// v1.9.8: a rebuilt facade must keep the same gate, or `_maybeAutoHandoff` would
|
|
2580
|
+
// silently fall back to its own lock after a bootstrap retry / migration reload.
|
|
2581
|
+
memory.setHandoffCoordinator?.(runtime.handoff);
|
|
2420
2582
|
memory.setHandoffPresetProvider?.(() => runtime.agentPreset);
|
|
2421
2583
|
emit({ type: 'retry', phase: runtime.phase });
|
|
2422
2584
|
queueMicrotask(() => {
|
|
@@ -3881,6 +4043,19 @@ export async function apply(ctx, rawConfig = {}) {
|
|
|
3881
4043
|
.map((entry) => entry.tag)
|
|
3882
4044
|
.filter(Boolean);
|
|
3883
4045
|
const feedbackStatus = runtime.hintFeedbackView();
|
|
4046
|
+
// v1.9.9: the yield must be readable, not inferred from a ratio that stopped
|
|
4047
|
+
// falling. `probe-unavailable` in particular means "we did not look".
|
|
4048
|
+
const ownership = (() => {
|
|
4049
|
+
try {
|
|
4050
|
+
return runtime.ownershipOf?.() ?? null;
|
|
4051
|
+
} catch {
|
|
4052
|
+
return null;
|
|
4053
|
+
}
|
|
4054
|
+
})();
|
|
4055
|
+
const ownershipLine = ownership
|
|
4056
|
+
? `折叠归属:smartPrune=${ownership.smartPrune} liveCompact=${ownership.liveCompact} handoff=${ownership.handoff} · ${ownership.reason}` +
|
|
4057
|
+
(ownership.foreignFolders?.length ? `(探测到:${ownership.foreignFolders.join('、')})` : '')
|
|
4058
|
+
: '折叠归属:未知';
|
|
3884
4059
|
return ok(
|
|
3885
4060
|
[
|
|
3886
4061
|
// v1.9.4: the one-liner comes FIRST — it is what a person opens this for.
|
|
@@ -3894,7 +4069,7 @@ export async function apply(ctx, rawConfig = {}) {
|
|
|
3894
4069
|
// v1.7.1: the hint loop is visible, not a mystery. A silenced tag is
|
|
3895
4070
|
// the engine's own decision and the operator must be able to see why.
|
|
3896
4071
|
`H提示反馈:追踪 ${feedbackStatus.tracked} 个标签,单向静默 ${feedbackStatus.silenced} 个${feedbackStatus.silencedTags.length ? `(${feedbackStatus.silencedTags.join('、')})` : ''}`,
|
|
3897
|
-
// v1.7.0 (M5): usage EVIDENCE, computed from in-process counters only.
|
|
4072
|
+
ownershipLine, // v1.7.0 (M5): usage EVIDENCE, computed from in-process counters only.
|
|
3898
4073
|
`工具使用(本进程):${toolUsageLine()}`,
|
|
3899
4074
|
].join('\n'),
|
|
3900
4075
|
);
|
|
@@ -3909,7 +4084,23 @@ export async function apply(ctx, rawConfig = {}) {
|
|
|
3909
4084
|
let result = null;
|
|
3910
4085
|
let error = null;
|
|
3911
4086
|
try {
|
|
3912
|
-
|
|
4087
|
+
// v1.9.8: `'manual'` is the ONLY verb that skips the re-handoff delta, and a
|
|
4088
|
+
// human typed it. Single-flight still applies — a command must never start a
|
|
4089
|
+
// second distillation next to a running one.
|
|
4090
|
+
const outcome = await runtime.handoff.request({
|
|
4091
|
+
source: 'command',
|
|
4092
|
+
force: FORCE.MANUAL,
|
|
4093
|
+
budgetMs: runtime.handoff.policy().commandBudgetMs,
|
|
4094
|
+
});
|
|
4095
|
+
result = outcome.result ?? null;
|
|
4096
|
+
if (!result) {
|
|
4097
|
+
return ok(
|
|
4098
|
+
`[Handoff 强制检测]\n结果: ${outcome.status}` +
|
|
4099
|
+
(outcome.status === HANDOFF_STATUS.BUDGET_EXCEEDED
|
|
4100
|
+
? '(等待超时,蒸馏仍在后台进行;先用 /memory status 看 lastResult)'
|
|
4101
|
+
: '(本次未执行蒸馏)'),
|
|
4102
|
+
);
|
|
4103
|
+
}
|
|
3913
4104
|
} catch (caught) {
|
|
3914
4105
|
error = caught;
|
|
3915
4106
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-layers-hippocampus",
|
|
3
|
-
"version": "1.9.
|
|
3
|
+
"version": "1.9.9",
|
|
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",
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* v1.9.9 — who owns "make the context smaller"?
|
|
3
|
+
*
|
|
4
|
+
* A profile can mount more than one component that rewrites the same context surface:
|
|
5
|
+
* this plugin (smartPrune + liveCompact), `dsh-context-fold` (tool-result folding and a
|
|
6
|
+
* compaction ledger), the host's own `tool-result-pruner`, and `compaction-basic`. Each
|
|
7
|
+
* has its own threshold and its own measure, so the moment one of them folds, the
|
|
8
|
+
* others' pressure ratio describes a surface that no longer exists.
|
|
9
|
+
*
|
|
10
|
+
* 1.9.4 already argued that folding is FAKE relief (it shrinks the prompt without
|
|
11
|
+
* reducing what was said) and made the handoff the thing that carries a conversation
|
|
12
|
+
* forward. Four writers make that argument impossible to hold: any of them can reset
|
|
13
|
+
* pressure just before our trigger. So the rule is now explicit and configurable:
|
|
14
|
+
*
|
|
15
|
+
* - `auto` (default) — exactly one component folds. If a foreign folder is present,
|
|
16
|
+
* hippocampus YIELDS folding entirely and keeps the handoff. Yielding means
|
|
17
|
+
* not calling the folder at all: a "quieter" fold is still a fold.
|
|
18
|
+
* - `lone` — hippocampus folds regardless of peers, and reports the conflict.
|
|
19
|
+
* - `shared` — observe only: no folding, no handoff. For diagnosing a profile.
|
|
20
|
+
*
|
|
21
|
+
* This module is pure: it takes the mode and a peer snapshot, and returns a decision.
|
|
22
|
+
* Reading the loader is `peerProbe.js`; using the decision is `index.js`.
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
export const OWNERSHIP_MODE = Object.freeze({ AUTO: 'auto', LONE: 'lone', SHARED: 'shared' });
|
|
26
|
+
|
|
27
|
+
const SWITCH = Object.freeze({ ON: 'on', OFF: 'off' });
|
|
28
|
+
|
|
29
|
+
/** Longest reason code rendered into the prompt's `[Task State]` line. */
|
|
30
|
+
const MAX_REASON = 24;
|
|
31
|
+
|
|
32
|
+
function normalizeMode(mode) {
|
|
33
|
+
const value = String(mode ?? '').toLowerCase();
|
|
34
|
+
if (value === OWNERSHIP_MODE.LONE || value === OWNERSHIP_MODE.SHARED) return value;
|
|
35
|
+
return OWNERSHIP_MODE.AUTO;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function foreignFoldersOf(peers) {
|
|
39
|
+
const list = Array.isArray(peers?.foreignFolders) ? peers.foreignFolders : [];
|
|
40
|
+
return list
|
|
41
|
+
.filter((entry) => entry && entry.foldEnabled !== false)
|
|
42
|
+
.map((entry) => String(entry.id ?? entry.name ?? 'peer'));
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* @param {{ mode?: string, peers?: object|null }} input
|
|
47
|
+
* @returns {{
|
|
48
|
+
* mode: string,
|
|
49
|
+
* smartPrune: 'on'|'off',
|
|
50
|
+
* liveCompact: 'on'|'off',
|
|
51
|
+
* handoff: 'on'|'off',
|
|
52
|
+
* reason: string,
|
|
53
|
+
* conflict: boolean,
|
|
54
|
+
* foreignFolders: string[],
|
|
55
|
+
* peers: object|null
|
|
56
|
+
* }}
|
|
57
|
+
*/
|
|
58
|
+
export function decideOwnership({ mode = OWNERSHIP_MODE.AUTO, peers = null } = {}) {
|
|
59
|
+
const normalizedMode = normalizeMode(mode);
|
|
60
|
+
const foreign = foreignFoldersOf(peers);
|
|
61
|
+
const decision = (smartPrune, liveCompact, handoff, reason, conflict = false) => ({
|
|
62
|
+
mode: normalizedMode,
|
|
63
|
+
smartPrune,
|
|
64
|
+
liveCompact,
|
|
65
|
+
handoff,
|
|
66
|
+
reason: String(reason).slice(0, MAX_REASON),
|
|
67
|
+
conflict,
|
|
68
|
+
foreignFolders: foreign,
|
|
69
|
+
peers,
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
// `lone` is the escape hatch for a profile where the sibling folder is broken or
|
|
73
|
+
// unwanted. It is loud: the conflict is reported, not hidden.
|
|
74
|
+
if (normalizedMode === OWNERSHIP_MODE.LONE) {
|
|
75
|
+
return decision(SWITCH.ON, SWITCH.ON, SWITCH.ON, 'lone', foreign.length > 0);
|
|
76
|
+
}
|
|
77
|
+
// `shared` exists so an operator can watch what the other component does.
|
|
78
|
+
if (normalizedMode === OWNERSHIP_MODE.SHARED) {
|
|
79
|
+
return decision(SWITCH.OFF, SWITCH.OFF, SWITCH.OFF, 'shared');
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// ---- auto ---------------------------------------------------------------
|
|
83
|
+
// An unreadable loader is NOT a detected peer. Yielding on "unknown" would silently
|
|
84
|
+
// remove folding on every host that does not expose `configEditor` — a much larger
|
|
85
|
+
// and quieter failure than the one this release fixes. So: yield only on DETECTION,
|
|
86
|
+
// and make the blind state visible (`probe-unavailable`) so it can be diagnosed.
|
|
87
|
+
if (peers?.probed !== true) {
|
|
88
|
+
return decision(SWITCH.ON, SWITCH.ON, SWITCH.ON, 'probe-unavailable');
|
|
89
|
+
}
|
|
90
|
+
if (foreign.length > 0) {
|
|
91
|
+
return decision(SWITCH.OFF, SWITCH.OFF, SWITCH.ON, `peer:${foreign[0]}`);
|
|
92
|
+
}
|
|
93
|
+
if (peers?.hostCompaction === 'enabled') {
|
|
94
|
+
return decision(SWITCH.OFF, SWITCH.OFF, SWITCH.ON, 'host-compaction');
|
|
95
|
+
}
|
|
96
|
+
// The host pruner only rewrites individual oversized tool results; it does not fold
|
|
97
|
+
// turns, so R3/R5-style decisions keep describing the same surface. Our own
|
|
98
|
+
// liveCompact, however, would be the second writer on that exact surface.
|
|
99
|
+
if (peers?.hostPruner === true) {
|
|
100
|
+
return decision(SWITCH.ON, SWITCH.OFF, SWITCH.ON, 'host-pruner');
|
|
101
|
+
}
|
|
102
|
+
return decision(SWITCH.ON, SWITCH.ON, SWITCH.ON, 'owner');
|
|
103
|
+
}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* v1.9.9 — read the loader and report which components could fold this conversation.
|
|
3
|
+
*
|
|
4
|
+
* The probe is deliberately defensive: every fact it reports is "best effort", and the
|
|
5
|
+
* ONLY thing the caller may conclude from a failure is `probed: false` (which makes
|
|
6
|
+
* `decideOwnership()` yield folding — see ownership.js for why that direction is safe).
|
|
7
|
+
*
|
|
8
|
+
* Two independent sources, because neither is always present:
|
|
9
|
+
* 1. `ctx.get('configEditor').entries()` — the loader rows. This is how a disabled
|
|
10
|
+
* row, a renamed row id and a row's own Config are all visible. index.js already
|
|
11
|
+
* uses this seam to persist config, so it is a known-good dependency.
|
|
12
|
+
* 2. Service presence — `toolResultPruner` (host pruner) and `compaction` (whichever
|
|
13
|
+
* backend holds the slot). A service can exist without a row we can read.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
/** Ids we recognise as "someone else folds turns". */
|
|
17
|
+
const FOREIGN_FOLDER_NAMES = ['dsh-context-fold', 'context-fold'];
|
|
18
|
+
const HOST_COMPACTION_NAMES = ['dsh-compaction-basic', 'compaction-basic'];
|
|
19
|
+
|
|
20
|
+
function rowOf(entry) {
|
|
21
|
+
const options = entry?.options ?? entry ?? {};
|
|
22
|
+
return {
|
|
23
|
+
id: options.id ?? entry?.id ?? null,
|
|
24
|
+
name: options.name ?? entry?.name ?? null,
|
|
25
|
+
disabled: options.disabled === true,
|
|
26
|
+
config: options.config && typeof options.config === 'object' ? options.config : {},
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function matches(row, names) {
|
|
31
|
+
const id = String(row.id ?? '');
|
|
32
|
+
const name = String(row.name ?? '');
|
|
33
|
+
return names.some((candidate) => id === candidate || name === candidate || name.includes(candidate) || id.includes(candidate));
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* @param {{ ctx?: object|null, logger?: object|null }} input
|
|
38
|
+
* @returns {{
|
|
39
|
+
* probed: boolean,
|
|
40
|
+
* rows: number,
|
|
41
|
+
* foreignFolders: Array<{id: string, name: string|null, foldEnabled: boolean}>,
|
|
42
|
+
* hostPruner: boolean,
|
|
43
|
+
* hostCompaction: 'enabled'|'disabled'|'unknown'
|
|
44
|
+
* }}
|
|
45
|
+
*/
|
|
46
|
+
export function probeContextPeers({ ctx = null, logger = null } = {}) {
|
|
47
|
+
const peers = {
|
|
48
|
+
probed: false,
|
|
49
|
+
rows: 0,
|
|
50
|
+
foreignFolders: [],
|
|
51
|
+
hostPruner: false,
|
|
52
|
+
hostCompaction: 'unknown',
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
const get = (name) => {
|
|
56
|
+
try {
|
|
57
|
+
return typeof ctx?.get === 'function' ? ctx.get(name) : null;
|
|
58
|
+
} catch {
|
|
59
|
+
return null;
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
peers.hostPruner = Boolean(get('toolResultPruner'));
|
|
64
|
+
|
|
65
|
+
let entries = null;
|
|
66
|
+
try {
|
|
67
|
+
const editor = get('configEditor');
|
|
68
|
+
if (editor && typeof editor.entries === 'function') entries = editor.entries();
|
|
69
|
+
} catch (error) {
|
|
70
|
+
logger?.debug?.(`hippocampus/ownership: configEditor.entries failed: ${error?.message ?? error}`);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
if (Array.isArray(entries)) {
|
|
74
|
+
peers.probed = true;
|
|
75
|
+
peers.rows = entries.length;
|
|
76
|
+
for (const entry of entries) {
|
|
77
|
+
const row = rowOf(entry);
|
|
78
|
+
if (matches(row, FOREIGN_FOLDER_NAMES)) {
|
|
79
|
+
peers.foreignFolders.push({
|
|
80
|
+
id: String(row.id ?? row.name ?? 'context-fold'),
|
|
81
|
+
name: row.name ?? null,
|
|
82
|
+
// A mounted row that is disabled, or a `mode: off`, is not folding anything.
|
|
83
|
+
foldEnabled: row.disabled !== true && row.config?.mode !== 'off' && row.config?.pruner?.enabled !== false,
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
if (matches(row, HOST_COMPACTION_NAMES)) {
|
|
87
|
+
peers.hostCompaction = row.disabled === true ? 'disabled' : 'enabled';
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// Service fallback: a compaction backend can hold the slot without a row we could
|
|
93
|
+
// read (a bundle row, an unlisted entry). Only used when the rows said nothing.
|
|
94
|
+
if (peers.hostCompaction === 'unknown' && get('compaction')) peers.hostCompaction = 'enabled';
|
|
95
|
+
|
|
96
|
+
return peers;
|
|
97
|
+
}
|
|
@@ -85,7 +85,7 @@ function textOfBlocks(content) {
|
|
|
85
85
|
return total;
|
|
86
86
|
}
|
|
87
87
|
|
|
88
|
-
function messageOf(session, seq) {
|
|
88
|
+
/** * v1.9.6: is this message already a FOLD POINTER rather than something a person said? * * This matters more than it looks. A pointer is written back as `user/message`, so * every later pass counted it as a user turn: the three most recent "user turns" * became three POINTERS, `protectedFrom` slid past the real messages, and the next * fold ate them -- which produced another pointer, and so on. That self-reinforcing * loop is what made folding look like it never stopped, and it is why the handoff * marker's `tailTurns` ended up carrying nothing but "此段已折叠" notices. */function isFoldPointer(message) { const content = message?.content; if (!Array.isArray(content)) return false; return content.some( (block) => block && typeof block.text === 'string' && block.text.startsWith(FOLD_MARKER), );}function messageOf(session, seq) {
|
|
89
89
|
try {
|
|
90
90
|
const event = typeof session?.eventAt === 'function' ? session.eventAt(seq) : null;
|
|
91
91
|
if (!event) return null;
|
|
@@ -120,7 +120,9 @@ export function planSmartPrune(session, options = {}) {
|
|
|
120
120
|
for (let index = nodes.length - 1; index >= 0; index -= 1) {
|
|
121
121
|
const node = messageOf(session, nodes[index]);
|
|
122
122
|
if (!node) continue;
|
|
123
|
-
|
|
123
|
+
// A fold pointer is not a turn a person took: counting it here slides the
|
|
124
|
+
// protected window past the real messages and folds them next time.
|
|
125
|
+
if (node.event?.type === 'user/message' && !isFoldPointer(node.message)) {
|
|
124
126
|
seen += 1;
|
|
125
127
|
if (seen >= keepRecentTurns) {
|
|
126
128
|
protectedFrom = index;
|
|
@@ -167,9 +169,7 @@ export function planSmartPrune(session, options = {}) {
|
|
|
167
169
|
continue;
|
|
168
170
|
}
|
|
169
171
|
const chars = textOfBlocks(message.content);
|
|
170
|
-
const alreadyMicro = message
|
|
171
|
-
(block) => block && typeof block.text === 'string' && block.text.startsWith(FOLD_MARKER),
|
|
172
|
-
);
|
|
172
|
+
const alreadyMicro = isFoldPointer(message);
|
|
173
173
|
if (alreadyMicro) {
|
|
174
174
|
closeRun();
|
|
175
175
|
continue;
|
|
@@ -0,0 +1,417 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* v1.9.8 — the ONE handoff entry point.
|
|
3
|
+
*
|
|
4
|
+
* Before this module, six independent paths called `memory.checkHandoff()` and only
|
|
5
|
+
* `_maybeAutoHandoff()` carried a concurrency guard. `recordToolCall()`, the one-shot
|
|
6
|
+
* fold, the folding hard stop, the fail-fast path and `/memory handoff` could all fire
|
|
7
|
+
* in the same tick: two `_distillHandoffTail()` runs, two `clearHandoff()` +
|
|
8
|
+
* `writeJsonAtomic()` pairs, and up to two blocking LLM distillations for one event.
|
|
9
|
+
* The 2026-12-01 incident ("no crash, no reply") is structurally explained by that.
|
|
10
|
+
*
|
|
11
|
+
* The coordinator owns the DECISION and the QUEUE; the engine keeps the EXECUTION
|
|
12
|
+
* (`checkHandoff`). Consequences, all deliberate:
|
|
13
|
+
*
|
|
14
|
+
* - **Single flight.** At most one distillation runs at a time. A second awaited
|
|
15
|
+
* request becomes at most ONE pending entry (latest wins); a fire-and-forget offer
|
|
16
|
+
* is simply dropped while a run is in flight.
|
|
17
|
+
* - **Budgets are per path.** The provider call must not wait for a distillation:
|
|
18
|
+
* the request path reads the result within `requestBudgetMs` and returns, while the
|
|
19
|
+
* run itself finishes in the background and publishes the marker for the NEXT turn.
|
|
20
|
+
* - **`force` is narrowed.** `'early'` bypasses ONLY the threshold gate. The
|
|
21
|
+
* re-handoff delta still applies, so a forced call can no longer re-distill a
|
|
22
|
+
* marker that is already active. `'manual'` (a human typing `/memory handoff`) is
|
|
23
|
+
* the only verb that skips the delta, and it is named so it cannot be reached by
|
|
24
|
+
* accident. The old boolean `true` is accepted but demoted to `'early'`.
|
|
25
|
+
* - **Never throws into the caller.** A handoff is best-effort; a failure is a value.
|
|
26
|
+
*
|
|
27
|
+
* This module is deliberately dependency-free (no cordis, no store access): the host
|
|
28
|
+
* injects `probe()` and `run()`, and tests inject fakes.
|
|
29
|
+
*/
|
|
30
|
+
|
|
31
|
+
/** The three force verbs. There is no fourth way to start a distillation. */
|
|
32
|
+
export const FORCE = Object.freeze({
|
|
33
|
+
/** Respect every gate (threshold + re-handoff delta). Default for automatic paths. */
|
|
34
|
+
NONE: 'none',
|
|
35
|
+
/** Bypass the THRESHOLD only; the re-handoff delta still applies. */
|
|
36
|
+
EARLY: 'early',
|
|
37
|
+
/** A human asked (`/memory handoff`): skip the delta too. Still respects single-flight. */
|
|
38
|
+
MANUAL: 'manual',
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
/** Every terminal outcome carries one of these. A caller must not have to infer. */
|
|
42
|
+
export const HANDOFF_STATUS = Object.freeze({
|
|
43
|
+
DONE: 'done',
|
|
44
|
+
DEGRADED: 'degraded',
|
|
45
|
+
ERROR: 'error',
|
|
46
|
+
COALESCED: 'coalesced',
|
|
47
|
+
SUPERSEDED: 'superseded',
|
|
48
|
+
THROTTLED: 'throttled',
|
|
49
|
+
DEDUPED: 'deduped',
|
|
50
|
+
BELOW_GATE: 'below-gate',
|
|
51
|
+
ALREADY_ACTIVE: 'already-active',
|
|
52
|
+
BUDGET_EXCEEDED: 'budget-exceeded',
|
|
53
|
+
WATCHDOG: 'watchdog',
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
export const DEFAULT_HANDOFF_POLICY = Object.freeze({
|
|
57
|
+
/**
|
|
58
|
+
* Wall-clock spacing between two STARTED handoffs. Default 0 (off) on purpose:
|
|
59
|
+
* the real anti-repeat rule is the 5-point re-handoff delta, and a wall-clock gate
|
|
60
|
+
* would reject a genuine growth that happens two seconds later (v197 asserts that
|
|
61
|
+
* growth re-handoffs). Set it only if a profile wants a hard floor.
|
|
62
|
+
*/
|
|
63
|
+
minIntervalMs: 0,
|
|
64
|
+
/** The provider call waits this long for a handoff before it goes out anyway. */
|
|
65
|
+
requestBudgetMs: 1500,
|
|
66
|
+
/** Fail-fast has less time: the request is already known not to fit. */
|
|
67
|
+
failFastBudgetMs: 800,
|
|
68
|
+
/** A human command may wait longer; it is interactive, not per-turn. */
|
|
69
|
+
commandBudgetMs: 10_000,
|
|
70
|
+
/**
|
|
71
|
+
* Absolute ceiling for one run. `checkHandoff` has its own HANDOFF_TIMEOUT_MS (5s),
|
|
72
|
+
* so this only fires when the injected runner ignores its own contract. It exists so
|
|
73
|
+
* a hung run can never leave the single-flight lock held forever.
|
|
74
|
+
*/
|
|
75
|
+
maxRunMs: 15_000,
|
|
76
|
+
/** Re-handoff needs real growth past the marker's own ratio (same as windowGuard). */
|
|
77
|
+
rehandoffDelta: 0.05,
|
|
78
|
+
/** Above this the re-handoff is unconditional (do not argue with a full window). */
|
|
79
|
+
nearLimitRatio: 0.95,
|
|
80
|
+
/**
|
|
81
|
+
* How many AWAITED requests may wait for the run in flight. Default 0 = pure
|
|
82
|
+
* coalescing: the run that is already going writes the marker for the next turn, so
|
|
83
|
+
* a second distillation started the moment it finishes is exactly the duplicate work
|
|
84
|
+
* this release exists to remove. Raise it only for a profile that must eventually
|
|
85
|
+
* succeed at a specific trigger.
|
|
86
|
+
*/
|
|
87
|
+
maxPending: 0,
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
const BUDGET = Symbol('handoff-budget');
|
|
91
|
+
|
|
92
|
+
function normalizePolicy(policy) {
|
|
93
|
+
const raw = (typeof policy === 'function' ? policy() : policy) ?? {};
|
|
94
|
+
const merged = { ...DEFAULT_HANDOFF_POLICY };
|
|
95
|
+
for (const [key, value] of Object.entries(raw)) {
|
|
96
|
+
if (Number.isFinite(value)) merged[key] = value;
|
|
97
|
+
}
|
|
98
|
+
return merged;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function normalizeForce(force) {
|
|
102
|
+
if (force === FORCE.EARLY || force === FORCE.MANUAL) return force;
|
|
103
|
+
// v1.9.4 callers passed `true` meaning "skip every gate". Demote it: the boolean is
|
|
104
|
+
// exactly the ambiguity this release removes, and no automatic path may keep it.
|
|
105
|
+
if (force === true) return FORCE.EARLY;
|
|
106
|
+
return FORCE.NONE;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* @param {object} deps
|
|
111
|
+
* @param {{ now(): number }} deps.clock
|
|
112
|
+
* @param {object|null} [deps.logger]
|
|
113
|
+
* @param {() => object} [deps.policy] live policy (config-backed); may change
|
|
114
|
+
* @param {() => object|null} [deps.probe] current pressure/marker snapshot
|
|
115
|
+
* @param {(input: { force: string, reason: string, runId: number, context: object|null }) => Promise<object>} deps.run
|
|
116
|
+
*/
|
|
117
|
+
export function createHandoffCoordinator({ clock, logger = null, policy = () => ({}), probe = null, run } = {}) {
|
|
118
|
+
if (typeof run !== 'function') throw new TypeError('createHandoffCoordinator requires a run() executor');
|
|
119
|
+
|
|
120
|
+
const now = () => {
|
|
121
|
+
try {
|
|
122
|
+
const value = typeof clock?.now === 'function' ? clock.now() : null;
|
|
123
|
+
if (Number.isFinite(value)) return value;
|
|
124
|
+
} catch {
|
|
125
|
+
/* a broken clock must not fail a handoff decision */
|
|
126
|
+
}
|
|
127
|
+
return Date.now();
|
|
128
|
+
};
|
|
129
|
+
|
|
130
|
+
/** `{ runId, source, startedAt, promise }` while a distillation is running. */
|
|
131
|
+
let inFlight = null;
|
|
132
|
+
/** At most one queued request: `{ request, context, decision, deferred }`. */
|
|
133
|
+
let pending = null;
|
|
134
|
+
let lastStartedAt = null;
|
|
135
|
+
/** Last settled outcome, for `/memory status` and tests. */
|
|
136
|
+
let lastResult = null;
|
|
137
|
+
let runCounter = 0;
|
|
138
|
+
/** sessionId -> pressure bucket of the last STARTED run (R5). */
|
|
139
|
+
const lastBucketBySession = new Map();
|
|
140
|
+
|
|
141
|
+
const warn = (message) => {
|
|
142
|
+
try {
|
|
143
|
+
logger?.warn?.(`hippocampus: handoff ${message}`);
|
|
144
|
+
} catch {
|
|
145
|
+
/* logging must never break the queue */
|
|
146
|
+
}
|
|
147
|
+
};
|
|
148
|
+
|
|
149
|
+
function snapshotContext(context) {
|
|
150
|
+
if (context && typeof context === 'object') return context;
|
|
151
|
+
try {
|
|
152
|
+
return probe?.() ?? null;
|
|
153
|
+
} catch {
|
|
154
|
+
return null;
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* The rules, in order. Deliberately synchronous: two triggers arriving in the same
|
|
160
|
+
* tick must both observe the same pre-run state, so nothing here awaits.
|
|
161
|
+
*/
|
|
162
|
+
/** The pressure band a context belongs to (used by R5 and by coalesced outcomes). */
|
|
163
|
+
function bandOf(context) {
|
|
164
|
+
const ratio = Number.isFinite(context?.projectedRatio) ? context.projectedRatio : null;
|
|
165
|
+
return { bucket: ratio === null ? null : Math.round(ratio * 100), sessionId: context?.sessionId ?? null };
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function evaluate(request, context, activePolicy) {
|
|
169
|
+
const sessionId = context?.sessionId ?? null;
|
|
170
|
+
const ratio = Number.isFinite(context?.projectedRatio) ? context.projectedRatio : null;
|
|
171
|
+
const marker = context?.marker ?? null;
|
|
172
|
+
const sameSession = !marker?.sessionId || !sessionId || marker.sessionId === sessionId;
|
|
173
|
+
const bucket = ratio === null ? null : Math.round(ratio * 100);
|
|
174
|
+
const base = { bucket, sessionId, ratio, marker, sameSession };
|
|
175
|
+
|
|
176
|
+
// R2 — wall-clock spacing (off by default; never applies to a human command).
|
|
177
|
+
if (activePolicy.minIntervalMs > 0 && request.force !== FORCE.MANUAL && lastStartedAt !== null) {
|
|
178
|
+
const elapsed = now() - lastStartedAt;
|
|
179
|
+
if (elapsed < activePolicy.minIntervalMs) {
|
|
180
|
+
return { ...base, status: HANDOFF_STATUS.THROTTLED, retryInMs: activePolicy.minIntervalMs - elapsed };
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// R3 — the threshold. `'early'` bypasses THIS and nothing else.
|
|
185
|
+
if (request.force === FORCE.NONE && context && context.rolloverDue !== true && context.hardExceeded !== true) {
|
|
186
|
+
return { ...base, status: HANDOFF_STATUS.BELOW_GATE };
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
// R4 — re-handoff inside the same session needs real growth past the marker.
|
|
190
|
+
// Applies to 'early' as well: forcing must not re-distil a live marker.
|
|
191
|
+
if (marker?.active === true && sameSession && request.force !== FORCE.MANUAL) {
|
|
192
|
+
const markerRatio = Number.isFinite(marker.ratio) ? marker.ratio : null;
|
|
193
|
+
if (markerRatio !== null && ratio !== null) {
|
|
194
|
+
const growth = ratio - markerRatio;
|
|
195
|
+
if (growth < activePolicy.rehandoffDelta && ratio < activePolicy.nearLimitRatio) {
|
|
196
|
+
return { ...base, status: HANDOFF_STATUS.ALREADY_ACTIVE, growth };
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
// R5 — same pressure band, same session: the summary for this band already exists.
|
|
202
|
+
if (request.force !== FORCE.MANUAL && sessionId && bucket !== null && lastBucketBySession.get(sessionId) === bucket) {
|
|
203
|
+
return { ...base, status: HANDOFF_STATUS.DEDUPED };
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
return { ...base, status: null };
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
function buildOutcome({ status, runId = null, source = null, decision = null, result = null, error = null, waitedMs = 0, retryInMs = null, coalesced = false }) {
|
|
210
|
+
const handoff = result?.handoff ?? null;
|
|
211
|
+
const resolved = status === HANDOFF_STATUS.DONE && handoff?.degraded === true ? HANDOFF_STATUS.DEGRADED : status;
|
|
212
|
+
return {
|
|
213
|
+
status: resolved,
|
|
214
|
+
source,
|
|
215
|
+
runId,
|
|
216
|
+
bucket: decision?.bucket ?? null,
|
|
217
|
+
retryInMs,
|
|
218
|
+
coalesced,
|
|
219
|
+
waitedMs,
|
|
220
|
+
forced: result?.forced === true,
|
|
221
|
+
handoff,
|
|
222
|
+
diagnostic: result?.diagnostic ?? null,
|
|
223
|
+
result,
|
|
224
|
+
error: error ? { code: error?.code ?? 'MEM_E_HANDOFF_FAILED', message: error?.message ?? String(error) } : null,
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** Resolve the queued request (if any) now that the lock is free. */
|
|
229
|
+
function pumpPending() {
|
|
230
|
+
if (!pending || inFlight) return;
|
|
231
|
+
const next = pending;
|
|
232
|
+
pending = null;
|
|
233
|
+
startRun(next.request, next.context, next.decision).then(next.resolve, next.reject);
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
function releaseRun(runId) {
|
|
237
|
+
if (inFlight?.runId === runId) inFlight = null;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/**
|
|
241
|
+
* Start ONE run. The returned promise settles at `budgetMs` at the latest, but the
|
|
242
|
+
* underlying distillation is NOT cancelled: the marker it writes is what the next
|
|
243
|
+
* turn reads, so letting it finish is the point.
|
|
244
|
+
*/
|
|
245
|
+
function startRun(request, context, decision) {
|
|
246
|
+
const activePolicy = normalizePolicy(policy);
|
|
247
|
+
const startedAt = now();
|
|
248
|
+
runCounter += 1;
|
|
249
|
+
const runId = runCounter;
|
|
250
|
+
const sessionId = decision?.sessionId ?? null;
|
|
251
|
+
if (sessionId && decision?.bucket !== null && decision?.bucket !== undefined) {
|
|
252
|
+
lastBucketBySession.set(sessionId, decision.bucket);
|
|
253
|
+
}
|
|
254
|
+
lastStartedAt = startedAt;
|
|
255
|
+
|
|
256
|
+
const execute = Promise.resolve().then(() =>
|
|
257
|
+
run({ force: request.force, reason: request.source, runId, context }),
|
|
258
|
+
);
|
|
259
|
+
inFlight = { runId, source: request.source, startedAt, promise: execute };
|
|
260
|
+
|
|
261
|
+
// Absolute ceiling: a runner that ignores its own timeout must not wedge the queue.
|
|
262
|
+
let watchdog = null;
|
|
263
|
+
if (activePolicy.maxRunMs > 0) {
|
|
264
|
+
watchdog = setTimeout(() => {
|
|
265
|
+
if (inFlight?.runId !== runId) return;
|
|
266
|
+
warn(`watchdog: ${request.source} did not settle within ${activePolicy.maxRunMs}ms`);
|
|
267
|
+
releaseRun(runId);
|
|
268
|
+
const outcome = buildOutcome({ status: HANDOFF_STATUS.WATCHDOG, runId, source: request.source, decision, waitedMs: now() - startedAt });
|
|
269
|
+
lastResult = outcome;
|
|
270
|
+
pumpPending();
|
|
271
|
+
}, activePolicy.maxRunMs);
|
|
272
|
+
watchdog.unref?.();
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
const settled = execute.then(
|
|
276
|
+
(result) => {
|
|
277
|
+
if (watchdog) clearTimeout(watchdog);
|
|
278
|
+
releaseRun(runId);
|
|
279
|
+
const outcome = buildOutcome({
|
|
280
|
+
status: HANDOFF_STATUS.DONE,
|
|
281
|
+
runId,
|
|
282
|
+
source: request.source,
|
|
283
|
+
decision,
|
|
284
|
+
result,
|
|
285
|
+
waitedMs: now() - startedAt,
|
|
286
|
+
});
|
|
287
|
+
lastResult = outcome;
|
|
288
|
+
pumpPending();
|
|
289
|
+
return outcome;
|
|
290
|
+
},
|
|
291
|
+
(error) => {
|
|
292
|
+
if (watchdog) clearTimeout(watchdog);
|
|
293
|
+
releaseRun(runId);
|
|
294
|
+
const outcome = buildOutcome({
|
|
295
|
+
status: HANDOFF_STATUS.ERROR,
|
|
296
|
+
runId,
|
|
297
|
+
source: request.source,
|
|
298
|
+
decision,
|
|
299
|
+
error,
|
|
300
|
+
waitedMs: now() - startedAt,
|
|
301
|
+
});
|
|
302
|
+
lastResult = outcome;
|
|
303
|
+
warn(`failed (${request.source}): ${outcome.error.code}`);
|
|
304
|
+
pumpPending();
|
|
305
|
+
return outcome;
|
|
306
|
+
},
|
|
307
|
+
);
|
|
308
|
+
// The budget race below may abandon `settled`; it must never look unhandled.
|
|
309
|
+
settled.catch(() => {});
|
|
310
|
+
|
|
311
|
+
const budgetMs = Number.isFinite(request.budgetMs) ? request.budgetMs : activePolicy.requestBudgetMs;
|
|
312
|
+
if (!(budgetMs > 0)) return settled;
|
|
313
|
+
|
|
314
|
+
const budget = new Promise((resolve) => {
|
|
315
|
+
const timer = setTimeout(() => resolve(BUDGET), budgetMs);
|
|
316
|
+
timer.unref?.();
|
|
317
|
+
});
|
|
318
|
+
return Promise.race([settled, budget.then((marker) => marker)]).then((value) => {
|
|
319
|
+
if (value === BUDGET) {
|
|
320
|
+
// The run keeps going; the caller gets the truth about WHY it has no answer.
|
|
321
|
+
return buildOutcome({
|
|
322
|
+
status: HANDOFF_STATUS.BUDGET_EXCEEDED,
|
|
323
|
+
runId,
|
|
324
|
+
source: request.source,
|
|
325
|
+
decision,
|
|
326
|
+
waitedMs: budgetMs,
|
|
327
|
+
});
|
|
328
|
+
}
|
|
329
|
+
return value;
|
|
330
|
+
});
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
/**
|
|
334
|
+
* Awaited entry point. Never rejects: every refusal and every failure is a status.
|
|
335
|
+
*
|
|
336
|
+
* @param {{ source?: string, force?: string|boolean, budgetMs?: number, context?: object|null, awaitable?: boolean }} options
|
|
337
|
+
*/
|
|
338
|
+
async function request(options = {}) {
|
|
339
|
+
const request_ = {
|
|
340
|
+
source: String(options.source ?? 'unknown'),
|
|
341
|
+
force: normalizeForce(options.force),
|
|
342
|
+
budgetMs: options.budgetMs,
|
|
343
|
+
};
|
|
344
|
+
const context = snapshotContext(options.context);
|
|
345
|
+
const activePolicy = normalizePolicy(policy);
|
|
346
|
+
|
|
347
|
+
// R1 FIRST. While a run is in flight, the only correct answer is "coalesce": the
|
|
348
|
+
// gates below describe a NEW run, and one is already happening. (Checking the gates
|
|
349
|
+
// first used to answer `deduped` for a trigger that was actually concurrent.)
|
|
350
|
+
if (inFlight) {
|
|
351
|
+
if (activePolicy.maxPending > 0) {
|
|
352
|
+
if (pending) {
|
|
353
|
+
// Latest wins: the queued request is superseded, not stacked behind.
|
|
354
|
+
const previous = pending;
|
|
355
|
+
pending = null;
|
|
356
|
+
previous.resolve(
|
|
357
|
+
buildOutcome({ status: HANDOFF_STATUS.SUPERSEDED, source: previous.request.source, decision: previous.decision }),
|
|
358
|
+
);
|
|
359
|
+
}
|
|
360
|
+
return new Promise((resolve, reject) => {
|
|
361
|
+
pending = { request: request_, context, decision: bandOf(context), resolve, reject };
|
|
362
|
+
});
|
|
363
|
+
}
|
|
364
|
+
const coalesced = buildOutcome({
|
|
365
|
+
status: HANDOFF_STATUS.COALESCED,
|
|
366
|
+
source: request_.source,
|
|
367
|
+
decision: bandOf(context),
|
|
368
|
+
coalesced: true,
|
|
369
|
+
});
|
|
370
|
+
lastResult = coalesced;
|
|
371
|
+
return coalesced;
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
const decision = evaluate(request_, context, activePolicy);
|
|
375
|
+
if (decision.status !== null) {
|
|
376
|
+
const outcome = buildOutcome({ status: decision.status, source: request_.source, decision, retryInMs: decision.retryInMs ?? null });
|
|
377
|
+
lastResult = outcome;
|
|
378
|
+
return outcome;
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
return startRun(request_, context, decision);
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
/**
|
|
385
|
+
* Fire-and-forget entry point for a tool boundary: it must cost nothing and it must
|
|
386
|
+
* not queue. If a run is in flight this is dropped — the run that is already going
|
|
387
|
+
* will produce the marker anyway.
|
|
388
|
+
*/
|
|
389
|
+
function offer(options = {}) {
|
|
390
|
+
const request_ = { source: String(options.source ?? 'tool-boundary'), force: normalizeForce(options.force), budgetMs: 0 };
|
|
391
|
+
const context = snapshotContext(options.context);
|
|
392
|
+
const activePolicy = normalizePolicy(policy);
|
|
393
|
+
if (inFlight) {
|
|
394
|
+
return { status: HANDOFF_STATUS.COALESCED, source: request_.source, coalesced: true, bucket: bandOf(context).bucket };
|
|
395
|
+
}
|
|
396
|
+
const decision = evaluate(request_, context, activePolicy);
|
|
397
|
+
if (decision.status !== null) {
|
|
398
|
+
return { status: decision.status, source: request_.source, bucket: decision.bucket ?? null };
|
|
399
|
+
}
|
|
400
|
+
startRun(request_, context, decision).catch(() => {});
|
|
401
|
+
return { status: HANDOFF_STATUS.DONE, source: request_.source, bucket: decision.bucket ?? null, started: true };
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
function state() {
|
|
405
|
+
return {
|
|
406
|
+
inFlight: inFlight ? { runId: inFlight.runId, source: inFlight.source, startedAt: inFlight.startedAt } : null,
|
|
407
|
+
pending: pending ? { source: pending.request.source } : null,
|
|
408
|
+
lastStartedAt,
|
|
409
|
+
lastResult,
|
|
410
|
+
buckets: Object.fromEntries(lastBucketBySession),
|
|
411
|
+
runs: runCounter,
|
|
412
|
+
policy: normalizePolicy(policy),
|
|
413
|
+
};
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
return { request, offer, state, policy: () => normalizePolicy(policy) };
|
|
417
|
+
}
|
package/src/memory.js
CHANGED
|
@@ -54,6 +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
58
|
import { DEFAULT_SPACE_ID, SpaceRouter, normaliseSpaceId, validateNewSpaceId } from './spaces/singleSpace.js';
|
|
58
59
|
import { nextRun, parseCron } from './cron.js';
|
|
59
60
|
|
|
@@ -546,6 +547,14 @@ export class Memory {
|
|
|
546
547
|
/** Tags whose oversized hint has already been shown: the next recall is "insist". */
|
|
547
548
|
this._oversizedHintTags = new Set();
|
|
548
549
|
this._handoffInFlight = false;
|
|
550
|
+
/**
|
|
551
|
+
* v1.9.8: the host-owned single-flight gate (src/handoff/coordinator.js).
|
|
552
|
+
*
|
|
553
|
+
* Null in the engine-only fixture (tests that construct `Memory` directly keep the
|
|
554
|
+
* old standalone behaviour). The plugin wires it in `setHandoffCoordinator()`, and
|
|
555
|
+
* `_maybeAutoHandoff()` then routes through it instead of racing its own flag.
|
|
556
|
+
*/
|
|
557
|
+
this._handoffCoordinator = null;
|
|
549
558
|
this.maintenance.onPublished = () => {
|
|
550
559
|
this._semanticCache = null;
|
|
551
560
|
};
|
|
@@ -1948,6 +1957,11 @@ export class Memory {
|
|
|
1948
1957
|
_recordRecentTurn(role, text) {
|
|
1949
1958
|
const clean = String(text ?? '').replace(/\s+/g, ' ').trim();
|
|
1950
1959
|
if (clean.length === 0) return;
|
|
1960
|
+
// v1.9.6: a fold pointer is OUR bookkeeping, not something a person said. Recording
|
|
1961
|
+
// it made the handoff marker's `tailTurns` carry lines like "此段包含 1 轮…已折叠"
|
|
1962
|
+
// instead of the last things actually said, so the next conversation started with
|
|
1963
|
+
// three notices and no context. Caught in the field on 2026-12-01.
|
|
1964
|
+
if (clean.startsWith(FOLD_MARKER)) return;
|
|
1951
1965
|
this._recentTurns.push({
|
|
1952
1966
|
role: role === 'assistant' ? 'assistant' : 'user',
|
|
1953
1967
|
text: clean.slice(0, RECENT_TURN_MAX_CHARS),
|
|
@@ -2406,16 +2420,53 @@ export class Memory {
|
|
|
2406
2420
|
}
|
|
2407
2421
|
}
|
|
2408
2422
|
|
|
2423
|
+
/**
|
|
2424
|
+
* v1.9.8: wire the host-owned single-flight gate. See `src/handoff/coordinator.js`.
|
|
2425
|
+
* Nullable on purpose — an embedder that uses `Memory` on its own keeps the
|
|
2426
|
+
* standalone path below.
|
|
2427
|
+
*/
|
|
2428
|
+
setHandoffCoordinator(coordinator) {
|
|
2429
|
+
this._handoffCoordinator = coordinator ?? null;
|
|
2430
|
+
return this;
|
|
2431
|
+
}
|
|
2432
|
+
|
|
2409
2433
|
/**
|
|
2410
2434
|
* Fire-and-forget handoff trigger used by the session/event listener and by tool
|
|
2411
2435
|
* calls. It never throws into the host's event bus and has an OUTER watchdog as
|
|
2412
2436
|
* well as checkHandoff's internal one: even if checkHandoff itself hangs, the
|
|
2413
2437
|
* in-flight flag is released so the next session/turn can proceed.
|
|
2438
|
+
*
|
|
2439
|
+
* v1.9.8: when the host wired a coordinator, this DELEGATES instead of running its
|
|
2440
|
+
* own distillation. `_handoffInFlight` survives only for the standalone path, which
|
|
2441
|
+
* is why the source scan allows it exactly here.
|
|
2414
2442
|
*/
|
|
2415
2443
|
_maybeAutoHandoff() {
|
|
2416
2444
|
if (this._closed || this._handoffInFlight) return;
|
|
2417
2445
|
const state = this.context.nativeState({ sessionTokens: this.sessionUsage().tokens });
|
|
2418
2446
|
if (!state.rolloverDue && !state.forceEvictionDue) return;
|
|
2447
|
+
if (this._handoffCoordinator) {
|
|
2448
|
+
try {
|
|
2449
|
+
const usage = this.sessionUsage();
|
|
2450
|
+
this._handoffCoordinator
|
|
2451
|
+
.request({
|
|
2452
|
+
source: 'auto',
|
|
2453
|
+
force: 'none',
|
|
2454
|
+
context: {
|
|
2455
|
+
sessionId: usage.sessionId ?? null,
|
|
2456
|
+
projectedRatio: state.projectedRatio,
|
|
2457
|
+
rolloverDue: true,
|
|
2458
|
+
hardExceeded: state.hardExceeded === true,
|
|
2459
|
+
marker: this.handoffState(),
|
|
2460
|
+
},
|
|
2461
|
+
})
|
|
2462
|
+
.catch(() => {
|
|
2463
|
+
/* a failed handoff must never break session capture */
|
|
2464
|
+
});
|
|
2465
|
+
} catch {
|
|
2466
|
+
/* the coordinator is best-effort */
|
|
2467
|
+
}
|
|
2468
|
+
return;
|
|
2469
|
+
}
|
|
2419
2470
|
this._handoffInFlight = true;
|
|
2420
2471
|
const watchdog = new Promise((resolve) => {
|
|
2421
2472
|
const timer = setTimeout(
|