@jjh32456/longlive 1.8.12 → 2.1.0

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.
Files changed (92) hide show
  1. package/CHANGELOG.md +258 -202
  2. package/QUICKSTART.md +10 -11
  3. package/README.en.md +13 -4
  4. package/README.md +61 -18
  5. package/SPEC.md +3 -3
  6. package/build-info.json +259 -129
  7. package/cordis.patch.yml +32 -1
  8. package/docs/ANSWER-GUARD.md +1 -1
  9. package/docs/ARCHITECTURE.md +3 -3
  10. package/docs/AUTO-RECALL-WIRING.md +5 -3
  11. package/docs/AUTO-RECALL.md +10 -4
  12. package/docs/CONFIG.md +46 -11
  13. package/docs/ERRORS.md +1 -1
  14. package/docs/FAQ.md +9 -9
  15. package/docs/FEATURES.md +19 -16
  16. package/docs/OPERATIONS.md +3 -3
  17. package/docs/PANEL-INTEGRATION.md +1 -1
  18. package/docs/PRIVACY.md +6 -6
  19. package/docs/QUICKSTART.md +5 -5
  20. package/docs/README.en.md +5 -3
  21. package/docs/TOOLS.md +1 -1
  22. package/docs/TROUBLESHOOTING.md +4 -4
  23. package/package.json +6 -3
  24. package/runbook.md +3 -3
  25. package/scripts/migrate-200.mjs +8 -0
  26. package/scripts/migrate-lifecycle.mjs +2 -2
  27. package/src/answer/claim-guard.mjs +234 -0
  28. package/src/backup.js +165 -1
  29. package/src/config.js +18 -7
  30. package/src/features.js +132 -5
  31. package/src/handoff/index.js +133 -0
  32. package/src/handoff/model.js +48 -0
  33. package/src/identity/handover.js +203 -15
  34. package/src/identity/inject-position.js +3 -1
  35. package/src/index.js +2 -2
  36. package/src/memory/a1-migration.js +72 -6
  37. package/src/memory/archive-cold-state.mjs +794 -0
  38. package/src/memory/archive-staging.mjs +305 -0
  39. package/src/memory/archive.mjs +415 -0
  40. package/src/memory/capture-host.js +71 -2
  41. package/src/memory/capture.js +45 -6
  42. package/src/memory/catchup.mjs +534 -0
  43. package/src/memory/conclusion-distill.js +51 -2
  44. package/src/memory/conclusion-drafts.js +7 -3
  45. package/src/memory/conflicts.js +915 -2
  46. package/src/memory/consolidate.js +20 -1
  47. package/src/memory/forget-v2.js +272 -2
  48. package/src/memory/forget.js +20 -1
  49. package/src/memory/frames-activation.js +3 -1
  50. package/src/memory/fts-query.js +2 -2
  51. package/src/memory/index.js +80 -7
  52. package/src/memory/land.mjs +743 -0
  53. package/src/memory/lifecycle.js +128 -0
  54. package/src/memory/maintenance.js +386 -22
  55. package/src/memory/memory-health.mjs +607 -0
  56. package/src/memory/memory-reader.mjs +1003 -0
  57. package/src/memory/migrate-200.js +1681 -0
  58. package/src/memory/migrate-lifecycle.js +3 -3
  59. package/src/memory/procedure-candidate.mjs +377 -0
  60. package/src/memory/procedure.js +20 -1
  61. package/src/memory/prospective-memory.mjs +362 -0
  62. package/src/memory/recall-feedback.mjs +406 -0
  63. package/src/memory/recall-v2.js +13 -1
  64. package/src/memory/recall.js +102 -1
  65. package/src/memory/reinforce.js +138 -2
  66. package/src/memory/retention.js +34 -0
  67. package/src/memory/turn-budget.mjs +290 -0
  68. package/src/memory/wake-bridge.mjs +2999 -0
  69. package/src/memory/working-frame.js +271 -8
  70. package/src/metrics/classify.mjs +3 -1
  71. package/src/recall/archive-config.mjs +130 -0
  72. package/src/recall/archive-fallback.mjs +174 -19
  73. package/src/recall/archive-search.mjs +3 -0
  74. package/src/recall/archive-state.mjs +588 -0
  75. package/src/recall/brain.mjs +501 -0
  76. package/src/recall/continuity-log.mjs +435 -0
  77. package/src/recall/continuity-volatile.mjs +1001 -0
  78. package/src/recall/current-line.mjs +110 -0
  79. package/src/recall/edges.js +21 -2
  80. package/src/recall/explain.mjs +10 -0
  81. package/src/recall/gate-log.mjs +280 -0
  82. package/src/recall/gate-metrics.mjs +191 -0
  83. package/src/recall/index.js +663 -29
  84. package/src/recall/inject-order.mjs +3 -1
  85. package/src/recall/link-fastpath.mjs +662 -0
  86. package/src/recall/recall-core.mjs +74 -2
  87. package/src/recall/turn-budget-inject.mjs +154 -0
  88. package/src/retention/cold-gate.mjs +146 -0
  89. package/src/retention/config.js +58 -1
  90. package/src/retention/index.js +193 -35
  91. package/src/router/design-headings.json +10 -10
  92. package/src/tools.js +122 -6
package/docs/TOOLS.md CHANGED
@@ -116,7 +116,7 @@
116
116
  |---|---|---|
117
117
  | `memory_save` | engram 插件 | 本插件只在 R1 里拦它(`routerRuntime: on` 时可能拒绝高风险写) |
118
118
  | `send_meme` / `web_search` / `acp_*` | 宿主或其他插件 | 与本插件无关,不要写进本插件的运维文档当能力 |
119
- | `router_status` / `router_tick` / `router_ask` / `router_report` | 本插件(1.1.0,默认关闭) | `routerEnabled: true` 才注册;打开后 22→26。`routerProposalEnabled: true` 再加 `router_propose` / `router_proposals` / `router_apply`(26→29);这三个里的 apply 还要 `routerApplyEnabled: true` 才真正写盘。默认配置下**一个都不会出现** |
119
+ | `router_status` / `router_tick` / `router_ask` / `router_report` | 本插件(1.1.0,默认关闭) | `routerEnabled: true` 才注册;打开后 22→26。`routerProposalEnabled: true` 再加 `router_propose` / `router_proposals` / `router_apply`(31→34);这三个里的 apply 还要 `routerApplyEnabled: true` 才真正写盘。默认配置下**一个都不会出现** |
120
120
  | 常驻守护 / 定时任务 | **没有** | 1.1.0 仍不注册计划任务、不起 daemon。RouterService 是插件进程内的后台服务,随 `apply()` 起停;`auto-truncate-run.ps1` 是**一次性**脚本(见 `OPERATIONS.md`) |
121
121
  | scope 打分 / 过滤器 | **规划中** | 面板"过滤器决策"页 `implemented:false`;没有对应工具或配置(Router 的 L1/L2 是上下文注入,不是 scope 打分) |
122
122
 
@@ -1,4 +1,4 @@
1
- # TROUBLESHOOTING.md — 按症状查(1.8.12)
1
+ # TROUBLESHOOTING.md — 按症状查(2.0.0)
2
2
 
3
3
  用法:先看「症状」,对不上再看「最可能原因」。每条只给**一条**验证命令——先确认判断,再动手。
4
4
  「什么时候该停手」比「怎么修」更重要:结构一旦不对,继续重试只会扩大损失。
@@ -41,9 +41,9 @@
41
41
 
42
42
  ## 2. 侧栏没有「潜望镜」
43
43
 
44
- **症状**:Web GUI 左侧看不到面板入口。1.8.0 面板侧 `GET /api/longlive-panel/v2/state` 返回 27 条路由 / 18 个动作;「本轮想起」审计入口读 `.longlive/recall-log.jsonl`。
44
+ **症状**:Web GUI 左侧看不到面板入口。2.0.0 面板侧只读状态接口(`PANEL_API_VERSION=3`;ROUTES 16、18 个受控动作);「本轮想起」审计入口读 `.longlive/recall-log.jsonl`。
45
45
 
46
- **最可能原因**:面板是**独立可选包** `@jjh32456/dsh-longlive-panel@1.8.0`,这一轮根本没装;
46
+ **最可能原因**:面板是**独立可选包** `@jjh32456/dsh-longlive-panel@2.1.0`,这一轮根本没装;
47
47
  或者只 `plugin add` 了、没加进 profile 的 `dsh.profile.bundles`,bundle patch 不生效;
48
48
  或者当前 profile 不是 `desktop`、宿主没重启。
49
49
 
@@ -54,7 +54,7 @@
54
54
  ```
55
55
 
56
56
  **修法**:
57
- 1. 安装独立可选包 `@jjh32456/dsh-longlive-panel@1.8.0`(装法见该包的 `INSTALL.md`);
57
+ 1. 安装独立可选包 `@jjh32456/dsh-longlive-panel@2.1.0`(装法见该包的 `INSTALL.md`);
58
58
  2. 在 `$P\package.json` 的 `dsh.profile.bundles` 里加入 `@jjh32456/dsh-longlive-panel`;
59
59
  3. 重启宿主,刷新页面。
60
60
  (两步缺一不可;只装不加 bundles,patch 不会应用。)
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@jjh32456/longlive",
3
- "version": "1.8.12",
3
+ "version": "2.1.0",
4
4
  "type": "module",
5
- "description": "久视(longlive):一个磁盘上的共享大脑,让每个会话都是同一个你——记忆卡、状态卡、开机卡让新会话接上同一段关系与未完成的事;配套会话卫生(热截断/备份/D2/D6 裁剪)与记忆工具(巩固/召回/程序性记忆)。1.6.8 在 1.6.7 之上并入共享大脑活动流(sharedBrain.activity:事件级活动写入、判重/蒸馏、只带新增的增量注入,默认关闭)与共享板状态诚实性修复(running 计数、焦点新鲜度、turn 状态、开机卡时效);热截断与 1.6.7 相同。",
5
+ "description": "久视(longlive):磁盘上的共享大脑——记忆卡、状态卡、开机卡让每个会话接上同一段关系与未完成的事;2.0 加入硬门(记忆治理)、工作帧、选择性遗忘、冲突候选、冷档离线 fail-closed、唤醒桥、每日体检与面板审批区;配套会话卫生(热截断/备份/D2/D6 裁剪)与记忆工具(巩固/召回/程序性记忆)。",
6
6
  "keywords": [
7
7
  "dsh",
8
8
  "deepseek-harness",
@@ -17,7 +17,9 @@
17
17
  "cordis",
18
18
  "plugin",
19
19
  "auto-recall",
20
- "presence-bus"
20
+ "presence-bus",
21
+ "hardgate",
22
+ "wake-bridge"
21
23
  ],
22
24
  "author": "longlive contributors",
23
25
  "license": "MIT",
@@ -118,6 +120,7 @@
118
120
  "scripts/migrate-lifecycle.mjs",
119
121
  "scripts/backfill-auto-cards.mjs",
120
122
  "scripts/migrate-a1-legacy.mjs",
123
+ "scripts/migrate-200.mjs",
121
124
  "scripts/verify-card-anchors.mjs",
122
125
  "scripts/surgery-inspect.mjs",
123
126
  "scripts/auto-truncate-run.ps1",
package/runbook.md CHANGED
@@ -67,7 +67,7 @@ session_compact { sessionPath: "...", dryRun: false } // 真压
67
67
  四步全过才允许真写(`confirm: "TRUNCATE"`)。真写之后**还要重启一次**,确认会话能打开、
68
68
  而且我能回出一句话——那是第五步,也是唯一能证明「记忆没丢」的一步。
69
69
 
70
- ## 1.7 装/升级后:先证明 21 个工具真的注册(发布闸门)
70
+ ## 1.7 装/升级后:先证明 21 个工具真的注册
71
71
 
72
72
  `dsh plugin ... add` 成功、`--dump-config` 里有 entry,都**不等于**插件激活。0.7.3 就是这样:
73
73
  `list` 显示 `@0.7.3`、dump 里一条 entry,起 web 宿主却只打
@@ -82,7 +82,7 @@ session_compact { sessionPath: "...", dryRun: false } // 真压
82
82
  3. **21 个工具在**:有模型凭据时,会话里调 `session_health` / `memory_index` / `session_live_list` /
83
83
  `session_wake` 各一次;没有凭据时,第 2 条就是无凭据的替代验证。
84
84
 
85
- 发布闸门(缺一条不许出包):
85
+ 装后自检(逐项核对):
86
86
 
87
87
  ```powershell
88
88
  # 1) 单元/契约套件;T27 会在「会抛 inject 错」的代理 ctx 上调用版本探测
@@ -99,7 +99,7 @@ T7 需要 `DSH_EXE` 与 `DSH_CLI_JS` 指向真实宿主(见 `test/t7_drive.mjs
99
99
 
100
100
  ## 1.8 1.8.6 发布安装窗(N4:三项资产检查,缺任一项不许 publish)
101
101
 
102
- 这一节是 1.8.6 新增的发布门;它不改变安装步骤,只把「替换宿主目录之前必须做完的三件事」
102
+ 这一节是 1.8.6 新增的;它不改变安装步骤,只把「替换宿主目录之前必须做完的三件事」
103
103
  写成可检查的清单。执行者:**lead 本人**(或 lead 明确授权的脚本),不是后台代理。
104
104
 
105
105
  1. **谁在替换前停宿主**:由 lead 本人在场确认,按 runbook 停宿主(先退 DSH,进程不在运行时
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env node
2
+ // B7 CLI 入口:1.8.x → 2.0.0 迁移 + 冷层迁移二次 approve(plan/backup/manifest 三件套)。
3
+ // 默认 dry-run 只读;数据移动必须 plan --write → 第一次 approve → apply(备份) → 第二次 approve → apply。
4
+ // 详细契约见 src/memory/migrate-200.js 文件头与 M200-DRAFT-REPORT.md。
5
+ import { main } from '../src/memory/migrate-200.js';
6
+
7
+ const exitCode = await main(process.argv.slice(2));
8
+ process.exitCode = exitCode;
@@ -104,10 +104,10 @@ const planPath = resolveDefaultPlanPath({
104
104
  planPath: typeof args.plan === 'string' ? args.plan : null,
105
105
  });
106
106
 
107
- // 1.8.12 隐私修复:npm 包不再随附 lifecycle-plan.json(逐字含真实记忆内容)。
107
+ // 1.8.13 隐私修复:npm 包不再随附 lifecycle-plan.json(逐字含真实记忆内容)。
108
108
  // plan/dry-run/apply 在找不到计划时给出明确指引,而不是抽象 E_PLAN_MISSING。
109
109
  if ((mode === 'plan' || mode === 'dry-run' || mode === 'apply') && !fs.existsSync(planPath)) {
110
- fail('E_PLAN_MISSING', `lifecycle 迁移映射不在 npm 包内(1.8.12 起):${planPath}。`
110
+ fail('E_PLAN_MISSING', `lifecycle 迁移映射不在 npm 包内(1.8.13 起):${planPath}。`
111
111
  + '请用 --plan 指定仓库内 src/memory/lifecycle-plan.json,或把计划放到 <memoryRoot>/.longlive/lifecycle-plan.json。', {
112
112
  planPath,
113
113
  memoryRoot: root,
@@ -0,0 +1,234 @@
1
+ // src/answer/claim-guard.mjs — D22 防编(W2 写侧,批 D)
2
+ //
3
+ // 设计依据(计划 v3.6.4 §4⑪ / §15 裁决):
4
+ // * 只读复用 answer/guard.js(HISTORY_CLAIM_RE / TOOL_CLAIM_RE / extractNumberClaims /
5
+ // SOURCE_GATE_HARD_CODES / auditTurn),不新建分析器、不改 guard.js / audit.js;
6
+ // * 触发点 = 宿主 pre-step 扫上一轮 assistant 文本(W4:src/recall/index.js),
7
+ // 不改 answer/index.js(含 :932)、不增改性点;
8
+ // * 命中 requires-source 时注入一条 ≤50 字的提醒(「称『我记得/上次』须指卡」),
9
+ // 同时经 recall/gate-log.mjs 的 appendGateLog 写 hg.d22.fail(decision=fail),
10
+ // 不阻断回答;分析失败一律 catch(写 warn),不得把主流程拖垮。
11
+ //
12
+ // fail-closed:参数缺失返回结构化错误码(不抛进调用方主流程的,是 apply/record 这类
13
+ // 预处理器;scanClaimGuard 作为纯函数在文本非法时也返回 ok:false 而不是编一个结果)。
14
+
15
+ import {
16
+ HISTORY_CLAIM_RE,
17
+ SOURCE_GATE_HARD_CODES,
18
+ auditTurn,
19
+ isAbstention,
20
+ } from './guard.js';
21
+ import { appendGateLog } from '../recall/gate-log.mjs';
22
+
23
+ export const BATCH = 'D';
24
+ export const SKELETON = Object.freeze({ version: '2.0.0', failClosed: true, implemented: true });
25
+ export const REQUIRES_SOURCE_MARK = 'requires-source';
26
+ export const INJECT_BUDGET_CHARS = 50;
27
+ export const GATE_EVENT = 'hg.d22.fail';
28
+ export const UNIMPLEMENTED_CODE = 'E_HG_CLAIM_GUARD_UNIMPLEMENTED';
29
+
30
+ export const FLAG_CODES = Object.freeze([
31
+ 'HISTORY_CLAIM_NO_CITATION',
32
+ 'ANSWERED_WITHOUT_EVIDENCE',
33
+ 'FAKE_TOOL_CLAIM',
34
+ 'UNGROUNDED_NUMBER',
35
+ 'FAKE_TURN_REF',
36
+ 'FAKE_CARD_REF',
37
+ ]);
38
+
39
+ /** 命中 requires-source 时的注入前缀(计划原文:「称『我记得/上次』须指卡」)。 */
40
+ export const INJECT_PREFIX = '称『我记得/上次』须指卡:';
41
+
42
+ function clip(text, max) {
43
+ const chars = Array.from(String(text ?? ''));
44
+ if (chars.length <= max) return chars.join('');
45
+ return chars.slice(0, Math.max(0, max - 1)).join('') + '…';
46
+ }
47
+
48
+ function isHardFlag(flag) {
49
+ if (!flag || typeof flag.code !== 'string') return false;
50
+ return flag.severity === 'fabrication' || SOURCE_GATE_HARD_CODES.includes(flag.code);
51
+ }
52
+
53
+ function buildInjectText(flags) {
54
+ const codes = [...new Set(flags.filter(isHardFlag).map((flag) => flag.code))].slice(0, 3);
55
+ const body = codes.length > 0 ? `${INJECT_PREFIX}${codes.join('/')}` : `${INJECT_PREFIX}先指卡再答`;
56
+ return clip(body, INJECT_BUDGET_CHARS);
57
+ }
58
+
59
+ /**
60
+ * 纯扫描:把一段 assistant 文本交给 guard.auditTurn 判定,登记防编结果。
61
+ *
62
+ * @param {object} input {text, turn?, question?, historyQuestion?, zeroHit?, evidenceTurns?,
63
+ * evidenceUnits?, toolNames?, sessionToolNames?, sessionTurns?, knownTools?, cardExists?,
64
+ * contextText?, contextTruncated?, canAbstain?, difficulty?, questionType?, now?}
65
+ * @returns {{ok:boolean,code?:string,requiresSource:boolean,hardCodes:string[],flags:object[],
66
+ * injectText:string,verdict:string|null,evidence:object}}
67
+ */
68
+ export function scanClaimGuard(input = {}) {
69
+ const text = String(input?.text ?? '');
70
+ if (text.trim() === '') {
71
+ return {
72
+ ok: false,
73
+ code: 'E_HG_D22_NO_TEXT',
74
+ requiresSource: false,
75
+ hardCodes: [],
76
+ flags: [],
77
+ injectText: '',
78
+ verdict: null,
79
+ evidence: { reason: 'empty-text' },
80
+ };
81
+ }
82
+ let audit;
83
+ try {
84
+ audit = auditTurn({
85
+ text,
86
+ turn: Number.isInteger(Number(input.turn)) ? Number(input.turn) : 0,
87
+ question: String(input.question ?? text),
88
+ historyQuestion: input.historyQuestion === true || HISTORY_CLAIM_RE.test(text),
89
+ zeroHit: input.zeroHit === true,
90
+ evidenceTurns: Array.isArray(input.evidenceTurns) ? input.evidenceTurns : [],
91
+ evidenceUnits: input.evidenceUnits,
92
+ toolNames: Array.isArray(input.toolNames) ? input.toolNames : [],
93
+ sessionToolNames: Array.isArray(input.sessionToolNames) ? input.sessionToolNames : [],
94
+ sessionTurns: Array.isArray(input.sessionTurns) ? input.sessionTurns : [],
95
+ knownTools: Array.isArray(input.knownTools) ? input.knownTools : [],
96
+ cardExists: typeof input.cardExists === 'function' ? input.cardExists : () => true,
97
+ contextText: String(input.contextText ?? ''),
98
+ contextTruncated: input.contextTruncated === true,
99
+ canAbstain: input.canAbstain === true,
100
+ difficulty: String(input.difficulty ?? ''),
101
+ questionType: String(input.questionType ?? ''),
102
+ now: input.now,
103
+ sessionId: input.sessionId,
104
+ });
105
+ } catch (error) {
106
+ return {
107
+ ok: false,
108
+ code: 'E_HG_D22_AUDIT_FAILED',
109
+ requiresSource: false,
110
+ hardCodes: [],
111
+ flags: [],
112
+ injectText: '',
113
+ verdict: null,
114
+ evidence: { reason: 'audit-threw', message: clip(error?.message ?? String(error), 200) },
115
+ };
116
+ }
117
+ const flags = Array.isArray(audit.flags) ? audit.flags : [];
118
+ const hardCodes = [...new Set(flags.filter(isHardFlag).map((flag) => flag.code))];
119
+ const requiresSource = hardCodes.length > 0;
120
+ const zeroHit = audit.zeroHit === true;
121
+ return {
122
+ ok: true,
123
+ requiresSource,
124
+ hardCodes,
125
+ flags,
126
+ injectText: requiresSource ? buildInjectText(flags) : '',
127
+ verdict: typeof audit.verdict === 'string' ? audit.verdict : null,
128
+ evidence: {
129
+ mode: audit.answerMode ?? null,
130
+ zeroHit,
131
+ abstained: isAbstention(text),
132
+ historyQuestion: audit.historyQuestion === true,
133
+ turnRefs: audit.checks?.turnRefs ?? [],
134
+ cardRefs: audit.checks?.cardRefs ?? [],
135
+ },
136
+ };
137
+ }
138
+
139
+ /**
140
+ * 写 hg.d22.fail(唯一门事件入口:appendGateLog)。
141
+ * 失败吞掉(返回 written:false),调用方据此只记录 warn。
142
+ */
143
+ export function recordClaimGuardFailure(input = {}) {
144
+ const memoryRoot = input?.memoryRoot;
145
+ if (typeof memoryRoot !== 'string' || memoryRoot.trim() === '') {
146
+ return { ok: false, code: 'E_HG_D22_NO_ROOT', written: false };
147
+ }
148
+ const at = input.now instanceof Date ? input.now : new Date(input.now ?? Date.now());
149
+ const codes = Array.isArray(input.codes) ? input.codes : [];
150
+ const reason = codes.length > 0 ? codes.join('+') : String(input.code ?? 'E_HG_D22_FAIL');
151
+ try {
152
+ appendGateLog(memoryRoot, {
153
+ at: at.toISOString(),
154
+ sessionId: input.sessionId,
155
+ turn: Number.isInteger(Number(input.turn)) ? Number(input.turn) : undefined,
156
+ gate: GATE_EVENT,
157
+ decision: 'fail',
158
+ reason,
159
+ evidence: [String(input.detail ?? ''), ...codes].filter((item) => item !== ''),
160
+ });
161
+ return { ok: true, written: true, gate: GATE_EVENT, reason };
162
+ } catch (error) {
163
+ return {
164
+ ok: false,
165
+ written: false,
166
+ code: 'E_HG_D22_GATELOG_FAILED',
167
+ message: clip(error?.message ?? String(error), 200),
168
+ };
169
+ }
170
+ }
171
+
172
+ /**
173
+ * 预处理器:扫描上一轮 assistant 文本,requires-source 时生成注入提醒并写门事件。
174
+ * 永不 throw(catch 后 warn),返回结构化结果供 W4 合并注入。
175
+ */
176
+ export function applyClaimGuard(context = {}) {
177
+ const memoryRoot = context?.memoryRoot;
178
+ const warn = typeof context.warn === 'function' ? context.warn : null;
179
+ const text = String(context?.text ?? '');
180
+ if (text.trim() === '') {
181
+ return { ok: true, requiresSource: false, injectText: '', gateWritten: false, code: 'E_HG_D22_NO_TEXT' };
182
+ }
183
+ try {
184
+ const scan = scanClaimGuard({
185
+ text,
186
+ turn: context.turn,
187
+ question: context.question,
188
+ historyQuestion: context.historyQuestion,
189
+ zeroHit: context.zeroHit,
190
+ evidenceTurns: context.evidenceTurns,
191
+ evidenceUnits: context.evidenceUnits,
192
+ toolNames: context.toolNames,
193
+ sessionToolNames: context.sessionToolNames,
194
+ sessionTurns: context.sessionTurns,
195
+ knownTools: context.knownTools,
196
+ cardExists: context.cardExists,
197
+ contextText: context.contextText,
198
+ contextTruncated: context.contextTruncated,
199
+ canAbstain: context.canAbstain,
200
+ difficulty: context.difficulty,
201
+ questionType: context.questionType,
202
+ now: context.now,
203
+ sessionId: context.sessionId,
204
+ });
205
+ if (!scan.ok) {
206
+ warn?.(`[claim-guard] scan 未完成(${scan.code}):${scan.evidence?.message ?? ''}`);
207
+ return { ok: false, requiresSource: false, injectText: '', gateWritten: false, code: scan.code };
208
+ }
209
+ if (!scan.requiresSource) {
210
+ return { ok: true, requiresSource: false, injectText: '', gateWritten: false, code: null, flags: scan.flags };
211
+ }
212
+ const record = recordClaimGuardFailure({
213
+ memoryRoot,
214
+ sessionId: context.sessionId,
215
+ turn: context.turn,
216
+ now: context.now,
217
+ codes: scan.hardCodes,
218
+ detail: clip(text, 200),
219
+ });
220
+ if (!record.ok) warn?.(`[claim-guard] 门事件写入失败(${record.code}):${record.message ?? ''}`);
221
+ return {
222
+ ok: true,
223
+ requiresSource: true,
224
+ injectText: scan.injectText,
225
+ gateWritten: record.written === true,
226
+ code: REQUIRES_SOURCE_MARK,
227
+ flags: scan.flags,
228
+ hardCodes: scan.hardCodes,
229
+ };
230
+ } catch (error) {
231
+ warn?.(`[claim-guard] apply 异常已吞(${error?.code ?? 'E_HG_D22_INTERNAL'}):${error?.message ?? error}`);
232
+ return { ok: false, requiresSource: false, injectText: '', gateWritten: false, code: 'E_HG_D22_INTERNAL' };
233
+ }
234
+ }
package/src/backup.js CHANGED
@@ -10,6 +10,14 @@ import fs from 'node:fs';
10
10
  import path from 'node:path';
11
11
  import crypto from 'node:crypto';
12
12
 
13
+ import { appendGateLog } from './recall/gate-log.mjs';
14
+
15
+ // 批 C(M22):备份是写路径的前置条件。备份不可用时必须 fail-closed,
16
+ // 对外只认一个错误码:E_HG_BACKUP。
17
+ export const BACKUP_ERROR_CODE = 'E_HG_BACKUP';
18
+ export const BACKUP_KEEP = 7;
19
+ const BACKUP_IO_CODES = ['EPERM', 'EACCES', 'EROFS', 'EBUSY', 'ENOSPC', 'ENOTDIR', 'EMFILE', 'ENFILE'];
20
+
13
21
  export function sha256File(file) {
14
22
  const hash = crypto.createHash('sha256');
15
23
  hash.update(fs.readFileSync(file));
@@ -98,7 +106,15 @@ export function nextBackupPath(sessionPath, date = new Date(), expected = null)
98
106
  * from the file we just wrote. A concurrent append therefore cannot slip into a
99
107
  * backup that claims to represent the bytes the plan was built from.
100
108
  */
101
- export function ensureBackup(sessionPath, { date = new Date(), sourceBuf = null, sha256: expectedSha = null, size = null } = {}) {
109
+ export function ensureBackup(sessionPath, options = {}) {
110
+ try {
111
+ return ensureBackupUnsafe(sessionPath, options);
112
+ } catch (error) {
113
+ throw asBackupError(error, sessionPath);
114
+ }
115
+ }
116
+
117
+ function ensureBackupUnsafe(sessionPath, { date = new Date(), sourceBuf = null, sha256: expectedSha = null, size = null } = {}) {
102
118
  const source = sourceBuf ?? fs.readFileSync(sessionPath);
103
119
  const bytes = size ?? source.length;
104
120
  if (source.length !== bytes) {
@@ -144,3 +160,151 @@ export function verifyBackup(file, expectedSha256) {
144
160
  }
145
161
  return { ok: true, sha256: actual };
146
162
  }
163
+
164
+ // ---------------------------------------------------------------------------
165
+ // 批 C(M22):backup fail-closed 四守卫 + 保留上限
166
+ // ---------------------------------------------------------------------------
167
+
168
+ export function backupError(code, message, cause = null) {
169
+ const error = new Error(message ?? String(code));
170
+ error.name = 'HardgateBackupError';
171
+ error.code = code;
172
+ if (cause) error.cause = cause;
173
+ return error;
174
+ }
175
+
176
+ /** 任何 IO 拒绝(EPERM/EACCES/只读/磁盘满…)统一转 E_HG_BACKUP;业务错误原样透传。 */
177
+ export function asBackupError(error, sessionPath = '') {
178
+ if (!error) return backupError(BACKUP_ERROR_CODE, '备份失败(未知原因)');
179
+ if (error.code === BACKUP_ERROR_CODE) return error;
180
+ if (BACKUP_IO_CODES.includes(error.code)) {
181
+ return backupError(
182
+ BACKUP_ERROR_CODE,
183
+ `备份不可用,拒写(${error.code})${sessionPath ? `:${sessionPath}` : ''}`,
184
+ error,
185
+ );
186
+ }
187
+ return error;
188
+ }
189
+
190
+ /**
191
+ * 写前守卫 1:备份必须先成功,返回备份回执;备份失败抛 E_HG_BACKUP。
192
+ */
193
+ export function assertBackupReady(sessionPath, options = {}) {
194
+ if (typeof sessionPath !== 'string' || sessionPath.trim() === '') {
195
+ throw backupError(BACKUP_ERROR_CODE, 'assertBackupReady 缺少 sessionPath:无法确认备份,拒写');
196
+ }
197
+ return ensureBackup(sessionPath, options);
198
+ }
199
+
200
+ /**
201
+ * 写前守卫 2:备份成功后再执行 writer(backup)。
202
+ * writer 抛错时备份保留(可回滚),错误原样抛出(不伪装成成功)。
203
+ */
204
+ export function ensureBackupThenWrite(input = {}, writer = null) {
205
+ const sessionPath = input.sessionPath;
206
+ const backup = assertBackupReady(sessionPath, {
207
+ date: input.date ?? new Date(),
208
+ sourceBuf: input.sourceBuf ?? null,
209
+ sha256: input.sha256 ?? null,
210
+ size: input.size ?? null,
211
+ });
212
+ const run = typeof writer === 'function' ? writer : (typeof input.writer === 'function' ? input.writer : null);
213
+ if (!run) return { ok: true, backup, written: false };
214
+ const written = run(backup);
215
+ return { ok: true, backup, written };
216
+ }
217
+
218
+ /**
219
+ * 写前守卫 3:guardedWrite。给卡片/状态写盘用:先备份会话日志,再原子写
220
+ * target(缺省 false 时只做备份守卫)。任何备份失败都拒绝落盘。
221
+ */
222
+ export function guardedWrite(input = {}) {
223
+ const sessionPath = String(input.sessionPath ?? '').trim();
224
+ if (sessionPath === '') {
225
+ throw backupError(BACKUP_ERROR_CODE, 'guardedWrite 缺少 sessionPath:无法确认备份,拒写');
226
+ }
227
+ const backup = assertBackupReady(sessionPath, {
228
+ date: input.date ?? new Date(),
229
+ sourceBuf: input.sourceBuf ?? null,
230
+ sha256: input.sha256 ?? null,
231
+ size: input.size ?? null,
232
+ });
233
+ const target = String(input.path ?? input.cardPath ?? '').trim();
234
+ if (target === '') return { ok: true, backup, written: false };
235
+ if (typeof input.writer === 'function') {
236
+ return { ok: true, backup, written: input.writer(backup) };
237
+ }
238
+ const file = path.isAbsolute(target) ? target : path.resolve(input.memoryRoot ?? process.cwd(), target);
239
+ const content = String(input.content ?? '');
240
+ const dir = path.dirname(file);
241
+ try {
242
+ fs.mkdirSync(dir, { recursive: true });
243
+ const tmp = `${file}.tmp-${process.pid}-${Date.now()}`;
244
+ fs.writeFileSync(tmp, content, 'utf8');
245
+ fs.renameSync(tmp, file);
246
+ } catch (error) {
247
+ throw asBackupError(error, file);
248
+ }
249
+ return { ok: true, backup, written: true, path: file, bytes: Buffer.byteLength(content, 'utf8') };
250
+ }
251
+
252
+ /** 写前守卫 4:writeWithBackup = guardedWrite 的可注入 writer 形态(旧名兼容)。 */
253
+ export function writeWithBackup(input = {}, writer = null) {
254
+ const opts = writer ? { ...input, writer } : input;
255
+ return guardedWrite(opts);
256
+ }
257
+
258
+ /**
259
+ * 保留上限(7 份):只删本会话自己的 .bak-* 副本,不碰 ledger 与其他文件。
260
+ * 删除前写 gate-log(备份可回滚,删的是重复副本);默认 dryRun=false 由调用方显式开启。
261
+ */
262
+ export function pruneBackups({ sessionPath, memoryRoot = null, keep = BACKUP_KEEP, now = new Date(), dryRun = false } = {}) {
263
+ const session = String(sessionPath ?? '').trim();
264
+ if (session === '') return { ok: false, error: 'session-path-missing', removed: [], kept: 0 };
265
+ const backups = listBackups(session);
266
+ const keepN = Math.max(1, Math.floor(Number(keep) || BACKUP_KEEP));
267
+ const excess = backups.slice(0, Math.max(0, backups.length - keepN));
268
+ const removed = [];
269
+ for (const item of excess) {
270
+ if (dryRun) {
271
+ removed.push({ file: item.file, dryRun: true });
272
+ continue;
273
+ }
274
+ try {
275
+ fs.unlinkSync(item.file);
276
+ removed.push({ file: item.file });
277
+ } catch (error) {
278
+ return { ok: false, error: String(error?.code ?? error), removed, kept: backups.length - removed.length };
279
+ }
280
+ }
281
+ // ledger 里只保留现存副本,避免下次读到幽灵记录。
282
+ if (!dryRun && removed.length > 0) {
283
+ try {
284
+ const ledger = readLedger(session);
285
+ const present = new Set(listBackups(session).map((item) => item.file));
286
+ ledger.backups = ledger.backups.filter((entry) => present.has(entry.file));
287
+ writeLedger(session, ledger);
288
+ } catch (error) {
289
+ return { ok: false, error: String(error?.code ?? error), removed, kept: backups.length - removed.length };
290
+ }
291
+ }
292
+ if (removed.length > 0 && memoryRoot) {
293
+ try {
294
+ appendGateLog(memoryRoot, {
295
+ gate: 'backup.prune',
296
+ decision: 'ok',
297
+ reason: 'backup.prune',
298
+ evidence: removed.map((item) => path.basename(item.file)),
299
+ at: (now instanceof Date ? now : new Date(now ?? Date.now())).toISOString(),
300
+ sessionId: null,
301
+ turn: null,
302
+ });
303
+ } catch {
304
+ // gate-log 写失败不回滚删除(副本已不在,账可事后补)
305
+ }
306
+ }
307
+ return { ok: true, removed, kept: backups.length - removed.length, dryRun, keep: keepN };
308
+ }
309
+
310
+ export { pruneBackups as cleanupBackups, pruneBackups as enforceBackupRetention, pruneBackups as retainBackups, pruneBackups as trimBackups };
package/src/config.js CHANGED
@@ -93,7 +93,7 @@ const ZH = {
93
93
  $description: '自动想起:按轮次从记忆库召回卡片并注入上下文。',
94
94
  enabled: '开启自动想起(默认开启;显式 false 关闭)。',
95
95
  topK: '每次召回的最大卡片数(默认 3,范围 1–10)。',
96
- budgetTokens: '每次召回的 token 预算(默认 2000,范围 200–2000)。',
96
+ budgetTokens: '每次召回的 token 预算(默认 2000,范围 200–2000)。B3 起每轮注入走字符车道:九项合计 2000 字符(≈1000 token,见 src/memory/turn-budget.mjs),召回块自身 ≤990 字符;本项同时作为字符车道上限使用(2000 字符),不再是纯 token 口径。',
97
97
  everyNTurns: '每 N 轮召回一次(默认 6;1.8.8 起强制触发路径不再受它限制)。',
98
98
  forceOnUserMessage: '1.8.8:每条真实用户任务消息都强制召回一次(默认 true;显式 false 完全回落 1.8.7 的按轮次/话题切换触发)。纯应答(好/嗯/继续/谢谢/收到)不触发。',
99
99
  },
@@ -118,10 +118,10 @@ const ZH = {
118
118
  },
119
119
  },
120
120
  identityCard: {
121
- $description: '身份卡:在每次对话前置注入 STATE.md 摘要。',
121
+ $description: '身份卡:在每次对话前置注入 STATE.md 摘要。recentBudgetChars(最近三件预算,默认 1161)与 handoffSummary(交接摘要承接,默认开启)按块内非严格解析透传,不新增 schema 叶子(153 节点锁)。',
122
122
  enabled: '开启身份卡注入(默认开启;显式 false 关闭)。',
123
123
  path: '身份卡路径(默认 <memoryRoot>/STATE.md)。',
124
- maxChars: '身份卡最多注入的字符数(默认 800,范围 120–4000)。',
124
+ maxChars: '身份卡最多注入的字符数(默认 2233,范围 120–4000)。',
125
125
  },
126
126
  presenceBus: {
127
127
  $description: '共享大脑:消费其他会话写入总线的消息。',
@@ -371,10 +371,10 @@ const EN = {
371
371
  },
372
372
  },
373
373
  identityCard: {
374
- $description: 'Identity card: prepend a STATE.md digest at the start of the conversation.',
374
+ $description: 'Identity card: prepend a STATE.md digest at the start of the conversation. recentBudgetChars (recent-section budget, default 1161) and handoffSummary (handoff-summary carry-over, on by default) pass through the block via non-strict parsing and add no schema leaves (153-node lock).',
375
375
  enabled: 'Enable identity-card injection (on by default; explicitly false opts out).',
376
376
  path: 'Identity-card path (default <memoryRoot>/STATE.md).',
377
- maxChars: 'Maximum characters injected (default 800, range 120–4000).',
377
+ maxChars: 'Maximum characters injected (default 2233, range 120–4000).',
378
378
  },
379
379
  presenceBus: {
380
380
  $description: 'Shared brain: consume messages other sessions write to the bus.',
@@ -562,10 +562,13 @@ function schemaOf() {
562
562
  everyNTurns: z.number().default(6).description(ZH.autoRecall.everyNTurns),
563
563
  }).collapse();
564
564
 
565
+ // M05(DESIGN §8 C):maxChars 默认对齐生产契约 2233。recentBudgetChars / handoffSummary
566
+ // 不声明 schemastery 叶子:settings schema 节点数与 1.8.3 锁死一致 153;schemastery
567
+ // 非严格解析会把块内未声明键合并回解析结果(test/config-schema.test.mjs「未知键保留」)。
565
568
  const identityCard = z.object({
566
569
  enabled: z.boolean().default(true).description(ZH.identityCard.enabled),
567
570
  path: z.string().default('<memoryRoot>/STATE.md').description(ZH.identityCard.path),
568
- maxChars: z.number().default(800).description(ZH.identityCard.maxChars),
571
+ maxChars: z.number().default(2233).description(ZH.identityCard.maxChars),
569
572
  }).collapse();
570
573
 
571
574
  const presenceBus = z.object({
@@ -719,7 +722,8 @@ function schemaOf() {
719
722
  enabled: z.boolean().default(false).description(ZH.retention.enabled),
720
723
  dryRun: z.boolean().default(true).description(ZH.retention.dryRun),
721
724
  intervalMs: z.number().default(86400000).description(ZH.retention.intervalMs),
722
- runOnStart: z.boolean().default(true).description(ZH.retention.runOnStart),
725
+ // 批 C(M25):启动瞬间不跑清理;先门禁(冷档校验 + approve)再执行。
726
+ runOnStart: z.boolean().default(false).description(ZH.retention.runOnStart),
723
727
  hotTruncate: z.object({
724
728
  maxBytes: z.number().default(2147483648).description(ZH.retention.hotTruncate.maxBytes),
725
729
  maxAgeDays: z.number().default(14).description(ZH.retention.hotTruncate.maxAgeDays),
@@ -795,6 +799,13 @@ function schemaOf() {
795
799
  // config.proactive / config.handoff / config.tiering 仍是原始行配置,归一化分别由
796
800
  // normalizeProactiveConfig / normalizeHandoffConfig / normalizeTiering 从 raw config 读取;
797
801
  // 配置文案见上方 ZH/EN.tiering、ZH/EN.proactive、ZH/EN.handoff。
802
+ //
803
+ // H 批 hardgate 唤醒桥(N15)也走同一 passthrough 路线:config.hardgate.wake 不声明 leaf
804
+ // (153 节点锁不变),只允许 6 个运维键 enabled/triggers/maxPerDay/cooldownSec/timeoutSec/
805
+ // toolExclude(其余键 maxRounds/maxOutputTokens/maxOutputChars/retryMax/ticketTtlHours/
806
+ // queueMax/maxFilesPerRun/allowTools/preset/approvalPolicy 走代码默认、只可收紧)。
807
+ // 归一化 + 钳制在 src/memory/wake-bridge.mjs 的 normalizeWakeConfig(越界 clamp + warn +
808
+ // 下次 run 审计 configClamps),接线见 src/features.js 的 registerHardgateWake 块。
798
809
 
799
810
  d2,
800
811
  d6,