dsh-layers-hippocampus 1.7.3 → 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.
package/CHANGELOG.md CHANGED
@@ -4,6 +4,55 @@ 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.7.4] — 2026-11-28
8
+
9
+ **图谱从「640×320 里挤沙子」变成可缩放的布局世界;节点按事件数自动收敛到 80;
10
+ recall 时命中的标签会真的亮起来。**
11
+
12
+ - **Fixed — 布局塌缩与画死边界(`ui/client.js`)**。旧实现把画布写死成 `640×320`,
13
+ 再在 640 宽里做力导向:向心力 `((width/2 - x)/width) * 2 * alpha` 在边缘处接近
14
+ `0.9*alpha`,远强于 40–80px 距离上的斥力 `900/d²`,于是所有点被吸回中心;
15
+ 布局和拖拽又各自 `Math.max(24, Math.min(width - 24, ...))`,节点永远出不了那个框。
16
+ 现在:坐标系换成**布局世界**(`layoutWorld()` 按节点数放大,最多 3×),斥力按面积自适应
17
+ (`0.9 * spacing²`),向心力改成温和弹簧(`0.02 * alpha`),最小距离 6px 防爆,
18
+ 标签留白 `GRAPH_LABEL_ROOM = 26`,最大速度收敛即早停;容器用 `ResizeObserver` 测量,
19
+ `viewBox` 跟着容器走、节点与文字保持固定像素大小;初始 `fitView()` 一屏看全,
20
+ 拖拽节点时**画布不动**,节点跟随指针、可以停在 world 之外 `GRAPH_DRAG_GUTTER = 240` 的走廊里
21
+ (「适应视图」或双击空白就能把它找回来);画布只在拖空白处平移——
22
+ **节点可以被拖出可见范围**;新增「适应视图」按钮与虚线世界边界,双击空白仍然重置。
23
+ 规划期曾试过「指针进边缘 28px 就自动平移视野」,实测在同一帧里先按旧视图换算指针坐标、
24
+ 再平移视图,节点与指针失配 ⇒ 每动一下就朝一个方向猛跳一段。该做法已删除,
25
+ 拖拽节点**永不**改动视图变换(回归测试直接断言这段代码里不出现 `applyView()`)。
26
+ - **Fixed — 光效永远不亮(活动环记错了实例)**。活动环的写入原本挂在
27
+ `Memory#_recallLocal` 末尾,但多空间 profile 里 `memory.recall()` 会经
28
+ `spaces.run()` 路由、跨空间读还会扇出到每个空间自己的 `Memory` 实例——真正
29
+ 执行的那一个不是路由读的那个,于是 `/api/hippocampus/activity` 永远是空数组,
30
+ 图谱一次都不会亮。现在改为在 `runtime.recall` 这一个边界统一记
31
+ (`index.js#noteRecallActivity`,单空间 / 跨空间 / 指定 `targetSpaceId` 三条路
32
+ 都覆盖,按应答空间落到各自环里),并新增运行时级回归测试
33
+ `test/v174.activity.test.js`「a real runtime recall feeds the ring the panel polls」。
34
+ - **Added — 节点上限 80(`src/graph.js#trimGraph`)**。`graphMaxNodes` 默认 80(10–2000),
35
+ 超出时按**事件数最少优先**隐藏(`events` ASC → `weight` ASC → `id` ASC),
36
+ 边同步过滤并按 weight 截断;payload 增加 `totalNodes` / `droppedNodes` / `droppedEdges`,
37
+ 面板显示「+N 节点未显示(按事件数从少到多隐藏)」。**事件多的节点是记忆里更扎实的那些**,
38
+ 所以先淘汰稀疏点而不是砍断主干。
39
+ - **Added — recall 光效(`src/activity.js` + `GET /api/hippocampus/activity`)**。
40
+ `_recallLocal` 在读取成功后 best-effort 记一条活动(`kind: 'recall'`,附 tags / eventIds,
41
+ `sensitive:` 与 `privacy:` 标签在入口就被剥离);图谱每 1000ms 拉一次增量
42
+ (页面不可见时跳过),命中的标签**强光呼吸**、1 跳邻居**弱光**,新写入的标签**脉冲 620ms**,
43
+ 2400ms 后自动熄灭。颜色默认跟随主题强调色(`ui.graphGlowPreset: 'accent'`),
44
+ 另有 `vivid` / `warm` 预设与 `ui.graphGlowCustom` 十六进制自定义;白底刺眼时可用
45
+ `ui.graphCanvasTint` 给画布加一层极淡底色;`prefers-reduced-motion` 下只保留静态高亮不脉冲。
46
+ 活动流默认只在内存里(`ui.graphActivityPersist: false`),打开后才落 `state/activity.json`(5s 节流)。
47
+ 节点总开关 `ui.graphGlowEnabled`。
48
+ - **Added — 设置页新增「图谱与光效」组**:节点上限、最大边数、光效开关、预设色、
49
+ 自定义取色器(「恢复跟随预设」一键回到 accent)、画布底色、活动持久化。
50
+ - **Contract**:MEMORY 路由表 9 → **10 条**(新增 `/api/hippocampus/activity`,GET/HEAD);
51
+ 新配置 `graphMaxNodes` 与 `ui.{graphGlowEnabled, graphGlowPreset, graphGlowCustom, graphCanvasTint, graphActivityPersist}`,
52
+ 全部可在设置 UI 改。
53
+ - **Tests**:`test/v174.ui.test.js`(几何纯函数真值断言 + 源码契约)、`test/v174.graph.test.js`、
54
+ `test/v174.activity.test.js`;全量 **591 / 591 通过,92 个测试文件**。
55
+
7
56
  ## [1.7.3] — 2026-11-27
8
57
 
9
58
  **上下文物理折叠、raw 墓碑移位、敏感标签硬拦截,以及交接标记随压力过期:
package/README.md CHANGED
@@ -7,7 +7,7 @@
7
7
 
8
8
  | | |
9
9
  | --- | --- |
10
- | 版本 | **1.7.3** |
10
+ | 版本 | **1.7.4** |
11
11
  | 包名 | `dsh-layers-hippocampus` |
12
12
  | 仓库 | <https://github.com/382quaii/dsh-Layers-Hippocampus> |
13
13
  | 许可证 | MIT |
@@ -253,7 +253,7 @@ raw 层提供三档,覆盖从“只留关键”到“全留”:
253
253
  pnpm add dsh-layers-hippocampus
254
254
 
255
255
  # 或从 GitHub 指定 tag
256
- pnpm add "github:382quaii/dsh-Layers-Hippocampus#v1.7.3"
256
+ pnpm add "github:382quaii/dsh-Layers-Hippocampus#v1.7.4"
257
257
  ```
258
258
 
259
259
  ### 2. 挂到 profile
@@ -1,6 +1,6 @@
1
1
  # @local/dsh-memory — 分层长期记忆 Host 插件
2
2
 
3
- > 版本:**1.7.3** | 全量用例:**571/571** | 运行时依赖:**零**
3
+ > 版本:**1.7.4** | 全量用例:**591/591** | 运行时依赖:**零**
4
4
 
5
5
  给 DSH 智能体一份"活得比会话久"的记忆:**追加式原始日志是唯一真相源**,标签索引、日记、活跃集合全部是可丢弃、可重建的读模型,语义摘要独立于原始日志生死。
6
6
 
@@ -681,7 +681,7 @@ window.__ModuleLoader__.load({
681
681
 
682
682
  运行器带**看门狗**:默认 **60s**(`MEM_TEST_TIMEOUT_MS` 可调)仍未退出,就打印**卡住时正在导入/执行的文件、最后完成的测试名与完成数、活动资源、尚未触发的定时器**,然后 `process.exit(1)`。它不会用 `process.exit(0)` 掩盖超时——挂起即失败。`MEM_TEST_TRACE=1` 可看文件级进度,`MEM_TEST_ONLY=<子串>` 只跑一组。
683
683
 
684
- 571 个用例(88 个文件)覆盖:
684
+ 591 个用例(92 个文件)覆盖:
685
685
 
686
686
  - 索引与标签:重建 digest 一致、行号漂移防护(eventId 不变、行号变)、同义合并、活跃集 cap 挤出、规则变更不改清单、空活跃集降级、top-k 有界有序去重。
687
687
  - 衰减与删除:30 天半衰期、reinforce 移动锚点(不存字段)、仅文本粗筛、标签过滤、维护代切换且旧代可读、boot 检查、压缩不丢记录、并发维护串行化、四阶段删除、archive 可回滚 vs purge 不可、strict 巩固暂停与恢复、任务重放幂等、错误 id 零变更。
package/index.js CHANGED
@@ -57,6 +57,9 @@ import { snippet } from './src/util.js';
57
57
  import { dimensionOf, groupByDimension, stripPhysiology, containsPhysiology } from './src/semantic/dimensions.js';
58
58
  import { isSecretRecord } from './src/privacy.js';
59
59
  import { MEMORY_API, registerMemoryRoutes } from './src/webRoutes.js';
60
+ // v1.7.4: bounded graph projection + the recent activity ring the panel flashes.
61
+ import { trimGraph } from './src/graph.js';
62
+ import { ActivityStore } from './src/activity.js';
60
63
 
61
64
  export const name = 'memory';
62
65
  export const inject = ['tools', 'systemPrompt'];
@@ -76,7 +79,7 @@ export { resolveConfig, DEFAULT_CONFIG };
76
79
  * of letting a raw 404 reach the user.
77
80
  */
78
81
  export const CAPABILITIES = Object.freeze({
79
- version: '1.7.3',
82
+ version: '1.7.4',
80
83
  spaces: true,
81
84
  memories: true,
82
85
  transferConsent: true,
@@ -259,6 +262,7 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
259
262
  policy: options.policy,
260
263
  config: owner.config,
261
264
  spaceId: path.basename(childDir),
265
+ activity: activityFor(path.basename(childDir)),
262
266
  ...multiSpaceExtras(),
263
267
  }),
264
268
  }),
@@ -268,8 +272,31 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
268
272
  dedupe: orchestrator.dedupe ?? null,
269
273
  };
270
274
  };
275
+ // v1.7.4 activity ring: ONE store per physical space, created lazily. The file is
276
+ // opt-in (`ui.graphActivityPersist`) and lives inside that space's OWN state/
277
+ // directory, so two spaces never share a ring. `runtime` does not exist yet while
278
+ // the first Memory is built, hence the small live-config reference. Tags only —
279
+ // ActivityStore strips sensitive:/privacy: and caps both arrays.
280
+ let runtimeRef = null;
281
+ const activityStores = new Map();
282
+ const activityConfig = () => runtimeRef?.config ?? config;
283
+ const activityFilePath = (spaceId) => {
284
+ if (activityConfig().ui?.graphActivityPersist !== true) return null;
285
+ const root = activityConfig().dataDir;
286
+ const dir = !spaceId || spaceId === 'default' ? root : path.join(root, 'spaces', String(spaceId));
287
+ return path.join(dir, 'state', 'activity.json');
288
+ };
289
+ const activityFor = (spaceId) => {
290
+ const key = spaceId === null || spaceId === undefined || spaceId === '' ? 'default' : String(spaceId);
291
+ let store = activityStores.get(key);
292
+ if (!store) {
293
+ store = new ActivityStore({ limit: 64, file: activityFilePath(key === 'default' ? null : key), clock });
294
+ activityStores.set(key, store);
295
+ }
296
+ return store;
297
+ };
271
298
  // `let` (not const): a failed bootstrap can be retried by rebuilding the facade.
272
- let memory = new Memory({ dataDir: config.dataDir, policy: options.policy, config: options.config, clock, ...multiSpaceExtras() });
299
+ let memory = new Memory({ dataDir: config.dataDir, policy: options.policy, config: options.config, clock, activity: activityFor(null), ...multiSpaceExtras() });
273
300
  // v1.5.6: engine warnings (currently MEM_E_AUTO_TAG_MISS) go to the Host log.
274
301
  memory.setWarnHook?.((code, message, details) => {
275
302
  ctx?.logger?.warn?.(`hippocampus: ${code} ${message}`, details);
@@ -279,6 +306,11 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
279
306
  const runtime = {
280
307
  config,
281
308
  memory,
309
+ // v1.7.4: recent recall/capture hints. One ring per physical space; `activity`
310
+ // is the default-space store handed to the Memory facade above.
311
+ activity: activityFor(null),
312
+ activityStores,
313
+ activityFor,
282
314
  logger: ctx?.logger ?? null,
283
315
  /** Raw (unresolved) config: re-merging a patch must not bake in defaults. */
284
316
  rawConfig: cloneRaw(raw ?? config),
@@ -308,6 +340,15 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
308
340
  /** Set by apply(): persists config patches through configEditor. */
309
341
  persist: null,
310
342
  };
343
+ runtimeRef = runtime;
344
+
345
+ /** Rebind the rings to the current dataDir / persistence flag (cosmetic state). */
346
+ runtime.resetActivityStores = () => {
347
+ activityStores.clear();
348
+ runtime.activity = activityFor(null);
349
+ runtime.activityStores = activityStores;
350
+ if (runtime.memory) runtime.memory.activity = runtime.activity;
351
+ };
311
352
 
312
353
  const migrationRunner = new MigrationRunner({
313
354
  stateFile: path.join(config.dataDir, 'state', 'migration.json'),
@@ -1381,6 +1422,36 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
1381
1422
  * Reads during startup. A migration has a source of truth that is still valid:
1382
1423
  * the legacy directory. Serving from it beats both an empty answer and a stall.
1383
1424
  */
1425
+ /**
1426
+ * v1.7.4: the panel's glow feed, recorded at the RUNTIME boundary on purpose.
1427
+ *
1428
+ * `memory.recall()` does not necessarily run on this facade: with multi-space it
1429
+ * routes through `spaces.run()`, and a cross-space recall fans out to per-space
1430
+ * `Memory` instances. A hook inside `Memory#_recallLocal` therefore only fires for
1431
+ * whichever instance happened to serve the call — in a two-space profile the
1432
+ * default ring stayed empty and the graph never lit up. Recording here means one
1433
+ * place, one store per answering space, and the same payload shape for every path.
1434
+ * Tags only: ActivityStore strips `sensitive:` / `privacy:` before they can reach
1435
+ * the panel, and a broken ring must never affect the recall result itself.
1436
+ */
1437
+ const noteRecallActivity = (result, spaceId = null) => {
1438
+ try {
1439
+ const tags = [];
1440
+ const eventIds = [];
1441
+ for (const hit of result?.hits ?? []) {
1442
+ for (const tag of hit?.tags ?? []) {
1443
+ const value = typeof tag === 'string' ? tag : tag?.tag;
1444
+ if (typeof value === 'string' && value) tags.push(value);
1445
+ }
1446
+ if (typeof hit?.eventId === 'string' && hit.eventId) eventIds.push(hit.eventId);
1447
+ }
1448
+ if (tags.length === 0 && eventIds.length === 0) return;
1449
+ runtime.activityFor(spaceId ?? result?.spaceId ?? null).record({ kind: 'recall', tags, eventIds, source: 'recall' });
1450
+ } catch {
1451
+ // A hint is cosmetic; recall itself must never fail because of it.
1452
+ }
1453
+ };
1454
+
1384
1455
  runtime.recall = async (query) => {
1385
1456
  if (runtime.phase === 'ready') {
1386
1457
  runtime.recordToolCall();
@@ -1395,9 +1466,13 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
1395
1466
  runtime.multiSpaceAvailable?.() &&
1396
1467
  memory.spaces.status().ids.length > 1
1397
1468
  ) {
1398
- return memory.recallAcrossSpaces(query ?? {});
1469
+ const result = await memory.recallAcrossSpaces(query ?? {});
1470
+ noteRecallActivity(result, null);
1471
+ return result;
1399
1472
  }
1400
- return memory.recall(query);
1473
+ const result = await memory.recall(query);
1474
+ noteRecallActivity(result, query && typeof query === 'object' ? query.targetSpaceId ?? null : null);
1475
+ return result;
1401
1476
  }
1402
1477
  if (runtime.legacy) {
1403
1478
  runtime.recordToolCall();
@@ -1601,15 +1676,18 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
1601
1676
  return {
1602
1677
  ok: false,
1603
1678
  ...view,
1604
- graph: { available: false, nodes: [], edges: [], totalEdges: 0, limit: runtime.config.graphMaxEdges },
1679
+ graph: { available: false, nodes: [], edges: [], totalEdges: 0, limit: runtime.config.graphMaxEdges, maxNodes: runtime.config.graphMaxNodes },
1605
1680
  tagTree: { available: false, ghosts: [] },
1606
1681
  };
1607
1682
  }
1608
1683
  try {
1609
- const { spaceId: selected, graph, tagTree } = await memory.graphForSpace({
1684
+ const { spaceId: selected, graph: rawGraph, tagTree } = await memory.graphForSpace({
1610
1685
  targetSpaceId: spaceId ?? undefined,
1611
1686
  limit: runtime.config.graphMaxEdges,
1612
1687
  });
1688
+ // v1.7.4: the cache keeps its full projection; the ROUTE gets a bounded copy so
1689
+ // one huge graph can never stall the panel. trimGraph is pure.
1690
+ const graph = trimGraph(rawGraph, { maxNodes: runtime.config.graphMaxNodes, maxEdges: runtime.config.graphMaxEdges });
1613
1691
  return { ok: true, phase: runtime.phase, state: runtime.phase, spaceId: selected, graph, tagTree };
1614
1692
  } catch (error) {
1615
1693
  return {
@@ -1617,12 +1695,23 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
1617
1695
  ...view,
1618
1696
  spaceId,
1619
1697
  error: asMemoryError(error).toJSON(),
1620
- graph: { available: false, nodes: [], edges: [], limit: runtime.config.graphMaxEdges },
1698
+ graph: { available: false, nodes: [], edges: [], limit: runtime.config.graphMaxEdges, maxNodes: runtime.config.graphMaxNodes },
1621
1699
  tagTree: { available: false, ghosts: [] },
1622
1700
  };
1623
1701
  }
1624
1702
  };
1625
1703
 
1704
+ /**
1705
+ * v1.7.4 activity route payload: the default or named space's recent ring.
1706
+ * `since` is an exclusive seq cursor, so the panel polls for just the new flips.
1707
+ * Read-only and store-independent: a hint never blocks on bootstrap.
1708
+ */
1709
+ runtime.activityPayload = ({ spaceId = null, since = 0, limit = 64 } = {}) => {
1710
+ const store = runtime.activityFor(spaceId);
1711
+ const recent = store.recent({ since, limit });
1712
+ return { ok: true, spaceId: spaceId ?? 'default', items: recent.items, cursor: recent.cursor, now: recent.now };
1713
+ };
1714
+
1626
1715
  /** Global SpaceSelector data source (root router: every physical space). */
1627
1716
  runtime.spaceList = () =>
1628
1717
  runtime.phase === 'ready'
@@ -1868,7 +1957,13 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
1868
1957
  * needs a restart.
1869
1958
  */
1870
1959
  runtime.applyConfig = (next) => {
1960
+ const previous = runtime.config;
1871
1961
  runtime.config = next;
1962
+ // v1.7.4: the rings' file binding depends on dataDir + ui.graphActivityPersist.
1963
+ // Rebinding is enough; the hint history itself is disposable.
1964
+ const rebindActivity =
1965
+ (previous.ui?.graphActivityPersist === true) !== (next.ui?.graphActivityPersist === true) ||
1966
+ path.resolve(previous.dataDir) !== path.resolve(next.dataDir);
1872
1967
  // Retrieval reads `memory.policy` on every call. The resolved policy is
1873
1968
  // deep-frozen, so replace it with a shallow copy carrying the new topK
1874
1969
  // instead of mutating a frozen object (which throws in strict mode).
@@ -1885,6 +1980,7 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
1885
1980
  // facade (and every open child space) instead of waiting for a reload: the
1886
1981
  // settings page promises "保存后立即生效".
1887
1982
  if (liveMemory) liveMemory.applyLiveConfig(toMemoryOptions(next).config);
1983
+ if (rebindActivity) runtime.resetActivityStores();
1888
1984
  emit({ type: 'config', config: uiConfig(next) });
1889
1985
  return next;
1890
1986
  };
@@ -1971,10 +2067,13 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
1971
2067
  } catch {
1972
2068
  /* the old store is read-mostly */
1973
2069
  }
1974
- memory = new Memory({ dataDir: next.dataDir, policy: nextOptions.policy, config: nextOptions.config, clock, ...multiSpaceExtras() });
2070
+ memory = new Memory({ dataDir: next.dataDir, policy: nextOptions.policy, config: nextOptions.config, clock, activity: activityFor(null), ...multiSpaceExtras() });
1975
2071
  runtime.memory = memory;
1976
2072
  runtime.config = next;
1977
2073
  runtime.rawConfig = merged;
2074
+ // The rings are bound to physical dirs; after the swap they must follow the new
2075
+ // dataDir (hints are cosmetic, so dropping the old in-memory ring is fine).
2076
+ runtime.resetActivityStores();
1978
2077
  await memory.init();
1979
2078
  if (runtime.scheduler) memory.attachScheduler(runtime.scheduler);
1980
2079
  // The runner still points at the OLD state file; rebase it on the new dataDir
@@ -2040,7 +2139,7 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
2040
2139
  } catch {
2041
2140
  /* a half-open store must not block the rebuild */
2042
2141
  }
2043
- memory = new Memory({ dataDir: config.dataDir, policy: options.policy, config: options.config, clock, ...multiSpaceExtras() });
2142
+ memory = new Memory({ dataDir: config.dataDir, policy: options.policy, config: options.config, clock, activity: runtime.activity, ...multiSpaceExtras() });
2044
2143
  runtime.memory = memory;
2045
2144
  memory.setHandoffPresetProvider?.(() => runtime.agentPreset);
2046
2145
  emit({ type: 'retry', phase: runtime.phase });
@@ -2348,6 +2447,9 @@ function uiConfig(config) {
2348
2447
  dreamIdleMinutes: config.dreamIdleMinutes,
2349
2448
  enableReflection: config.enableReflection,
2350
2449
  graphMaxEdges: config.graphMaxEdges,
2450
+ graphMaxNodes: config.graphMaxNodes,
2451
+ // v1.7.4 presentation knobs (glow / canvas tint) + optional activity persistence.
2452
+ ui: config.ui,
2351
2453
  storageBudgetMb: config.storageBudgetMb,
2352
2454
  maxRecallTopK: config.maxRecallTopK,
2353
2455
  retrieval: { topK: config.retrieval.topK },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-layers-hippocampus",
3
- "version": "1.7.3",
3
+ "version": "1.7.4",
4
4
  "private": false,
5
5
  "description": "Layered long-term memory for DeepSeek Harness: append-only event log, rebuildable tag index, day diaries, independent semantic layer, L2.5 trend quarantine, offline knowledge graph and a Web UI panel.",
6
6
  "type": "module",
@@ -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
+ }