dsh-layers-hippocampus 1.7.0 → 1.7.2

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/README.md CHANGED
@@ -7,7 +7,7 @@
7
7
 
8
8
  | | |
9
9
  | --- | --- |
10
- | 版本 | **1.7.0** |
10
+ | 版本 | **1.7.2** |
11
11
  | 包名 | `dsh-layers-hippocampus` |
12
12
  | 仓库 | <https://github.com/382quaii/dsh-Layers-Hippocampus> |
13
13
  | 许可证 | MIT |
@@ -124,6 +124,27 @@
124
124
  `capabilities.externalSeams` 会如实报告 `{wired, source}`,所以「没装」是可见事实。
125
125
  **高峰期不丢任务**:LLM 蒸馏在高峰只被写入持久化队列并在谷时唤醒,不是跳过。
126
126
 
127
+ ### 设置页:左侧目录 + 五个分组(1.7.2)
128
+
129
+ 17 张卡片按用途收进五组,左侧竖排目录固定在视口、点击平滑跳转、滚动自动高亮:
130
+ **身份与行为** / **上下文与注入** / **摄入与蒸馏** / **留存与归档** / **空间与存储**。
131
+ 卡片本身逐字搬迁,控件与校验行为零变化;简洁模式仍只显示四组(`ingest` 整组不渲染)。
132
+
133
+ ### 提示预算治理:任务 / 专家模式(1.7.1)
134
+
135
+ 记忆插件过去只回答「记住什么」,不回答「该不该现在说」。1.7.1 把注入面收紧:
136
+
137
+ - **摘要卫生(常开)**:注入的摘要会先去掉写那一刻的簿记数字(`events 348`、`reviews due 337`、
138
+ 版本号),再补一个 `(snapshot …)` 时间戳。**带教训的数字不会被删**——`854,668 + 256,000 >
139
+ 1,048,576` 这类结论原样保留。
140
+ - **提示标签单向静默(任务模式)**:同一标签连续 `context.hintsIdleSilenceAfter`(默认 8)次出现
141
+ 且一次都没换来 `recall`,就永久不再出现;之后偶然被召回也不会自动复活。
142
+ 看不出来源时用 `/memory status` 查看被静默的标签。
143
+ - **`[Task State]` 当前状态行(任务模式)**:Prompt 末尾一行
144
+ `repo@branch · HEAD <sha7> · window 291k/1048k (host)`,不 spawn git、硬上限 300 字符。
145
+ - **`context.mode`**:`task`(默认)启用上面两项;`expert` 保留全部提示、不注入状态行。
146
+ 设置页「上下文窗口」可切换,简洁模式下同样可改。
147
+
127
148
  ### 全链路记忆:写入归并 / 检索联想 / 自动指针(1.6.9)
128
149
 
129
150
  - **写入时归并实体**:`entity:` 标签先查别名字典,再按**子串包含**(已有 `entity:红薯`,写入
@@ -232,7 +253,7 @@ raw 层提供三档,覆盖从“只留关键”到“全留”:
232
253
  pnpm add dsh-layers-hippocampus
233
254
 
234
255
  # 或从 GitHub 指定 tag
235
- pnpm add "github:382quaii/dsh-Layers-Hippocampus#v1.7.0"
256
+ pnpm add "github:382quaii/dsh-Layers-Hippocampus#v1.7.2"
236
257
  ```
237
258
 
238
259
  ### 2. 挂到 profile
@@ -303,7 +324,7 @@ node scripts/wait-for-routes.mjs
303
324
  ### 6. 验证
304
325
 
305
326
  ```bash
306
- npm test # 进程内全量用例(548 个)
327
+ npm test # 进程内全量用例(555 个)
307
328
  npm run check # 语法检查 + 全量测试
308
329
  ```
309
330
 
@@ -1,6 +1,6 @@
1
1
  # @local/dsh-memory — 分层长期记忆 Host 插件
2
2
 
3
- > 版本:**1.7.0** | 全量用例:**548/548** | 运行时依赖:**零**
3
+ > 版本:**1.7.2** | 全量用例:**555/555** | 运行时依赖:**零**
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
- 548 个用例(86 个文件)覆盖:
684
+ 555 个用例(87 个文件)覆盖:
685
685
 
686
686
  - 索引与标签:重建 digest 一致、行号漂移防护(eventId 不变、行号变)、同义合并、活跃集 cap 挤出、规则变更不改清单、空活跃集降级、top-k 有界有序去重。
687
687
  - 衰减与删除:30 天半衰期、reinforce 移动锚点(不存字段)、仅文本粗筛、标签过滤、维护代切换且旧代可读、boot 检查、压缩不丢记录、并发维护串行化、四阶段删除、archive 可回滚 vs purge 不可、strict 巩固暂停与恢复、任务重放幂等、错误 id 零变更。
package/index.js CHANGED
@@ -27,6 +27,7 @@
27
27
  * must resolve standalone under pnpm's strict node_modules layout.
28
28
  */
29
29
 
30
+ import fs from 'node:fs';
30
31
  import path from 'node:path';
31
32
  import { resolveConfig, toMemoryOptions, DEFAULT_CONFIG, multiSpaceActive, multiSpaceReason } from './src/config.js';
32
33
  import { extractEntities } from './src/utils/RegexExtractor.js';
@@ -35,8 +36,10 @@ import { MigrationRunner } from './src/migrationRunner.js';
35
36
  import { CronScheduler } from './src/scheduler.js';
36
37
  import { asMemoryError, ErrorCodes, MemoryError } from './src/errors.js';
37
38
  import { Memory, turnFromSessionEvent } from './src/memory.js';
38
- import { composePrompt, renderActiveTask, renderPointers } from './src/utils/promptLayout.js';
39
+ import { composePrompt, renderActiveTask, renderPointers, renderStateLine } from './src/utils/promptLayout.js';
39
40
  import { renderMemoryHints, selectRelevantTags } from './src/utils/memoryHints.js';
41
+ import { HintFeedbackStore } from './src/hintFeedback.js';
42
+ import { hygienicSummary, stripVolatile } from './src/promptHygiene.js';
40
43
  import { HostBridge } from './src/hostBridge.js';
41
44
  import { isLowValley, nextLowValleyStart, windowInfo } from './src/priceWindow.js';
42
45
  import { DreamTimer } from './src/dreamTimer.js';
@@ -65,7 +68,7 @@ export { resolveConfig, DEFAULT_CONFIG };
65
68
  * of letting a raw 404 reach the user.
66
69
  */
67
70
  export const CAPABILITIES = Object.freeze({
68
- version: '1.7.0',
71
+ version: '1.7.2',
69
72
  spaces: true,
70
73
  memories: true,
71
74
  transferConsent: true,
@@ -453,6 +456,103 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
453
456
  * by the turn counter, never by a timer.
454
457
  */
455
458
  runtime.pointers = { armed: true, userTurns: 0, lastSignature: null, lastAt: null, injected: 0 };
459
+ /**
460
+ * v1.7.1: the hint feedback loop (task mode).
461
+ *
462
+ * Constructed lazily (the state directory does not exist until the memory opens) and
463
+ * only in task mode; expert mode keeps every hint as-is. Failure to create the store
464
+ * must never break prompt assembly, so construction is guarded and `null` means
465
+ * "no silencing" everywhere below.
466
+ */
467
+ runtime.hintFeedback = null;
468
+ runtime.ensureHintFeedback = () => {
469
+ if (runtime.hintFeedback) return runtime.hintFeedback;
470
+ try {
471
+ const stateDir = memory?.paths?.state;
472
+ if (typeof stateDir !== 'string' || stateDir.length === 0) return null;
473
+ runtime.hintFeedback = new HintFeedbackStore({
474
+ file: `${stateDir}/hint-feedback.json`,
475
+ clock: { now: () => memory.clock.now() },
476
+ });
477
+ runtime.hintFeedback.load();
478
+ return runtime.hintFeedback;
479
+ } catch {
480
+ return null;
481
+ }
482
+ };
483
+ // A functional no-op so promptState() never needs a null check at the call site.
484
+ runtime.hintFeedbackFacade = () => {
485
+ const store = runtime.ensureHintFeedback();
486
+ if (store) return store;
487
+ return { filter: (tags) => (Array.isArray(tags) ? tags : []), noteShown: () => ({ silenced: [], changed: false }), noteRecalled: () => ({ changed: false }), status: () => ({ tracked: 0, silenced: 0, silencedTags: [], updatedAt: null }) };
488
+ };
489
+ /**
490
+ * v1.7.1: the ONE current-state line injected in task mode.
491
+ *
492
+ * Memory answers "where have we been"; a build/debug session needs "where am I now".
493
+ * Two facts only, both cheap and both genuinely current:
494
+ * - the repo HEAD (read from .git/HEAD + the loose ref, cached 5s — never a spawn);
495
+ * - the live window pressure the host reported for this turn.
496
+ * Nothing here is a counter that ages badly: HEAD moves and pressure is per-turn.
497
+ */
498
+ runtime.statePointerCache = { at: null, text: '' };
499
+ runtime.gitHead = () => {
500
+ try {
501
+ const dir = process.cwd();
502
+ const headPath = `${dir}/.git/HEAD`;
503
+ if (!fs.existsSync(headPath)) return { branch: null, sha: null };
504
+ const head = String(fs.readFileSync(headPath, 'utf8')).trim();
505
+ if (head.startsWith('ref:')) {
506
+ const ref = head.slice(4).trim();
507
+ const refPath = `${dir}/.git/${ref}`;
508
+ const sha = fs.existsSync(refPath) ? String(fs.readFileSync(refPath, 'utf8')).trim().slice(0, 7) : null;
509
+ return { branch: ref.replace(/^refs\/heads\//, ''), sha };
510
+ }
511
+ return { branch: null, sha: head.slice(0, 7) };
512
+ } catch {
513
+ return { branch: null, sha: null };
514
+ }
515
+ };
516
+ runtime.statePointerText = () => {
517
+ // Expert mode serves the full memory contract, not a task dashboard: the caller
518
+ // gates this too, but the function must not lie when called directly.
519
+ if (runtime.config?.context?.mode === 'expert') return '';
520
+ const pointerConfig = runtime.config?.context?.statePointer ?? {};
521
+ if (pointerConfig.enabled === false) return '';
522
+ const budget = Math.max(60, Number(pointerConfig.maxChars) || 300);
523
+ const now = memory?.clock?.now?.() ?? Date.now();
524
+ // 5s is enough: HEAD cannot move more than once per test run, and a prompt
525
+ // assembly must not stat the repo on every single turn.
526
+ if (runtime.statePointerCache.at !== null && now - runtime.statePointerCache.at < 5000) {
527
+ return runtime.statePointerCache.text;
528
+ }
529
+ const fields = {};
530
+ try {
531
+ const repo = String(process.cwd()).split(/[\\/]/).filter(Boolean).pop() ?? null;
532
+ const { branch, sha } = runtime.gitHead();
533
+ if (repo) fields.repo = branch ? `${repo}@${branch}` : repo;
534
+ if (sha) fields.head = `HEAD ${sha}`;
535
+ } catch {
536
+ /* the task line must never fail the assembly */
537
+ }
538
+ try {
539
+ const session = memory.context.nativeState({ now });
540
+ if (Number.isFinite(Number(session?.tokens)) && Number.isFinite(Number(session?.nativeTokenLimit))) {
541
+ fields.window = `window ${Math.round(Number(session.tokens) / 1000)}k/${Math.round(Number(session.nativeTokenLimit) / 1000)}k (${session.windowSource ?? 'config'})`;
542
+ }
543
+ } catch {
544
+ /* ignore */
545
+ }
546
+ try {
547
+ const lastMaintain = Number(runtime.scheduler?.lastSuccessAt) || null;
548
+ if (lastMaintain) fields.maintained = `maintained ${Math.max(0, Math.round((now - lastMaintain) / 60000))}m ago`;
549
+ } catch {
550
+ /* ignore */
551
+ }
552
+ const text = renderStateLine(fields, { maxChars: budget });
553
+ runtime.statePointerCache = { at: now, text };
554
+ return text;
555
+ };
456
556
  /**
457
557
  * v1.6.3 cold-start state (replaces the v1.6.0 boolean `coldStartPending`).
458
558
  *
@@ -521,7 +621,10 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
521
621
  // summary left with nothing is not rendered at all.
522
622
  const cleaned = [];
523
623
  for (const summary of [...summaries].sort(byConfidence)) {
524
- const text = stripPhysiology(summary.text ?? '');
624
+ // v1.7.1: same counter hygiene as every other injected summary — a trait line
625
+ // that is mostly bookkeeping is dropped, the rest is cleaned.
626
+ const stripped = stripVolatile(summary.text ?? '');
627
+ const text = stripPhysiology(stripped.text);
525
628
  if (!text) continue;
526
629
  cleaned.push({ ...summary, text });
527
630
  if (cleaned.length >= 18) break;
@@ -793,7 +896,16 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
793
896
  .join('\n');
794
897
  }
795
898
  if (summaryText.trim()) {
796
- lines.push('[Cold-Start Summary]', summaryText.replace(/\s+/g, ' ').trim().slice(0, 800));
899
+ // v1.7.1: this is the single biggest source of stale facts in the prompt
900
+ // ("events 348 / reviews 346 due 337 / v1.6.9"). Strip the bookkeeping
901
+ // counters and stamp the moment the summary was made, so the reader knows
902
+ // the text is old even after cleaning. Always on, independent of mode.
903
+ const summaryAt =
904
+ Number(allEvents.find((event) => event.eventId === handoff?.summaryEventId)?.eventTime) ||
905
+ Number(handoff?.at) ||
906
+ null;
907
+ const hygienic = hygienicSummary(summaryText, { at: summaryAt, maxChars: 800, label: 'cold start' });
908
+ if (hygienic.text) lines.push('[Cold-Start Summary]', hygienic.text);
797
909
  }
798
910
  }
799
911
  if (wantTurns) {
@@ -806,8 +918,20 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
806
918
  .map((turn) => `- ${turn.role === 'assistant' ? 'assistant' : 'user'}: ${String(turn.text ?? '').replace(/\s+/g, ' ').trim().slice(0, 200)}`)
807
919
  .filter((line) => line.length > 10)
808
920
  : events
921
+ // v1.7.1: a folded/handoff SUMMARY is not a turn. It was leaking into the
922
+ // tail (with its stale counters) and duplicating the summary block above,
923
+ // so summary events are excluded here and each remaining line gets the
924
+ // same counter hygiene as everything else injected.
925
+ .filter((event) => {
926
+ if (handoff?.summaryEventId && event.eventId === handoff.summaryEventId) return false;
927
+ const tags = (event.tags ?? []).map((tag) => (tag?.tag ?? tag));
928
+ return !tags.some((tag) => tag === 'status:handoff' || tag === 'folded_summary');
929
+ })
809
930
  .slice(0, 5)
810
- .map((event) => `- ${String(event.content ?? '').replace(/\s+/g, ' ').trim().slice(0, 200)}`)
931
+ .map((event) => {
932
+ const cleaned = stripVolatile(String(event.content ?? '')).text;
933
+ return `- ${cleaned.replace(/\s+/g, ' ').trim().slice(0, 200)}`;
934
+ })
811
935
  .filter((line) => line.length > 2);
812
936
  if (recent.length > 0) lines.push('[Previous Context Tail]', ...recent);
813
937
  }
@@ -854,10 +978,24 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
854
978
  activeTags,
855
979
  fallbackTags: runtime.lastHintTags,
856
980
  });
857
- const freshTags = selected.filter((tag) => !runtime.injection.tags.has(tag));
981
+ // v1.7.1: in TASK mode a hint that has been shown `hintsIdleSilenceAfter` times
982
+ // and never earned a recall is silenced for good. The filter runs BEFORE the
983
+ // session-level dedup pool so a silenced tag is neither rendered nor burned.
984
+ const taskMode = config.context.mode !== 'expert';
985
+ const hintFeedback = runtime.hintFeedbackFacade();
986
+ const hinted = taskMode ? hintFeedback.filter(selected) : selected;
987
+ const freshTags = hinted.filter((tag) => !runtime.injection.tags.has(tag));
858
988
  for (const tag of freshTags) runtime.injection.tags.add(tag);
859
989
  if (selected.length > 0) runtime.lastHintTags = selected;
860
990
  const hints = hintsMuted ? '' : renderMemoryHints(freshTags, { toolName: `${config.toolPrefix}_recall` });
991
+ if (taskMode && hints && freshTags.length > 0) {
992
+ // Count only what was actually rendered; a silenced/blank render must not
993
+ // look like "the user saw it".
994
+ const feedback = hintFeedback.noteShown(freshTags, { threshold: config.context.hintsIdleSilenceAfter });
995
+ if (feedback.silenced.length > 0) {
996
+ runtime.logger?.debug?.(`hippocampus: hints silenced after N showings with no recall: ${feedback.silenced.join(',')}`);
997
+ }
998
+ }
861
999
  // v1.6.9 (module 3): computed AFTER hints (the most volatile of all) and rendered
862
1000
  // below them, so the cacheable prefix never moves.
863
1001
  const pointers = runtime.pointerText();
@@ -871,7 +1009,13 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
871
1009
  // P3-1: the SAME event must not appear again as a `[Memory Blocks]` entry.
872
1010
  // Block ids ARE event ids, so registering the bare id hides the block form.
873
1011
  runtime.injection.ids.add(activeTask.eventId);
874
- activeTaskBlock = renderActiveTask(activeTask);
1012
+ // v1.7.1: the task line is a summary, so it gets the same counter hygiene as
1013
+ // the cold-start block — a stale "events 348" is not part of the task.
1014
+ activeTaskBlock = hygienicSummary(renderActiveTask(activeTask), {
1015
+ at: Number(activeTask.at) || null,
1016
+ maxChars: 1200,
1017
+ label: 'active task',
1018
+ }).text;
875
1019
  }
876
1020
 
877
1021
  // Recall blocks: the block id IS the event id. Render only blocks that this
@@ -903,8 +1047,11 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
903
1047
  // v1.6.7 M1: in `index` mode the window renders pointer lines, so the rules
904
1048
  // must say so — otherwise the model reads a title as if it were the memory.
905
1049
  const rules = memory.context.injectMode === 'full' ? PROMPT_STATE_RULES : PROMPT_STATE_RULES_INDEX;
1050
+ // v1.7.1: task mode adds ONE current-state line, last in the prompt. It answers
1051
+ // "where am I now" (repo HEAD, window pressure), which memory cannot answer.
1052
+ const stateLine = taskMode ? runtime.statePointerText() : '';
906
1053
  return (
907
- composePrompt({ rules, activeTask: activeTaskBlock, blocks, hints, pointers }) +
1054
+ composePrompt({ rules, activeTask: activeTaskBlock, blocks, hints, pointers, stateLine }) +
908
1055
  marker +
909
1056
  (coldStart ? `\n${coldStart}` : '')
910
1057
  );
@@ -1445,6 +1592,10 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
1445
1592
  // M2: which optional external seams answered. Absence is reported, not hidden:
1446
1593
  // `wired:false` means this engine fell back to its own local behaviour.
1447
1594
  externalSeams: runtime.externalSeams?.() ?? null,
1595
+ // v1.7.1: which contract this engine serves, and how the hint loop is doing.
1596
+ // Observable on purpose — a silently silenced tag must be explainable from /stats.
1597
+ mode: runtime.config?.context?.mode ?? 'task',
1598
+ hints: runtime.hintFeedbackFacade().status(),
1448
1599
  crossSpaceTransfer: runtime.multiSpaceAvailable() && runtime.config.features.crossSpaceTransfer !== false,
1449
1600
  // v1.5.6: opt-in cross-space recall aggregation (default false).
1450
1601
  crossSpaceRecall: runtime.multiSpaceAvailable() && runtime.config.features.crossSpaceRecall === true,
@@ -1472,7 +1623,10 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
1472
1623
  })(),
1473
1624
  });
1474
1625
 
1475
- /** v1.5.6: handoff observability (the client shows the marker + summary link). */ runtime.handoffView = () => {
1626
+ /** v1.5.6: handoff observability (the client shows the marker + summary link). */ /** v1.7.1: the hint feedback loop (tracked / silenced counts and the silenced tags). */
1627
+ runtime.hintFeedbackView = () => runtime.hintFeedbackFacade().status();
1628
+
1629
+ runtime.handoffView = () => {
1476
1630
  const handoff = memory.handoffState();
1477
1631
  return {
1478
1632
  active: handoff?.active === true,
@@ -3160,6 +3314,7 @@ export async function apply(ctx, rawConfig = {}) {
3160
3314
  .slice(0, 8)
3161
3315
  .map((entry) => entry.tag)
3162
3316
  .filter(Boolean);
3317
+ const feedbackStatus = runtime.hintFeedbackView();
3163
3318
  return ok(
3164
3319
  [
3165
3320
  `记忆引擎:ready(v${CAPABILITIES.version})`,
@@ -3167,7 +3322,10 @@ export async function apply(ctx, rawConfig = {}) {
3167
3322
  `会话 ${session.sessionId ?? '未知'} · 已用 ${session.tokens ?? 0} + 预留 ${session.reservedTokens ?? 0} = ${session.projectedTokens ?? 0} / 窗口 ${session.nativeTokenLimit ?? '?'}(来源 ${session.windowSource ?? 'config'})`,
3168
3323
  `交接标记:${session.handoffActive ? `active(${session.handoffAt ?? '?'})` : '无'} · 冷启动待注入 ${runtime.coldStart.pending.size} 条 / 已注入 ${runtime.coldStart.injected.size} 次`,
3169
3324
  tagList.length ? `活跃标签 Top:${tagList.join('、')}` : '活跃标签:无',
3170
- `[Memory Hints]:${runtime.hintsMuted ? '已静默(/memory unmute 恢复)' : '开启'}`,
3325
+ `[Memory Hints]:${runtime.hintsMuted ? '已静默(/memory unmute 恢复)' : '开启'}·运行模式 ${runtime.config?.context?.mode ?? 'task'}`,
3326
+ // v1.7.1: the hint loop is visible, not a mystery. A silenced tag is
3327
+ // the engine's own decision and the operator must be able to see why.
3328
+ `H提示反馈:追踪 ${feedbackStatus.tracked} 个标签,单向静默 ${feedbackStatus.silenced} 个${feedbackStatus.silencedTags.length ? `(${feedbackStatus.silencedTags.join('、')})` : ''}`,
3171
3329
  // v1.7.0 (M5): usage EVIDENCE, computed from in-process counters only.
3172
3330
  `工具使用(本进程):${toolUsageLine()}`,
3173
3331
  ].join('\n'),
@@ -3300,6 +3458,18 @@ function injectRecall(runtime, result) {
3300
3458
  now,
3301
3459
  });
3302
3460
  }
3461
+ // v1.7.1: this is the ONLY place a hint can earn its keep. Feeds the loop that
3462
+ // silences tags which keep being shown but never bring the model here — without this
3463
+ // signal the loop would silence everything, which is worse than no loop at all.
3464
+ try {
3465
+ const recalledTags = [
3466
+ ...(result.hits ?? []).flatMap((hit) => (Array.isArray(hit?.tags) ? hit.tags : [])),
3467
+ ...(result.associative?.tags ?? []),
3468
+ ].filter((tag) => typeof tag === 'string' && tag.length > 0);
3469
+ if (recalledTags.length > 0) runtime.hintFeedbackFacade().noteRecalled(recalledTags);
3470
+ } catch {
3471
+ /* feedback is advisory: never let it break a recall */
3472
+ }
3303
3473
  // Folding: what left the window is not lost. Fire-and-forget so a recall never
3304
3474
  // waits on a write; a failure is reported through the logger, never through the
3305
3475
  // recall result.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-layers-hippocampus",
3
- "version": "1.7.0",
3
+ "version": "1.7.2",
4
4
  "private": false,
5
5
  "description": "Layered long-term memory for DeepSeek Harness: append-only event log, rebuildable tag index, day diaries, independent semantic layer, L2.5 trend quarantine, offline knowledge graph and a Web UI panel.",
6
6
  "type": "module",
package/src/config.js CHANGED
@@ -221,6 +221,19 @@ export const DEFAULT_CONFIG = Object.freeze({
221
221
  // v1.7.0 (M1): how many raw tail turns `getLatestHandoffSummary()` carries.
222
222
  // Bounded 3..5: fewer loses the thread, more is a second transcript.
223
223
  handoffSummaryTurns: 4,
224
+ // v1.7.1: which of the two prompt contracts this engine serves.
225
+ // - `task` (default): the model is doing a build/debug task. It needs the
226
+ // CURRENT state (repo HEAD, window pressure), not a stream of memory hints —
227
+ // so hints that never earn a recall go quiet after N showings, and a compact
228
+ // `[Task State]` line is injected instead.
229
+ // - `expert`: the model is meant to use memory actively. Every hint stays on and
230
+ // no task-state line is added.
231
+ mode: 'task',
232
+ // Shown N times with zero recalls → one-way silence (task mode only).
233
+ hintsIdleSilenceAfter: 8,
234
+ // The `[Task State]` line (task mode only). `maxChars` is a hard cap: this line
235
+ // sits in the volatile tail and must never grow into a status dump.
236
+ statePointer: { enabled: true, maxChars: 300 },
224
237
  coldStartInjectRecentTurns: true,
225
238
  // REMOVED in v1.5.3: `minInjectConfidence`. It never demonstrably saved tokens
226
239
  // (0.6 vs 0 produced byte-identical payloads) and every hit-shaping pass is a
@@ -846,6 +859,30 @@ function buildResolvedConfig(raw = {}, { env = process.env } = {}) {
846
859
  : contextIn.coldStartInjectRecentTurns,
847
860
  'context.coldStartInjectRecentTurns',
848
861
  );
862
+ // v1.7.1: task vs expert is a CONTRACT choice, so it is an enum (a typo must fail
863
+ // fast, not silently default to "task" and mute hints the user wanted).
864
+ const contextMode = requireEnum(
865
+ contextIn.mode === undefined ? defaults.context.mode : contextIn.mode,
866
+ 'context.mode',
867
+ ['task', 'expert'],
868
+ );
869
+ const contextHintsIdleSilenceAfter = requireInteger(
870
+ contextIn.hintsIdleSilenceAfter === undefined
871
+ ? defaults.context.hintsIdleSilenceAfter
872
+ : contextIn.hintsIdleSilenceAfter,
873
+ 'context.hintsIdleSilenceAfter',
874
+ { min: 1, max: 100 },
875
+ );
876
+ const statePointerIn = contextIn.statePointer ?? {};
877
+ const statePointerEnabled = requireBoolean(
878
+ statePointerIn.enabled === undefined ? defaults.context.statePointer.enabled : statePointerIn.enabled,
879
+ 'context.statePointer.enabled',
880
+ );
881
+ const statePointerMaxChars = requireInteger(
882
+ statePointerIn.maxChars === undefined ? defaults.context.statePointer.maxChars : statePointerIn.maxChars,
883
+ 'context.statePointer.maxChars',
884
+ { min: 60, max: 2000 },
885
+ );
849
886
  // REMOVED KEY (v1.5.3), loud on purpose: nested groups normally ignore unknown
850
887
  // keys, but silently ignoring a removed confidence knob would let a profile run
851
888
  // with a false belief about token behaviour. Fail fast with the exact path.
@@ -1477,6 +1514,10 @@ function buildResolvedConfig(raw = {}, { env = process.env } = {}) {
1477
1514
  // v1.6.3 cold-start injection switches (independent booleans).
1478
1515
  coldStartInjectSummary: contextColdStartInjectSummary,
1479
1516
  handoffSummaryTurns: contextHandoffSummaryTurns,
1517
+ // v1.7.1 task/expert contract + the two task-mode behaviours it gates.
1518
+ mode: contextMode,
1519
+ hintsIdleSilenceAfter: contextHintsIdleSilenceAfter,
1520
+ statePointer: { enabled: statePointerEnabled, maxChars: statePointerMaxChars },
1480
1521
  coldStartInjectRecentTurns: contextColdStartInjectRecentTurns,
1481
1522
  // v1.5.0 routing knobs below; v1.5.3 removed minInjectConfidence entirely.
1482
1523
  autoSpaceFollow: contextAutoSpaceFollow,
@@ -0,0 +1,200 @@
1
+ /**
2
+ * Hint feedback loop (v1.7.1, task mode).
3
+ *
4
+ * `[Memory Hints]` shows "相关经验标签: X、Y, 若需借鉴请调用 memory_recall". The loop
5
+ * closes here:每展示一次就记一次 `shown`,只有当该标签**真的**带来一次 recall 时
6
+ * 才记 `recalled`。连续展示 8 次(可配)且一次都没换来 recall 的标签,会被**单向
7
+ * 静默**——不再出现在 hints 里,也不会因为之后偶然被 recall 而自动复活。
8
+ *
9
+ * "单向" is the important part: the previous behaviour (show forever, hope) made a
10
+ * stale tag cost a line of prompt every single turn. A silencing that auto-revives
11
+ * would just re-learn the same mistake, so revival requires deleting the state file
12
+ * (or raising the threshold), not a lucky recall.
13
+ *
14
+ * Persistence: `state/hint-feedback.json` (schema 1). Bounded: at most
15
+ * `MAX_TRACKED_TAGS` tags are kept, oldest-by-last-shown evicted. Never throws: a
16
+ * broken/missing file degrades to "nothing silenced", because a hint loop must never
17
+ * be able to break prompt assembly.
18
+ */
19
+
20
+ import fs from 'node:fs';
21
+ import path from 'node:path';
22
+
23
+ import { ensureDir, readJson, writeJsonAtomic } from './util.js';
24
+
25
+ export const HINT_FEEDBACK_SCHEMA = 1;
26
+ /** Default: 8 fruitless showings and the tag goes quiet for good. */
27
+ export const HINT_IDLE_SILENCE_AFTER = 8;
28
+ /** Hard bound on tracked tags — the file is state, not an archive. */
29
+ export const MAX_TRACKED_TAGS = 2000;
30
+
31
+ /**
32
+ * @param {object} record one tag's counters
33
+ * @param {number} threshold
34
+ */
35
+ export function shouldSilence(record, threshold = HINT_IDLE_SILENCE_AFTER) {
36
+ if (!record || record.silenced === true) return record?.silenced === true;
37
+ const shown = Number(record.shown) || 0;
38
+ const recalled = Number(record.recalled) || 0;
39
+ const limit = Math.max(1, Number(threshold) || HINT_IDLE_SILENCE_AFTER);
40
+ return recalled === 0 && shown >= limit;
41
+ }
42
+
43
+ export class HintFeedbackStore {
44
+ /**
45
+ * @param {{file: string, clock?: {now: () => number}}} options
46
+ */
47
+ constructor({ file, clock = { now: () => Date.now() } } = {}) {
48
+ if (typeof file !== 'string' || file.length === 0) throw new Error('HintFeedbackStore needs a file path');
49
+ this.file = file;
50
+ this.clock = clock;
51
+ this.state = { schema: HINT_FEEDBACK_SCHEMA, tags: {}, updatedAt: null };
52
+ this.loaded = false;
53
+ }
54
+
55
+ load() {
56
+ this.loaded = true;
57
+ try {
58
+ const raw = readJson(this.file, null);
59
+ if (!raw || typeof raw !== 'object') return this.state;
60
+ const tags = raw.tags && typeof raw.tags === 'object' ? raw.tags : {};
61
+ const clean = {};
62
+ for (const [tag, record] of Object.entries(tags)) {
63
+ if (typeof tag !== 'string' || !tag) continue;
64
+ if (!record || typeof record !== 'object') continue;
65
+ clean[tag] = {
66
+ shown: Math.max(0, Number(record.shown) || 0),
67
+ recalled: Math.max(0, Number(record.recalled) || 0),
68
+ silenced: record.silenced === true,
69
+ silencedAt: Number(record.silencedAt) || null,
70
+ lastShownAt: Number(record.lastShownAt) || null,
71
+ };
72
+ }
73
+ this.state = { schema: HINT_FEEDBACK_SCHEMA, tags: clean, updatedAt: Number(raw.updatedAt) || null };
74
+ } catch {
75
+ /* a broken file means "nothing silenced", never a crash */
76
+ }
77
+ return this.state;
78
+ }
79
+
80
+ _ensure() {
81
+ if (!this.loaded) this.load();
82
+ return this.state;
83
+ }
84
+
85
+ /** Tags currently silenced (one-way). */
86
+ silencedTags() {
87
+ const state = this._ensure();
88
+ return Object.entries(state.tags)
89
+ .filter(([, record]) => record.silenced === true)
90
+ .map(([tag]) => tag);
91
+ }
92
+
93
+ /** Filter a hint list: drop silenced tags, keep order. */
94
+ filter(tags = []) {
95
+ const silenced = new Set(this.silencedTags());
96
+ return (Array.isArray(tags) ? tags : []).filter((tag) => typeof tag === 'string' && !silenced.has(tag));
97
+ }
98
+
99
+ /**
100
+ * Record that these tags were SHOWN this turn. Returns the tags that just became
101
+ * silenced, so the caller can log/observe the transition instead of only noticing
102
+ * that a hint vanished.
103
+ */
104
+ noteShown(tags = [], { threshold = HINT_IDLE_SILENCE_AFTER } = {}) {
105
+ const state = this._ensure();
106
+ const now = this.clock.now();
107
+ const newlySilenced = [];
108
+ let changed = false;
109
+ for (const tag of Array.isArray(tags) ? tags : []) {
110
+ if (typeof tag !== 'string' || tag.length === 0) continue;
111
+ const record = state.tags[tag] ?? { shown: 0, recalled: 0, silenced: false, silencedAt: null, lastShownAt: null };
112
+ if (record.silenced === true) continue;
113
+ record.shown += 1;
114
+ record.lastShownAt = now;
115
+ if (shouldSilence(record, threshold)) {
116
+ record.silenced = true;
117
+ record.silencedAt = now;
118
+ newlySilenced.push(tag);
119
+ }
120
+ state.tags[tag] = record;
121
+ changed = true;
122
+ }
123
+ if (changed) {
124
+ this._trim();
125
+ state.updatedAt = now;
126
+ this._write();
127
+ }
128
+ return { silenced: newlySilenced, changed };
129
+ }
130
+
131
+ /** Record that a recall actually happened for these tags. Does NOT revive. */
132
+ noteRecalled(tags = []) {
133
+ const state = this._ensure();
134
+ let changed = false;
135
+ for (const tag of Array.isArray(tags) ? tags : []) {
136
+ if (typeof tag !== 'string' || tag.length === 0) continue;
137
+ const record = state.tags[tag];
138
+ if (!record) continue;
139
+ record.recalled += 1;
140
+ changed = true;
141
+ }
142
+ if (changed) {
143
+ state.updatedAt = this.clock.now();
144
+ this._write();
145
+ }
146
+ return { changed };
147
+ }
148
+
149
+ /** Forget one tag's silence (explicit operator action; not called automatically). */
150
+ revive(tag) {
151
+ const state = this._ensure();
152
+ const record = state.tags[tag];
153
+ if (!record?.silenced) return false;
154
+ record.silenced = false;
155
+ record.silencedAt = null;
156
+ record.shown = 0;
157
+ record.recalled = 0;
158
+ state.updatedAt = this.clock.now();
159
+ this._write();
160
+ return true;
161
+ }
162
+
163
+ _trim() {
164
+ const state = this._ensure();
165
+ const entries = Object.entries(state.tags);
166
+ if (entries.length <= MAX_TRACKED_TAGS) return;
167
+ entries.sort((left, right) => (Number(left[1].lastShownAt) || 0) - (Number(right[1].lastShownAt) || 0));
168
+ for (const [tag] of entries.slice(0, entries.length - MAX_TRACKED_TAGS)) delete state.tags[tag];
169
+ }
170
+
171
+ _write() {
172
+ try {
173
+ ensureDir(path.dirname(this.file));
174
+ writeJsonAtomic(this.file, this.state);
175
+ } catch {
176
+ /* state is advisory: a read-only disk must not break prompt assembly */
177
+ }
178
+ }
179
+
180
+ status() {
181
+ const state = this._ensure();
182
+ const tags = Object.entries(state.tags);
183
+ const silenced = tags.filter(([, record]) => record.silenced === true);
184
+ return {
185
+ tracked: tags.length,
186
+ silenced: silenced.length,
187
+ silencedTags: silenced.slice(0, 20).map(([tag]) => tag),
188
+ updatedAt: state.updatedAt,
189
+ };
190
+ }
191
+
192
+ /** Test/ops helper: drop the file and the in-memory cache. */
193
+ static removeFile(file) {
194
+ try {
195
+ fs.rmSync(file, { force: true });
196
+ } catch {
197
+ /* best effort */
198
+ }
199
+ }
200
+ }