dsh-layers-hippocampus 1.7.0 → 1.7.1

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,49 @@ 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.1] — 2026-11-24
8
+
9
+ **把注入面从“多给点信息”改成“只给还没过期的信息”:摘要卫生常开,提示标签单向静默,
10
+ 任务模式补一行当前状态。三项都来自一次真实长会话的复盘,不是理论优化。**
11
+
12
+ - **Fixed — 注入摘要里的过期计数(常开,不受模式开关影响)**:交接摘要、L3 人格行、
13
+ `[Active Task]` 都会带上写那一刻的簿记数字(`events 348`、`reviews total 346 due 337`、
14
+ `version 1.6.9`)。它们**写入时是真的,几分钟后就假了**,模型要先读一遍再花 token 纠正。
15
+ 新增 `src/promptHygiene.js`:`stripVolatile()` 只删**簿记子句**(版本号、`key: N`、
16
+ `gen-000131`、ISO 时间戳、`N 条/个/分片`),**刻意不删没有键名的裸数字**——否则
17
+ `854,668 + 256,000 > 1,048,576` 这类教训会被一起删掉;带「是/为/需要/必须/禁止/不要」
18
+ 的句子不按计数量删除。`hygienicSummary()` 再补一个快照时间戳
19
+ (`(snapshot … · counters stripped as stale)`),让读者知道这段文字有多旧。
20
+ 三个注入点(冷启动摘要、人格行、活动任务)全部走同一条路径。
21
+ - **Fixed — 冷启动尾部泄漏摘要事件**:`[Previous Context Tail]` 在缺少 `tailTurns` 时回退到
22
+ 「最近业务事件」,而交接摘要事件本身带 `folded_summary` 标签,于是**摘要被当成一轮对话**
23
+ 再注入一次(连同它的过期计数)。现在排除摘要事件,其余每行也过一遍卫生。
24
+ - **Added — 提示标签的单向静默(任务模式)**:`[Memory Hints]` 过去会一直展示同一个不相关
25
+ 标签,从不换来一次 `recall`(实测 2 次出现、0 次使用)。新增 `src/hintFeedback.js`
26
+ (`state/hint-feedback.json`,schema 1):每个标签记 `shown` / `recalled`;连续
27
+ `context.hintsIdleSilenceAfter`(默认 **8**)次展示且 `recalled === 0` → **永久静默**。
28
+ 单向是关键:静默后即使偶然被 recall 也不会自动复活,只有 `revive()` 或删状态文件才能恢复
29
+ —— 自动复活只会把同一个错误再学一遍。计数只在真的渲染出 hints 时才增加;召回路径
30
+ (`injectRecall`)记录 `recalled`,这是唯一能让标签留下的信号。
31
+ - **Added — `[Task State]` 当前状态行(任务模式)**:记忆回答「去过哪里」,构建/调试会话
32
+ 还需要「现在在哪」。任务模式在 Prompt **最末**注入一行
33
+ (`repo@branch · HEAD <sha7> · window 291k/1048k (host) · maintained 12m ago`):
34
+ HEAD 直接读 `.git/HEAD` + loose ref(**不 spawn git**,5 秒缓存),窗口压力取宿主上报值,
35
+ 硬上限 `context.statePointer.maxChars`(默认 300,超出截断加 `…`)。
36
+ 它排在所有易变段之后,前缀缓存不受影响。
37
+ - **Added — 任务 / 专家模式(`context.mode`)**:`task`(默认)启用上面两项;
38
+ `expert` 保留全部提示、不注入状态行、不咨询提示闭环。设置页「上下文窗口」新增
39
+ 运行模式下拉、静默阈值数字框与状态行开关;`context.mode` 也进了简洁模式白名单
40
+ (同一个开关在两种视图里都必须可改,否则等于骗人)。枚举校验:拼错直接 fail-fast。
41
+ - **Observability**:`capabilities.mode` 与 `capabilities.hints`(`tracked` / `silenced` /
42
+ `silencedTags`)进入 `/stats`;`/memory status` 显示运行模式、提示反馈统计与被静默的标签
43
+ ——「一个标签为什么不再出现」必须能从接口回答,而不是靠猜。
44
+ - **Tests**:`test/v171.mode.test.js`(7 例)锁定模式默认与枚举校验、8 次空手展示后的单向
45
+ 静默且 recall 不复活、静默跨重启持久、有 recall 的标签不被静默、专家模式不咨询闭环也不注入
46
+ 状态行、状态行硬上限与 HEAD 存在且排在最后、卫生剔除簿记却保留 854,668 那组教训数字、
47
+ 快照时间戳格式,以及真实交接下冷启动块既被清洗又保留结论半句。
48
+ 全量 **555/555**(87 个测试文件)。
49
+
7
50
  ## [1.7.0] — 2026-11-24
8
51
 
9
52
  **全链路记忆的第二半:写入侧去重(实体)、检索侧联想(1 跳)、语义侧分层(六维人格)、
package/README.md CHANGED
@@ -7,7 +7,7 @@
7
7
 
8
8
  | | |
9
9
  | --- | --- |
10
- | 版本 | **1.7.0** |
10
+ | 版本 | **1.7.1** |
11
11
  | 包名 | `dsh-layers-hippocampus` |
12
12
  | 仓库 | <https://github.com/382quaii/dsh-Layers-Hippocampus> |
13
13
  | 许可证 | MIT |
@@ -124,6 +124,21 @@
124
124
  `capabilities.externalSeams` 会如实报告 `{wired, source}`,所以「没装」是可见事实。
125
125
  **高峰期不丢任务**:LLM 蒸馏在高峰只被写入持久化队列并在谷时唤醒,不是跳过。
126
126
 
127
+ ### 提示预算治理:任务 / 专家模式(1.7.1)
128
+
129
+ 记忆插件过去只回答「记住什么」,不回答「该不该现在说」。1.7.1 把注入面收紧:
130
+
131
+ - **摘要卫生(常开)**:注入的摘要会先去掉写那一刻的簿记数字(`events 348`、`reviews due 337`、
132
+ 版本号),再补一个 `(snapshot …)` 时间戳。**带教训的数字不会被删**——`854,668 + 256,000 >
133
+ 1,048,576` 这类结论原样保留。
134
+ - **提示标签单向静默(任务模式)**:同一标签连续 `context.hintsIdleSilenceAfter`(默认 8)次出现
135
+ 且一次都没换来 `recall`,就永久不再出现;之后偶然被召回也不会自动复活。
136
+ 看不出来源时用 `/memory status` 查看被静默的标签。
137
+ - **`[Task State]` 当前状态行(任务模式)**:Prompt 末尾一行
138
+ `repo@branch · HEAD <sha7> · window 291k/1048k (host)`,不 spawn git、硬上限 300 字符。
139
+ - **`context.mode`**:`task`(默认)启用上面两项;`expert` 保留全部提示、不注入状态行。
140
+ 设置页「上下文窗口」可切换,简洁模式下同样可改。
141
+
127
142
  ### 全链路记忆:写入归并 / 检索联想 / 自动指针(1.6.9)
128
143
 
129
144
  - **写入时归并实体**:`entity:` 标签先查别名字典,再按**子串包含**(已有 `entity:红薯`,写入
@@ -232,7 +247,7 @@ raw 层提供三档,覆盖从“只留关键”到“全留”:
232
247
  pnpm add dsh-layers-hippocampus
233
248
 
234
249
  # 或从 GitHub 指定 tag
235
- pnpm add "github:382quaii/dsh-Layers-Hippocampus#v1.7.0"
250
+ pnpm add "github:382quaii/dsh-Layers-Hippocampus#v1.7.1"
236
251
  ```
237
252
 
238
253
  ### 2. 挂到 profile
@@ -303,7 +318,7 @@ node scripts/wait-for-routes.mjs
303
318
  ### 6. 验证
304
319
 
305
320
  ```bash
306
- npm test # 进程内全量用例(548 个)
321
+ npm test # 进程内全量用例(555 个)
307
322
  npm run check # 语法检查 + 全量测试
308
323
  ```
309
324
 
@@ -1,6 +1,6 @@
1
1
  # @local/dsh-memory — 分层长期记忆 Host 插件
2
2
 
3
- > 版本:**1.7.0** | 全量用例:**548/548** | 运行时依赖:**零**
3
+ > 版本:**1.7.1** | 全量用例:**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.1',
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.1",
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
+ }
@@ -0,0 +1,144 @@
1
+ /**
2
+ * Prompt hygiene for INJECTED summaries (v1.7.1).
3
+ *
4
+ * The problem this solves is concrete: a handoff/L3 summary written hours ago says
5
+ * "events 348 / reviews total 346 due 337 / version 1.6.9", and the model spends
6
+ * tokens reading a stale fact and then more tokens contradicting it. Counters are
7
+ * TRUE AT WRITE TIME and false almost immediately, so they must never enter a
8
+ * prompt as if they were knowledge.
9
+ *
10
+ * Two rules, both conservative:
11
+ *
12
+ * 1. **Drop bookkeeping counters** — version strings, `events: N`, `reviews total
13
+ * N/due M`, `gen-000123`, ISO timestamps, `N 条事件` etc. Numbers that carry a
14
+ * LESSON (e.g. "854,668 + 256,000 > 1,048,576") are NOT touched: only the
15
+ * known bookkeeping keys are stripped, never bare digits.
16
+ * 2. **Stamp the snapshot** so a reader knows the text is old even after cleaning.
17
+ *
18
+ * Pure and deterministic: no clock reads inside the transforms (the caller passes
19
+ * `at`), no IO, no regex backtracking traps (all patterns are anchored on literal
20
+ * key names and bounded quantifiers).
21
+ */
22
+
23
+ /** Bookkeeping keys whose numeric value is stale by definition. */
24
+ const COUNTER_KEYS = [
25
+ 'version',
26
+ 'events',
27
+ 'eventcount',
28
+ 'activetags',
29
+ 'semsummaries',
30
+ 'semanticsummaries',
31
+ 'summaries',
32
+ 'reviewstotal',
33
+ 'reviews',
34
+ 'due',
35
+ 'pinned',
36
+ 'shards',
37
+ 'rawshards',
38
+ 'indexedshards',
39
+ 'archives',
40
+ 'archivecount',
41
+ 'diskbytes',
42
+ 'rawbytes',
43
+ 'tokens',
44
+ 'injected',
45
+ 'pending',
46
+ 'gen',
47
+ 'indexgen',
48
+ 'loggen',
49
+ 'runs',
50
+ 'groups',
51
+ ];
52
+
53
+ /** `events: 1446` / `reviews total 346` → drop the clause. */
54
+ const COUNTER_RE = new RegExp(
55
+ `(?:^|[\\s((、,,;;|·])[^;;。\\n|]{0,24}?(?:${COUNTER_KEYS.join('|')})[^;;。\\n|]{0,12}?[::=≈]?\\s*\\d[\\d,._/]*`,
56
+ 'i',
57
+ );
58
+
59
+ /** Semver-ish stamps: `1.6.9`, `v1.7.0`. Bounded so `854,668` is never matched. */
60
+ const VERSION_RE = /(?:\bv|\bversion\s*[::=]?\s*)?\b\d+\.\d+\.\d+\b/i;
61
+
62
+ /** `gen-000113`, `ev_ab12…`, ISO timestamps. */
63
+ const MACHINE_ID_RE = /\bgen-\d{3,}\b|\b\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2})?(?:\.\d+)?Z?\b/;
64
+
65
+ /** `348 条事件` / `9 个分片` / `85 个文件` — count + counting noun. */
66
+ const COUNT_NOUN_RE = /\b\d[\d,]*\s*(?:条|个|篇|次|files?|events?|shards?|tokens?|items?)\b/i;
67
+
68
+ /** Sentence/clause separators used when deciding what a "segment" is. */
69
+ const SEGMENT_SEP = /([;;。\n]|(?:\s·\s))/;
70
+
71
+ /**
72
+ * True when this clause is bookkeeping rather than knowledge.
73
+ *
74
+ * Deliberately narrow: a clause is dropped only when it looks like a counter or a
75
+ * machine id. A clause mixing a lesson AND a counter keeps the lesson half only if
76
+ * the counter is a separate `;`-delimited segment — we never rewrite inside a clause.
77
+ */
78
+ export function isVolatileClause(clause) {
79
+ const text = String(clause ?? '').trim();
80
+ if (text.length === 0) return false;
81
+ if (MACHINE_ID_RE.test(text)) return true;
82
+ if (COUNTER_RE.test(text)) return true;
83
+ if (COUNT_NOUN_RE.test(text) && !/[是为需要必须禁止不要]/.test(text)) return true;
84
+ // A bare version stamp is only volatile when it is the whole clause ("v1.6.9").
85
+ if (VERSION_RE.test(text) && text.replace(VERSION_RE, '').trim().length <= 6) return true;
86
+ return false;
87
+ }
88
+
89
+ /**
90
+ * Strip volatile clauses from a block of injected text.
91
+ *
92
+ * @param {string} text raw summary / persona / active-task text
93
+ * @returns {{text: string, removed: string[]}} cleaned text plus what was dropped
94
+ */
95
+ export function stripVolatile(text) {
96
+ const raw = String(text ?? '');
97
+ if (raw.trim().length === 0) return { text: '', removed: [] };
98
+ const removed = [];
99
+ const kept = [];
100
+ for (const piece of raw.split(SEGMENT_SEP)) {
101
+ if (piece === undefined) continue;
102
+ if (/^[;;。\n]$/.test(piece) || /^\s·\s$/.test(piece)) {
103
+ kept.push(piece);
104
+ continue;
105
+ }
106
+ if (isVolatileClause(piece)) {
107
+ const trimmed = piece.trim();
108
+ if (trimmed) removed.push(trimmed);
109
+ continue;
110
+ }
111
+ kept.push(piece);
112
+ }
113
+ // Collapse the separators that lost their neighbour and normalise whitespace.
114
+ let out = kept.join('');
115
+ out = out.replace(/^\s*[;;。·]\s*/u, '').replace(/[;;·]\s*(?=[;;。]|$)/gu, '');
116
+ out = out.replace(/\s{2,}/g, ' ').trim();
117
+ if (out.length > 0 && !/[。.!?!?]$/.test(out)) out += '。';
118
+ return { text: out, removed };
119
+ }
120
+
121
+ /** `2026-11-24T14:31Z` — the moment the summary was produced, or "unknown". */
122
+ export function snapshotStamp(at) {
123
+ const value = Number(at);
124
+ if (!Number.isFinite(value) || value <= 0) return 'snapshot time unknown';
125
+ return `snapshot ${new Date(value).toISOString().replace(/\.\d{3}Z$/, 'Z')}`;
126
+ }
127
+
128
+ /**
129
+ * Clean a summary and stamp it. This is the ONE entry point every injection site
130
+ * should use, so "clean + dated" cannot be forgotten in one place and applied in
131
+ * another.
132
+ *
133
+ * @param {string} text
134
+ * @param {{at?: number, maxChars?: number, label?: string}} options
135
+ */
136
+ export function hygienicSummary(text, { at = null, maxChars = 800, label = null } = {}) {
137
+ const { text: cleaned, removed } = stripVolatile(text);
138
+ if (cleaned.length === 0) return { text: '', removed, dropped: true };
139
+ const head = `(${snapshotStamp(at)}${label ? ` · ${label}` : ''} · counters stripped as stale)`;
140
+ const body = cleaned.replace(/\s+/g, ' ').trim();
141
+ const budget = Math.max(0, Number(maxChars) || 0);
142
+ const text_ = `${head} ${body}`.slice(0, budget > 0 ? budget : undefined);
143
+ return { text: text_, removed, dropped: false };
144
+ }
@@ -16,8 +16,20 @@
16
16
  export const BLOCK_MARKER = '[Memory Blocks]';
17
17
  export const ACTIVE_TASK_MARKER = '[Active Task]';
18
18
  export const POINTER_MARKER = '[Memory Index]';
19
+ // v1.7.1: the CURRENT-STATE line (task mode). It is the most volatile thing in the
20
+ // prompt (window pressure changes every turn), so it goes LAST — after every other
21
+ // volatile section — and never before the block marker.
22
+ export const STATE_MARKER = '[Task State]';
19
23
 
20
- export function composePrompt({ rules = '', activeTask = '', map = '', hints = '', blocks = '', pointers = '' } = {}) {
24
+ export function composePrompt({
25
+ rules = '',
26
+ activeTask = '',
27
+ map = '',
28
+ hints = '',
29
+ blocks = '',
30
+ pointers = '',
31
+ stateLine = '',
32
+ } = {}) {
21
33
  const parts = [String(rules).trim()];
22
34
  // The active task sits at the very top of the memory section: a new session must
23
35
  // know what it was doing before it reads anything else.
@@ -30,6 +42,9 @@ export function composePrompt({ rules = '', activeTask = '', map = '', hints = '
30
42
  // v1.6.9 (module 3): index pointers sit UNDER the hints — both are per-turn and
31
43
  // both must stay after the block marker so the cacheable prefix never moves.
32
44
  if (String(pointers).trim()) parts.push(`${POINTER_MARKER}\n${String(pointers).trim()}`);
45
+ // v1.7.1: the task-state line changes on almost every turn, so it must be the very
46
+ // last section — everything above it stays byte-identical for the prefix cache.
47
+ if (String(stateLine).trim()) parts.push(`${STATE_MARKER}\n${String(stateLine).trim()}`);
33
48
  return parts.filter(Boolean).join('\n\n');
34
49
  }
35
50
 
@@ -70,6 +85,26 @@ export function renderPointers(entries = [], { maxChars = 300 } = {}) {
70
85
  return lines.join('\n');
71
86
  }
72
87
 
88
+ /**
89
+ * v1.7.1: render the `[Task State]` body.
90
+ *
91
+ * Contract: ONE line, `·`-separated, hard-capped by `maxChars`. This exists because a
92
+ * build/debug task needs "where am I right now" (repo HEAD, window pressure), while
93
+ * memory summarises where it has BEEN. Anything that does not fit the budget is cut,
94
+ * not wrapped — a status dump in the prompt tail is worse than a short line.
95
+ */
96
+ export function renderStateLine(fields = {}, { maxChars = 300 } = {}) {
97
+ const budget = Math.max(0, Number(maxChars) || 0);
98
+ const parts = [];
99
+ for (const value of Object.values(fields ?? {})) {
100
+ const text = String(value ?? '').replace(/\s+/g, ' ').trim();
101
+ if (text) parts.push(text);
102
+ }
103
+ const line = parts.join(' · ');
104
+ if (budget > 0 && line.length > budget) return line.slice(0, Math.max(0, budget - 1)) + '…';
105
+ return line;
106
+ }
107
+
73
108
  /** Map view: tag names + counts only, never event bodies. */
74
109
  export function renderMemoryMap(entries = []) {
75
110
  return entries.map((entry) => `${entry.tag}(${entry.count ?? entry.events ?? 0})`).join(' · ');
package/src/webRoutes.js CHANGED
@@ -98,6 +98,11 @@ export const EDITABLE_CONFIG_KEYS = Object.freeze([
98
98
  'context.autoInjectIndex.maxChars',
99
99
  // v1.6.0 cold-start injection switches (independent; both default on since 1.6.3).
100
100
  'context.handoffSummaryTurns',
101
+ // v1.7.1: the task/expert contract switch and the two task-mode behaviours it gates.
102
+ 'context.mode',
103
+ 'context.hintsIdleSilenceAfter',
104
+ 'context.statePointer.enabled',
105
+ 'context.statePointer.maxChars',
101
106
  'context.coldStartInjectSummary',
102
107
  'context.coldStartInjectRecentTurns',
103
108
  // v1.5.6 L2 multi-merge tunables (offline maintain phase).
package/ui/client.js CHANGED
@@ -2531,6 +2531,7 @@
2531
2531
  // v1.6.7 M1: visible in the 上下文窗口 card in both modes, so it must also be
2532
2532
  // in the simple-mode allowlist — a control that renders but never saves is a lie.
2533
2533
  'context.injectMode',
2534
+ 'context.mode',
2534
2535
  'raw.mode',
2535
2536
  'raw.maxTotalMb',
2536
2537
  'raw.compressionEngine',
@@ -2643,6 +2644,10 @@
2643
2644
  target: Number(config.context.target),
2644
2645
  injectPrompt: Boolean(config.context.injectPrompt),
2645
2646
  injectMode: config.context && config.context.injectMode === 'full' ? 'full' : 'index',
2647
+ // v1.7.1: default to TASK — a build session must not be fed hints forever.
2648
+ mode: config.context && config.context.mode === 'expert' ? 'expert' : 'task',
2649
+ hintsIdleSilenceAfter: Number((config.context && config.context.hintsIdleSilenceAfter) ?? 8),
2650
+ statePointer: (config.context && config.context.statePointer) || { enabled: true, maxChars: 300 },
2646
2651
  // v1.5.0 physical routing + session handoff. Read with defaults so an
2647
2652
  // older Host half that has not learned these keys yet still renders.
2648
2653
  autoSpaceFollow: Boolean((config.context && config.context.autoSpaceFollow) ?? false),
@@ -3034,6 +3039,9 @@
3034
3039
  'context.target': Number(draft.context.target),
3035
3040
  'context.injectPrompt': Boolean(draft.context.injectPrompt),
3036
3041
  'context.injectMode': draft.context.injectMode === 'full' ? 'full' : 'index',
3042
+ 'context.mode': draft.context.mode === 'expert' ? 'expert' : 'task',
3043
+ 'context.hintsIdleSilenceAfter': Number(draft.context.hintsIdleSilenceAfter),
3044
+ 'context.statePointer.enabled': Boolean(draft.context.statePointer && draft.context.statePointer.enabled),
3037
3045
  'context.autoSpaceFollow': Boolean(draft.context.autoSpaceFollow),
3038
3046
  'context.autoRolloverEnabled': Boolean(draft.context.autoRolloverEnabled),
3039
3047
  'context.coldStartInjectSummary': Boolean(draft.context.coldStartInjectSummary),
@@ -3602,6 +3610,37 @@
3602
3610
  onChange: (value) => edit('context.injectMode', value),
3603
3611
  disabled,
3604
3612
  }),
3613
+ // v1.7.1: the task/expert switch. It gates TWO behaviours (hint silence and
3614
+ // the state line); the summary-hygiene clean-up above is always on.
3615
+ h(Select, {
3616
+ label: '运行模式(context.mode)',
3617
+ hint: '任务(推荐,构建/调试):提示标签连续 N 次且一次都没换来 recall 就单向静默,并注入一行「当前状态」(仓库 HEAD / 窗口压力)。专家:每个提示都保留,不注入状态行。',
3618
+ value: draft.context.mode === 'expert' ? 'expert' : 'task',
3619
+ options: [
3620
+ { value: 'task', label: '任务(静默无效提示 + 当前状态行)' },
3621
+ { value: 'expert', label: '专家(全量提示,不静默)' },
3622
+ ],
3623
+ onChange: (value) => edit('context.mode', value),
3624
+ disabled,
3625
+ }),
3626
+ h(Field, {
3627
+ label: '提示静默阈值(context.hintsIdleSilenceAfter)',
3628
+ hint: '仅任务模式生效:同一标签连续展示这么多次且从未带来一次 recall,就永久不再出现。默认 8。',
3629
+ value: draft.context.hintsIdleSilenceAfter,
3630
+ min: 1,
3631
+ max: 100,
3632
+ step: 1,
3633
+ onChange: (value) => edit('context.hintsIdleSilenceAfter', value),
3634
+ disabled: disabled || (draft.context.mode === 'expert'),
3635
+ }),
3636
+ h(Toggle, {
3637
+ label: '注入当前状态行(context.statePointer.enabled)',
3638
+ hint: '任务模式有效:在 Prompt 末尾注入一行「仓库 HEAD · 窗口压力」,总长 ≤ maxChars。',
3639
+ checked: Boolean(draft.context.statePointer && draft.context.statePointer.enabled),
3640
+ onChange: (value) =>
3641
+ edit('context.statePointer', { ...(draft.context.statePointer || {}), enabled: value }),
3642
+ disabled,
3643
+ }),
3605
3644
  ),
3606
3645
  h(
3607
3646
  Section,