dsh-layers-hippocampus 1.7.2 → 1.7.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,220 @@
1
+ /**
2
+ * Activity stream: a tiny bounded ring of recent recall/capture events.
3
+ *
4
+ * The Web panel flashes tags that were *just* used. That is presentation state,
5
+ * not durable memory: it must never grow, never fail a recall, and never carry a
6
+ * secret. So this store:
7
+ * - keeps at most `limit` items in memory (default 64);
8
+ * - sanitises every write (<= 12 tags, <= 8 event ids, 64 chars each) and drops
9
+ * `sensitive:` / `privacy:` tags outright — the v1.7.3 sensitive read gate must
10
+ * not be undone by an activity hint;
11
+ * - persists opt-in only (`file` set), at most once per `persistIntervalMs`;
12
+ * - treats a missing/corrupt file as empty.
13
+ */
14
+
15
+ import path from 'node:path';
16
+ import { ensureDir, readJson, writeJsonAtomic } from './util.js';
17
+
18
+ /** Bump when the persisted shape changes; older files are ignored, not migrated. */
19
+ export const ACTIVITY_SCHEMA = 1;
20
+ /** Hard sanitisation caps shared by every write path. */
21
+ export const ACTIVITY_MAX_TAGS = 12;
22
+ export const ACTIVITY_MAX_EVENT_IDS = 8;
23
+ export const ACTIVITY_MAX_STRING = 64;
24
+
25
+ const KINDS = new Set(['recall', 'capture']);
26
+ const SECRET_TAG_PREFIXES = ['sensitive:', 'privacy:'];
27
+
28
+ function positiveInt(value, fallback, max) {
29
+ const number = Number(value);
30
+ if (!Number.isFinite(number)) return fallback;
31
+ return Math.max(1, Math.min(Math.trunc(number), max));
32
+ }
33
+
34
+ /** Trim, cap and drop secret tags; returns a fresh array. */
35
+ function sanitiseTags(tags) {
36
+ if (!Array.isArray(tags)) return [];
37
+ const out = [];
38
+ const seen = new Set();
39
+ for (const entry of tags) {
40
+ if (typeof entry !== 'string') continue;
41
+ const tag = entry.trim().slice(0, ACTIVITY_MAX_STRING);
42
+ if (!tag) continue;
43
+ const lowered = tag.toLowerCase();
44
+ if (SECRET_TAG_PREFIXES.some((prefix) => lowered.startsWith(prefix))) continue;
45
+ if (seen.has(tag)) continue;
46
+ seen.add(tag);
47
+ out.push(tag);
48
+ if (out.length >= ACTIVITY_MAX_TAGS) break;
49
+ }
50
+ return out;
51
+ }
52
+
53
+ /** Same contract as tags, but event ids get their own (smaller) cap. */
54
+ function sanitiseEventIds(eventIds) {
55
+ if (!Array.isArray(eventIds)) return [];
56
+ const out = [];
57
+ const seen = new Set();
58
+ for (const entry of eventIds) {
59
+ if (typeof entry !== 'string') continue;
60
+ const id = entry.trim().slice(0, ACTIVITY_MAX_STRING);
61
+ if (!id) continue;
62
+ if (seen.has(id)) continue;
63
+ seen.add(id);
64
+ out.push(id);
65
+ if (out.length >= ACTIVITY_MAX_EVENT_IDS) break;
66
+ }
67
+ return out;
68
+ }
69
+
70
+ function copyItem(item) {
71
+ return { ...item, tags: [...item.tags], eventIds: [...item.eventIds] };
72
+ }
73
+
74
+ export class ActivityStore {
75
+ /**
76
+ * @param {object} [options]
77
+ * @param {number} [options.limit] ring size (default 64)
78
+ * @param {string|null} [options.file] opt-in persistence file
79
+ * @param {{now?: Function}|null} [options.clock]
80
+ * @param {number} [options.persistIntervalMs] minimum automatic write interval
81
+ */
82
+ constructor({ limit = 64, file = null, clock = null, persistIntervalMs = 5000 } = {}) {
83
+ this.limit = positiveInt(limit, 64, 1024);
84
+ this.file = typeof file === 'string' && file.trim() ? file : null;
85
+ this.clock = clock && typeof clock.now === 'function' ? clock : { now: () => Date.now() };
86
+ this.persistIntervalMs = positiveInt(persistIntervalMs, 5000, 60 * 60 * 1000);
87
+ this._items = [];
88
+ this._cursor = 0;
89
+ this._loaded = false;
90
+ this._dirty = false;
91
+ this._timer = null;
92
+ }
93
+
94
+ /** Load the persisted ring once; corrupt/missing files are simply empty. */
95
+ _ensureLoaded() {
96
+ if (this._loaded) return;
97
+ this._loaded = true;
98
+ if (!this.file) return;
99
+ const record = readJson(this.file, null);
100
+ if (!record || record.schema !== ACTIVITY_SCHEMA || !Array.isArray(record.items)) return;
101
+ const items = record.items
102
+ .filter((item) => item && Number.isInteger(item.seq) && item.seq > 0 && KINDS.has(item.kind))
103
+ .map((item) => ({
104
+ seq: item.seq,
105
+ kind: item.kind,
106
+ tags: sanitiseTags(item.tags),
107
+ eventIds: sanitiseEventIds(item.eventIds),
108
+ at: Number.isFinite(item.at) ? item.at : this.clock.now(),
109
+ source: typeof item.source === 'string' && item.source ? item.source.slice(0, ACTIVITY_MAX_STRING) : 'memory',
110
+ }))
111
+ .sort((a, b) => a.seq - b.seq);
112
+ this._items = items.slice(-this.limit);
113
+ const storedCursor = Number.isInteger(record.cursor) && record.cursor > 0 ? record.cursor : 0;
114
+ const lastSeq = items.length > 0 ? items[items.length - 1].seq : 0;
115
+ this._cursor = Math.max(storedCursor, lastSeq);
116
+ }
117
+
118
+ /**
119
+ * Append one activity item.
120
+ *
121
+ * @param {{kind: string, tags?: string[], eventIds?: string[], at?: number|null, source?: string}} input
122
+ * @returns {{seq: number, item: object}|null} null for an unknown kind (never throws)
123
+ */
124
+ record({ kind, tags = [], eventIds = [], at = null, source = 'memory' } = {}) {
125
+ try {
126
+ if (!KINDS.has(kind)) return null;
127
+ this._ensureLoaded();
128
+ const seq = this._cursor + 1;
129
+ this._cursor = seq;
130
+ const item = {
131
+ seq,
132
+ kind,
133
+ tags: sanitiseTags(tags),
134
+ eventIds: sanitiseEventIds(eventIds),
135
+ at: Number.isFinite(at) ? at : this.clock.now(),
136
+ source: typeof source === 'string' && source ? source.slice(0, ACTIVITY_MAX_STRING) : 'memory',
137
+ };
138
+ this._items.push(item);
139
+ if (this._items.length > this.limit) this._items.splice(0, this._items.length - this.limit);
140
+ this._markDirty();
141
+ return { seq, item: copyItem(item) };
142
+ } catch {
143
+ // An activity hint must never break a recall or a capture.
144
+ return null;
145
+ }
146
+ }
147
+
148
+ /**
149
+ * Read items newer than `since`, oldest first.
150
+ *
151
+ * @param {{since?: number, limit?: number}} [options]
152
+ * @returns {{items: object[], cursor: number, now: number}}
153
+ */
154
+ recent({ since = 0, limit = 64 } = {}) {
155
+ try {
156
+ this._ensureLoaded();
157
+ const sinceSeq = Number.isFinite(Number(since)) ? Math.max(0, Math.trunc(Number(since))) : 0;
158
+ const max = positiveInt(limit, 64, this.limit);
159
+ const matching = this._items.filter((item) => item.seq > sinceSeq);
160
+ return { items: matching.slice(-max).map(copyItem), cursor: this._cursor, now: this.clock.now() };
161
+ } catch {
162
+ return { items: [], cursor: this._cursor, now: this.clock.now() };
163
+ }
164
+ }
165
+
166
+ size() {
167
+ this._ensureLoaded();
168
+ return this._items.length;
169
+ }
170
+
171
+ /** Reset the ring (and its cursor) in memory; the persisted file is truncated on flush. */
172
+ clear() {
173
+ this._ensureLoaded();
174
+ this._items = [];
175
+ this._cursor = 0;
176
+ this._dirty = true;
177
+ this._scheduleFlush();
178
+ }
179
+
180
+ /** Write now. No-op for an in-memory store. */
181
+ flush() {
182
+ this._ensureLoaded();
183
+ this._cancelFlush();
184
+ if (!this.file) return;
185
+ try {
186
+ ensureDir(path.dirname(this.file));
187
+ writeJsonAtomic(this.file, {
188
+ schema: ACTIVITY_SCHEMA,
189
+ items: this._items.map(copyItem),
190
+ cursor: this._cursor,
191
+ updatedAt: this.clock.now(),
192
+ });
193
+ this._dirty = false;
194
+ } catch {
195
+ // Persistence is best-effort; the in-memory ring stays authoritative.
196
+ }
197
+ }
198
+
199
+ _markDirty() {
200
+ this._dirty = true;
201
+ this._scheduleFlush();
202
+ }
203
+
204
+ _scheduleFlush() {
205
+ if (!this.file || this._timer) return;
206
+ const timer = setTimeout(() => {
207
+ this._timer = null;
208
+ this.flush();
209
+ }, this.persistIntervalMs);
210
+ // A pending hint flush must never keep the host process alive.
211
+ if (typeof timer.unref === 'function') timer.unref();
212
+ this._timer = timer;
213
+ }
214
+
215
+ _cancelFlush() {
216
+ if (!this._timer) return;
217
+ clearTimeout(this._timer);
218
+ this._timer = null;
219
+ }
220
+ }
package/src/config.js CHANGED
@@ -43,6 +43,10 @@ export const FLAT_ALIASES = Object.freeze({
43
43
  export const EVENT_TIME_POLICIES = Object.freeze(['content', 'explicit', 'ingest']);
44
44
  /** Raw-turn retention modes: off / gated by value / everything. */
45
45
  export const RAW_MODES = Object.freeze(['off', 'salience', 'all']);
46
+ /** v1.7.4 graph glow presets: named palettes the panel can render without a custom colour. */
47
+ export const GRAPH_GLOW_PRESETS = Object.freeze(['accent', 'vivid', 'warm']);
48
+ /** v1.7.4 canvas tint modes: follow the theme / force a tint / stay neutral. */
49
+ export const GRAPH_CANVAS_TINTS = Object.freeze(['auto', 'tint', 'none']);
46
50
 
47
51
  /**
48
52
  * Tool suffixes this plugin registers (`${toolPrefix}_<suffix>`). This is the
@@ -99,6 +103,9 @@ export const CONFIG_KEYS = Object.freeze([
99
103
  'dream',
100
104
  'enableReflection',
101
105
  'graphMaxEdges',
106
+ // v1.7.4: read-time node ceiling, applied next to graphMaxEdges.
107
+ 'graphMaxNodes',
108
+ 'ui',
102
109
  'storageBudgetMb',
103
110
  'maxRecallTopK',
104
111
  'retrieval',
@@ -181,6 +188,20 @@ export const DEFAULT_CONFIG = Object.freeze({
181
188
  // Edges returned by /api/memory/graph. The offline cache may hold up to
182
189
  // GRAPH_HARD_CAP; this is the read-time ceiling, so changing it is cheap.
183
190
  graphMaxEdges: 500,
191
+ // Nodes returned by the same route (v1.7.4): trimming is a pure projection over
192
+ // the cached graph, so the ceiling is independent from graphMaxEdges.
193
+ graphMaxNodes: 80,
194
+ // v1.7.4 graph presentation only. None of these values changes what is stored;
195
+ // they are read by the Web panel (and the activity route) and never by recall.
196
+ ui: Object.freeze({
197
+ graphGlowEnabled: true,
198
+ graphGlowPreset: 'accent',
199
+ // `null` = follow the preset; `#rrggbb` = an explicit glow colour.
200
+ graphGlowCustom: null,
201
+ graphCanvasTint: 'auto',
202
+ // Opt-in persistence of the recent-activity ring (state/activity.json).
203
+ graphActivityPersist: false,
204
+ }),
184
205
  // Display threshold for the storage ring (MB). Never evicts anything.
185
206
  storageBudgetMb: 50,
186
207
  maxRecallTopK: 100,
@@ -244,6 +265,10 @@ export const DEFAULT_CONFIG = Object.freeze({
244
265
  // permission rules here, only routing and context-window bookkeeping.
245
266
  autoSpaceFollow: false,
246
267
  autoRolloverEnabled: true,
268
+ // v1.7.4: a handoff marker is a claim about pressure. Below this ratio the claim is
269
+ // no longer true, so the marker is consumed and the [交接标记] block stops being
270
+ // injected (otherwise the model reads "context almost full" at 10% usage forever).
271
+ handoffClearRatio: 0.5,
247
272
  autoRolloverThreshold: 0.85,
248
273
  // v1.6.3: USER OVERRIDE ONLY. The model's real context window comes from the host
249
274
  // adapter (`llm.resolveModelInfo().context.contextWindow`); this value is used only
@@ -262,6 +287,11 @@ export const DEFAULT_CONFIG = Object.freeze({
262
287
  tailChars: 2_000,
263
288
  maxNodesPerRequest: 4,
264
289
  },
290
+ // v1.7.3 (module 1): physical pruning of the conversation surface. This is the
291
+ // replacement for "hope the host compacts": at `threshold` of the REAL window the
292
+ // oldest verbose turns are rewritten into `[System: …已折叠。原文 ID: ev_x]` pointers.
293
+ // The log itself is untouched — only the surface the model reads.
294
+ smartPrune: { enabled: true, threshold: 0.85, keepRecentTurns: 3, minChars: 1200, maxNodes: 8 },
265
295
  // Security (v1.5.1): moving memories across spaces is NEVER an autonomous
266
296
  // decision. While true, the engine refuses a model-initiated transfer unless
267
297
  // the tool call carries `user_approved: true`; the UI route is the human
@@ -483,6 +513,23 @@ function requireEnum(value, key, allowed) {
483
513
  return value;
484
514
  }
485
515
 
516
+ /**
517
+ * v1.7.4: `null` (follow the preset) or an explicit `#rrggbb` colour. Anything
518
+ * else is a config error carrying the key path — a typo must not silently render
519
+ * an invisible glow.
520
+ */
521
+ function requireHexColorOrNull(value, key) {
522
+ if (value === null || value === undefined) return null;
523
+ if (typeof value !== 'string' || !/^#[0-9a-fA-F]{6}$/.test(value)) {
524
+ throw configError(
525
+ ErrorCodes.CONFIG_INVALID_TYPE,
526
+ `config.${key} must be null or a #rrggbb colour, got ${JSON.stringify(value)}`,
527
+ { key, expected: 'null | #rrggbb', got: value },
528
+ );
529
+ }
530
+ return value;
531
+ }
532
+
486
533
  function requireStringArray(value, key) {
487
534
  if (!Array.isArray(value)) {
488
535
  throw configError(ErrorCodes.CONFIG_INVALID_TYPE, `config.${key} must be an array of strings`, {
@@ -530,7 +577,7 @@ function normaliseRaw(raw) {
530
577
  }
531
578
 
532
579
  const out = { ...nested };
533
- for (const group of ['retrieval', 'context', 'index', 'temp', 'decay', 'activeSet', 'raw', 'delete', 'review', 'migration', 'identity', 'tools', 'dream', 'tagging', 'features', 'l2Merge']) {
580
+ for (const group of ['retrieval', 'context', 'index', 'temp', 'decay', 'activeSet', 'raw', 'delete', 'review', 'migration', 'identity', 'tools', 'dream', 'tagging', 'features', 'l2Merge', 'ui']) {
534
581
  if (isPlainObject(nested[group])) out[group] = { ...nested[group] };
535
582
  }
536
583
  for (const [alias, path] of Object.entries(FLAT_ALIASES)) {
@@ -748,7 +795,7 @@ function attachConfigMeta(config, migration) {
748
795
  function buildResolvedConfig(raw = {}, { env = process.env } = {}) {
749
796
  const input = normaliseRaw(raw);
750
797
 
751
- for (const group of ['retrieval', 'context', 'index', 'temp', 'decay', 'activeSet', 'raw', 'delete', 'review', 'migration', 'identity', 'tools', 'dream', 'tagging', 'features', 'l2Merge']) {
798
+ for (const group of ['retrieval', 'context', 'index', 'temp', 'decay', 'activeSet', 'raw', 'delete', 'review', 'migration', 'identity', 'tools', 'dream', 'tagging', 'features', 'l2Merge', 'ui']) {
752
799
  if (group in input && input[group] !== undefined && !isPlainObject(input[group])) {
753
800
  throw configError(ErrorCodes.CONFIG_INVALID_TYPE, `config.${group} must be an object`, { key: group });
754
801
  }
@@ -898,6 +945,11 @@ function buildResolvedConfig(raw = {}, { env = process.env } = {}) {
898
945
  contextIn.autoSpaceFollow === undefined ? defaults.context.autoSpaceFollow : contextIn.autoSpaceFollow,
899
946
  'context.autoSpaceFollow',
900
947
  );
948
+ const contextHandoffClearRatio = requireNumberInRange(
949
+ contextIn.handoffClearRatio === undefined ? defaults.context.handoffClearRatio : contextIn.handoffClearRatio,
950
+ 'context.handoffClearRatio',
951
+ { min: 0.1, max: 0.9 },
952
+ );
901
953
  const contextAutoRolloverEnabled = requireBoolean(
902
954
  contextIn.autoRolloverEnabled === undefined ? defaults.context.autoRolloverEnabled : contextIn.autoRolloverEnabled,
903
955
  'context.autoRolloverEnabled',
@@ -917,6 +969,32 @@ function buildResolvedConfig(raw = {}, { env = process.env } = {}) {
917
969
  );
918
970
  // v1.6.3 Live Compact tunables. `thresholdChars` is compared against the total
919
971
  // characters of ONE tool result's text blocks.
972
+ // v1.7.3 physical pruning (module 1).
973
+ const smartPruneIn = contextIn.smartPrune ?? {};
974
+ const smartPruneEnabled = requireBoolean(
975
+ smartPruneIn.enabled === undefined ? defaults.context.smartPrune.enabled : smartPruneIn.enabled,
976
+ 'context.smartPrune.enabled',
977
+ );
978
+ const smartPruneThreshold = requireNumberInRange(
979
+ smartPruneIn.threshold === undefined ? defaults.context.smartPrune.threshold : smartPruneIn.threshold,
980
+ 'context.smartPrune.threshold',
981
+ { min: 0.5, max: 0.99 },
982
+ );
983
+ const smartPruneKeepRecentTurns = requireInteger(
984
+ smartPruneIn.keepRecentTurns === undefined ? defaults.context.smartPrune.keepRecentTurns : smartPruneIn.keepRecentTurns,
985
+ 'context.smartPrune.keepRecentTurns',
986
+ { min: 0, max: 50 },
987
+ );
988
+ const smartPruneMinChars = requireInteger(
989
+ smartPruneIn.minChars === undefined ? defaults.context.smartPrune.minChars : smartPruneIn.minChars,
990
+ 'context.smartPrune.minChars',
991
+ { min: 200, max: 1_000_000 },
992
+ );
993
+ const smartPruneMaxNodes = requireInteger(
994
+ smartPruneIn.maxNodes === undefined ? defaults.context.smartPrune.maxNodes : smartPruneIn.maxNodes,
995
+ 'context.smartPrune.maxNodes',
996
+ { min: 1, max: 64 },
997
+ );
920
998
  const liveCompactIn = contextIn.liveCompact ?? {};
921
999
  const liveCompactEnabled = requireBoolean(
922
1000
  liveCompactIn.enabled === undefined ? defaults.context.liveCompact.enabled : liveCompactIn.enabled,
@@ -1465,6 +1543,39 @@ function buildResolvedConfig(raw = {}, { env = process.env } = {}) {
1465
1543
  'graphMaxEdges',
1466
1544
  { min: 100, max: 2000 },
1467
1545
  );
1546
+ // v1.7.4 node ceiling: same fail-fast contract, independent from the edge limit.
1547
+ const graphMaxNodes = requireInteger(
1548
+ input.graphMaxNodes === undefined ? defaults.graphMaxNodes : input.graphMaxNodes,
1549
+ 'graphMaxNodes',
1550
+ { min: 10, max: 2000 },
1551
+ );
1552
+ // v1.7.4 UI-only presentation settings. They never change stored data, but a
1553
+ // typo must still fail fast instead of silently rendering an invisible graph.
1554
+ const uiIn = input.ui ?? {};
1555
+ const uiConfig = Object.freeze({
1556
+ graphGlowEnabled: requireBoolean(
1557
+ uiIn.graphGlowEnabled === undefined ? defaults.ui.graphGlowEnabled : uiIn.graphGlowEnabled,
1558
+ 'ui.graphGlowEnabled',
1559
+ ),
1560
+ graphGlowPreset: requireEnum(
1561
+ uiIn.graphGlowPreset === undefined ? defaults.ui.graphGlowPreset : uiIn.graphGlowPreset,
1562
+ 'ui.graphGlowPreset',
1563
+ GRAPH_GLOW_PRESETS,
1564
+ ),
1565
+ graphGlowCustom: requireHexColorOrNull(
1566
+ uiIn.graphGlowCustom === undefined ? defaults.ui.graphGlowCustom : uiIn.graphGlowCustom,
1567
+ 'ui.graphGlowCustom',
1568
+ ),
1569
+ graphCanvasTint: requireEnum(
1570
+ uiIn.graphCanvasTint === undefined ? defaults.ui.graphCanvasTint : uiIn.graphCanvasTint,
1571
+ 'ui.graphCanvasTint',
1572
+ GRAPH_CANVAS_TINTS,
1573
+ ),
1574
+ graphActivityPersist: requireBoolean(
1575
+ uiIn.graphActivityPersist === undefined ? defaults.ui.graphActivityPersist : uiIn.graphActivityPersist,
1576
+ 'ui.graphActivityPersist',
1577
+ ),
1578
+ });
1468
1579
  // Ring budget: integer MB, fail-fast. The UI recomputes the ring from this
1469
1580
  // value, so an out-of-range number is a config bug, not something to clamp.
1470
1581
  const storageBudgetMb = requireInteger(
@@ -1493,6 +1604,8 @@ function buildResolvedConfig(raw = {}, { env = process.env } = {}) {
1493
1604
  dream: dreamConfig,
1494
1605
  enableReflection,
1495
1606
  graphMaxEdges,
1607
+ graphMaxNodes,
1608
+ ui: uiConfig,
1496
1609
  storageBudgetMb,
1497
1610
  maxRecallTopK,
1498
1611
  retrieval: { topK: retrievalTopK },
@@ -1522,6 +1635,7 @@ function buildResolvedConfig(raw = {}, { env = process.env } = {}) {
1522
1635
  // v1.5.0 routing knobs below; v1.5.3 removed minInjectConfidence entirely.
1523
1636
  autoSpaceFollow: contextAutoSpaceFollow,
1524
1637
  autoRolloverEnabled: contextAutoRolloverEnabled,
1638
+ handoffClearRatio: contextHandoffClearRatio,
1525
1639
  autoRolloverThreshold: contextAutoRolloverThreshold,
1526
1640
  nativeTokenLimit: contextNativeTokenLimit,
1527
1641
  liveCompact: {
@@ -1531,6 +1645,13 @@ function buildResolvedConfig(raw = {}, { env = process.env } = {}) {
1531
1645
  tailChars: liveCompactTailChars,
1532
1646
  maxNodesPerRequest: liveCompactMaxNodesPerRequest,
1533
1647
  },
1648
+ smartPrune: {
1649
+ enabled: smartPruneEnabled,
1650
+ threshold: smartPruneThreshold,
1651
+ keepRecentTurns: smartPruneKeepRecentTurns,
1652
+ minChars: smartPruneMinChars,
1653
+ maxNodes: smartPruneMaxNodes,
1654
+ },
1534
1655
  requireExplicitConsentForTransfer: contextRequireExplicitConsentForTransfer,
1535
1656
  },
1536
1657
  temp: { ttlDays: tempTtlDays, promotionWindowDays: tempPromotionWindowDays },
@@ -0,0 +1,188 @@
1
+ /**
2
+ * v1.7.3 (module 1): PHYSICAL context pruning with pointers.
3
+ *
4
+ * The host's `compaction-basic` summarises old history with a MODEL CALL: it costs
5
+ * tokens, it is slow, and its output is a lossy paraphrase that cannot be audited.
6
+ * This module folds instead of summarising:
7
+ *
8
+ * old turn (8 000 chars of tool output)
9
+ * → `[System: 此段包含 N 轮关于 [tag] 的细节,已折叠。原文 ID: ev_xxx。若需要,请使用 recall 工具检索。]`
10
+ *
11
+ * The original bytes are untouched in the raw log and still reachable through
12
+ * `deep_raw` / `recall`, so folding is REVERSIBLE in a way a summary is not. Nothing
13
+ * here sends a request to a provider: the only thing it spends is CPU.
14
+ *
15
+ * Invariants (a violation corrupts the conversation, so they are enforced here):
16
+ * - a node is replaced ON THE SURFACE ONLY: the log keeps the original event and a
17
+ * `compaction/prune` record explains what was shadowed and why;
18
+ * - `tool/call` nodes are never rewritten, so every surviving `tool/result` still
19
+ * has its call (and a folded result keeps its call id in the pointer context);
20
+ * - the most recent `keepRecentTurns` user turns are untouchable — the model must
21
+ * always see what was just asked;
22
+ * - the pointer is never empty: an empty replacement would look like the turn was
23
+ * deleted, which is exactly the failure mode this is meant to avoid.
24
+ */
25
+
26
+ export const FOLD_MARKER = '[System: 此段包含';
27
+ /** Below this, folding a node saves nothing worth the risk. */
28
+ export const FOLD_MIN_CHARS = 1200;
29
+ /** Hard ceiling on how much one request may fold, so pruning cannot snowball. */
30
+ export const FOLD_MAX_NODES = 8;
31
+
32
+ /**
33
+ * The pointer text. Kept deliberately short (≈120 chars): the whole point is that it
34
+ * is much smaller than what it replaces.
35
+ *
36
+ * @param {{turns?: number, tags?: string[], eventId?: string|null, turnId?: string|null, tool?: string|null}} input
37
+ */
38
+ export function foldPointer({ turns = 1, tags = [], eventId = null, turnId = null, tool = null } = {}) {
39
+ const label = (Array.isArray(tags) ? tags : []).filter((tag) => typeof tag === 'string' && tag.length > 0).slice(0, 2);
40
+ const topic = label.length > 0 ? label.map((tag) => `[${tag}]`).join('') : '[未标注]';
41
+ const turnWord = Number(turns) > 1 ? `${Number(turns)} 轮` : '1 轮';
42
+ const ref = eventId ? `ev_${String(eventId).replace(/^ev_/, '')}` : turnId ? `raw:${turnId}` : 'unknown';
43
+ const toolHint = tool ? `(${tool} 的工具输出)` : '';
44
+ return `${FOLD_MARKER}${turnWord}关于 ${topic} 的细节${toolHint},已折叠。原文 ID: ${ref}。若需要,请使用 recall 工具检索。]`;
45
+ }
46
+
47
+ function textOfBlocks(content) {
48
+ const blocks = Array.isArray(content) ? content : [];
49
+ let total = 0;
50
+ for (const block of blocks) {
51
+ if (block && typeof block.text === 'string') total += block.text.length;
52
+ }
53
+ return total;
54
+ }
55
+
56
+ function messageOf(session, seq) {
57
+ try {
58
+ const event = typeof session?.eventAt === 'function' ? session.eventAt(seq) : null;
59
+ if (!event) return null;
60
+ const message = typeof session.deriveEventMessage === 'function' ? session.deriveEventMessage(event) : null;
61
+ return { event, message };
62
+ } catch {
63
+ return null;
64
+ }
65
+ }
66
+
67
+ /**
68
+ * Which surface nodes are eligible to be folded.
69
+ *
70
+ * Separated from the mutation so the decision is testable without a host session and
71
+ * so the caller can log what WOULD happen at a dry run.
72
+ *
73
+ * @param {object} session host Session (`surface.nodes`, `eventAt`, `deriveEventMessage`)
74
+ * @param {{keepRecentTurns?: number, minChars?: number, maxNodes?: number, describe?: Function}} options
75
+ * @returns {{candidates: object[], protectedFrom: number|null, scanned: number}}
76
+ */
77
+ export function planSmartPrune(session, options = {}) {
78
+ const keepRecentTurns = Math.max(0, Number(options.keepRecentTurns ?? 3));
79
+ const minChars = Math.max(0, Number(options.minChars ?? FOLD_MIN_CHARS));
80
+ const maxNodes = Math.max(1, Number(options.maxNodes ?? FOLD_MAX_NODES));
81
+ const nodes = Array.isArray(session?.surface?.nodes) ? session.surface.nodes : [];
82
+
83
+ // The keep-window is measured in USER turns, not nodes: one turn may be a dozen
84
+ // tool results, and protecting only N nodes would fold the question itself.
85
+ let protectedFrom = null;
86
+ if (keepRecentTurns > 0) {
87
+ let seen = 0;
88
+ for (let index = nodes.length - 1; index >= 0; index -= 1) {
89
+ const node = messageOf(session, nodes[index]);
90
+ if (!node) continue;
91
+ if (node.event?.type === 'user/message') {
92
+ seen += 1;
93
+ if (seen >= keepRecentTurns) {
94
+ protectedFrom = index;
95
+ break;
96
+ }
97
+ }
98
+ }
99
+ }
100
+
101
+ const candidates = [];
102
+ let scanned = 0;
103
+ for (let index = 0; index < nodes.length; index += 1) {
104
+ if (protectedFrom !== null && index >= protectedFrom) break;
105
+ const seq = nodes[index];
106
+ const found = messageOf(session, seq);
107
+ if (!found) continue;
108
+ const { event, message } = found;
109
+ scanned += 1;
110
+ // A tool/call has no text and its pair must stay intact.
111
+ if (event?.type === 'tool/call') continue;
112
+ if (!message || !Array.isArray(message.content)) continue;
113
+ const chars = textOfBlocks(message.content);
114
+ if (chars < minChars) continue;
115
+ const already = message.content.some(
116
+ (block) => block && typeof block.text === 'string' && block.text.startsWith(FOLD_MARKER),
117
+ );
118
+ if (already) continue;
119
+ const described = typeof options.describe === 'function' ? options.describe({ seq, event, message, chars }) : null;
120
+ candidates.push({
121
+ seq,
122
+ type: event?.type ?? 'user/message',
123
+ chars,
124
+ eventId: described?.eventId ?? null,
125
+ turnId: described?.turnId ?? null,
126
+ tags: Array.isArray(described?.tags) ? described.tags : [],
127
+ tool: typeof described?.tool === 'string' ? described.tool : event?.data?.name ?? null,
128
+ message,
129
+ });
130
+ if (candidates.length >= maxNodes) break;
131
+ }
132
+ // Largest first: folding big nodes is where the tokens are, and folding many small
133
+ // ones costs more surface churn for the same saving.
134
+ candidates.sort((left, right) => right.chars - left.chars);
135
+ return { candidates, protectedFrom, scanned };
136
+ }
137
+
138
+ /**
139
+ * Apply the plan. One node at a time, each through the host's surface-replace
140
+ * protocol; a failure on one node never aborts the rest (pruning is best-effort,
141
+ * whereas a half-written surface would be corruption).
142
+ *
143
+ * @returns {{folded:number, charsBefore:number, charsAfter:number, pointers:object[], failed:string|null, scanned:number}}
144
+ */
145
+ export function smartPruneSession(session, options = {}) {
146
+ const report = { folded: 0, charsBefore: 0, charsAfter: 0, pointers: [], failed: null, scanned: 0 };
147
+ if (!session || typeof session.append !== 'function') return report;
148
+ let plan;
149
+ try {
150
+ plan = planSmartPrune(session, options);
151
+ } catch (error) {
152
+ report.failed = error?.message ?? String(error);
153
+ return report;
154
+ }
155
+ report.scanned = plan.scanned;
156
+ const tagCount = Math.max(1, Number(options.turnsPerPointer ?? 1));
157
+ for (const candidate of plan.candidates) {
158
+ const pointer = foldPointer({
159
+ turns: tagCount,
160
+ tags: candidate.tags,
161
+ eventId: candidate.eventId,
162
+ turnId: candidate.turnId,
163
+ tool: candidate.tool,
164
+ });
165
+ const content = [{ type: 'text', text: pointer }];
166
+ try {
167
+ session.append('compaction/prune', {
168
+ shadowedRange: { start: candidate.seq, end: candidate.seq },
169
+ shadowedSeqs: [candidate.seq],
170
+ shadowedTokenCount: Math.ceil(candidate.chars / 4),
171
+ reason: 'hippocampus:smart-context-prune',
172
+ pointer,
173
+ });
174
+ session.append(
175
+ candidate.type,
176
+ { ...(candidate.message?.data ?? null), ...(options.eventData?.(candidate) ?? {}), message: { ...candidate.message, content } },
177
+ { surfaceOp: { op: 'replace', startSeq: candidate.seq, endSeq: candidate.seq }, sourceEventSeqs: [candidate.seq] },
178
+ );
179
+ report.folded += 1;
180
+ report.charsBefore += candidate.chars;
181
+ report.charsAfter += pointer.length;
182
+ report.pointers.push({ seq: candidate.seq, eventId: candidate.eventId, chars: candidate.chars, pointer });
183
+ } catch (error) {
184
+ report.failed = error?.message ?? String(error);
185
+ }
186
+ }
187
+ return report;
188
+ }
@@ -116,3 +116,33 @@ export function rehandoffDecision({ markerRatio = null, projectedRatio = 0, same
116
116
  if (projectedRatio - base >= REHANDOFF_DELTA) return { rehandoff: true, reason: 'pressure-growth' };
117
117
  return { rehandoff: false, reason: 'below-delta' };
118
118
  }
119
+
120
+ /**
121
+ * v1.7.4: when does an ACTIVE handoff marker stop being true?
122
+ *
123
+ * `checkHandoff()` used to run only on the fail-fast path, and since 1.6.3 a
124
+ * conversation keeps its session id across a handoff, so the stale-session branch
125
+ * never fired either: once a marker went active NOTHING cleared it. The prompt then
126
+ * announced "context near the native window limit" on every single turn — even after
127
+ * the host compacted this conversation down to ~10% — and the model duly handed off
128
+ * early. Relief is observable: pressure below half the window, or a 30-point drop
129
+ * against the marker's own ratio, means the marker is no longer telling the truth.
130
+ */
131
+ export const HANDOFF_CLEAR_RATIO = 0.5;
132
+
133
+ /** How far pressure must fall below the marker's own ratio to count as relief. */
134
+ export const RELIEF_COLLAPSE_DELTA = 0.3;
135
+
136
+ /**
137
+ * @param {{ markerRatio?: number|null, projectedRatio?: number, threshold?: number }} input
138
+ * @returns {{ relieved: boolean, reason: string }}
139
+ */
140
+ export function relievedDecision({ markerRatio = null, projectedRatio = 0, threshold = HANDOFF_CLEAR_RATIO }) {
141
+ const limit = Number.isFinite(threshold) && threshold > 0 && threshold < 1 ? threshold : HANDOFF_CLEAR_RATIO;
142
+ const base = Number.isFinite(markerRatio) && markerRatio > 0 ? markerRatio : null;
143
+ if (projectedRatio <= limit) return { relieved: true, reason: 'below-clear-ratio' };
144
+ if (base !== null && projectedRatio <= base - RELIEF_COLLAPSE_DELTA) {
145
+ return { relieved: true, reason: 'pressure-collapsed' };
146
+ }
147
+ return { relieved: false, reason: 'pressure-still-high' };
148
+ }
package/src/errors.js CHANGED
@@ -150,6 +150,10 @@ export const ErrorCodes = Object.freeze({
150
150
  * paying for the prompt.
151
151
  */
152
152
  CONTEXT_EXCEEDED: 'MEM_E_CONTEXT_EXCEEDED',
153
+ // v1.7.3 (module 3): a caller asked for a specific record that carries a
154
+ // `sensitive:*` tag without passing `allow_sensitive`. Refusing loudly beats
155
+ // returning "[withheld]" and letting the caller believe the record is gone.
156
+ SENSITIVE_ACCESS_DENIED: 'MEM_E_SENSITIVE_ACCESS_DENIED',
153
157
  });
154
158
 
155
159
  export class MemoryError extends Error {