@furongjun1999/dsh-memory 0.9.22 → 0.10.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.
Files changed (179) hide show
  1. package/CHANGELOG.en.md +450 -0
  2. package/CHANGELOG.md +112 -0
  3. package/README.en.md +244 -0
  4. package/README.md +272 -260
  5. package/codebuddy/CODEBUDDY.md +1 -1
  6. package/docs/README.md +2 -0
  7. package/docs/discipline/templates/full.md.tmpl +1 -1
  8. package/docs/discipline/templates/rules.mdc.tmpl +1 -1
  9. package/docs/en/README.md +190 -0
  10. package/docs/en/TRANSLATION.md +78 -0
  11. package/docs/en/TRANSLATION_MANIFEST.json +170 -0
  12. package/docs/en/TRANSLATION_REPORT.md +11 -0
  13. package/docs/en/dev/README.md +10 -0
  14. package/docs/en/dev/coding-testing.md +72 -0
  15. package/docs/en/dev/switch-matrix.md +10 -0
  16. package/docs/en/glossary.md +97 -0
  17. package/docs/en/harnesses/claude.md +100 -0
  18. package/docs/en/harnesses/codebuddy.md +93 -0
  19. package/docs/en/harnesses/codex.md +88 -0
  20. package/docs/en/harnesses/dsh.md +84 -0
  21. package/docs/en/harnesses/zcode.md +42 -0
  22. package/docs/en/mdcg/ccg.md +32 -0
  23. package/docs/en/mdcg/generated-docs.md +20 -0
  24. package/docs/en/mdcg/guardrail-charter.md +170 -0
  25. package/docs/en/mdcg/mcp-tool-names.md +43 -0
  26. package/docs/en/mdcg/multi-harness.md +43 -0
  27. package/docs/en/mdcg/recall-metadata.md +30 -0
  28. package/docs/en/mdcg/world-model-endpoint.md +379 -0
  29. package/docs/en/mdcg/write-aliases.md +130 -0
  30. package/docs/en/ops/README.md +11 -0
  31. package/docs/en/ops/environment-known-issues.md +244 -0
  32. package/docs/en/ops/install.md +72 -0
  33. package/docs/en/ops/operations-troubleshooting.md +86 -0
  34. package/docs/en/ops/permissions-review.md +79 -0
  35. package/docs/en/ops/release-governance.md +49 -0
  36. package/docs/en/ops/tool-name-migration.md +30 -0
  37. package/docs/en/ops/ui-install-troubleshooting.md +53 -0
  38. package/docs/en/standards/ai-coding-standard-checklist.md +71 -0
  39. package/docs/en/standards/ai-coding-standard-lingshu.md +47 -0
  40. package/docs/en/standards/ai-coding-standard.md +185 -0
  41. package/docs/en/ui/minimal.md +62 -0
  42. package/docs/mdcg/cogmap_ops.md +16 -15
  43. package/lib/client.js +29 -3
  44. package/lib/hooks.d.ts +34 -0
  45. package/lib/hooks.js +167 -33
  46. package/lib/index.js +19 -3
  47. package/lib/lib/console_web.mjs +30 -3
  48. package/lib/lib/hook_audit.d.ts +3 -2
  49. package/lib/lib/hook_audit.js +14 -4
  50. package/lib/lib/mdcg_client.d.ts +5 -2
  51. package/lib/lib/mdcg_client.js +8 -4
  52. package/lib/lib/prompt_safety.d.ts +24 -0
  53. package/lib/lib/prompt_safety.js +77 -1
  54. package/lib/lib/token_store.js +5 -2
  55. package/lib/tools.js +5 -3
  56. package/md_cg/bucketindex.py +231 -0
  57. package/md_cg/bucketscope.py +339 -0
  58. package/md_cg/config_registry_bulk.py +19 -10
  59. package/md_cg/config_validate.py +14 -2
  60. package/md_cg/detrerank.py +137 -0
  61. package/md_cg/fsutil.py +215 -25
  62. package/md_cg/govern/__init__.py +23 -0
  63. package/md_cg/iface/__init__.py +46 -0
  64. package/md_cg/iface/_verify.py +609 -0
  65. package/md_cg/iface/contracts.py +337 -0
  66. package/md_cg/judgment_manifest.py +14 -0
  67. package/md_cg/kernel/__init__.py +27 -0
  68. package/md_cg/mcp_server.py +457 -23
  69. package/md_cg/mdcg.py +1034 -79
  70. package/md_cg/mdcos.py +263 -21
  71. package/md_cg/metacognition.py +66 -13
  72. package/md_cg/mutate_extract_shipped.py +126 -0
  73. package/md_cg/mutate_ledger_e2e.py +100 -0
  74. package/md_cg/nodefile.py +147 -23
  75. package/md_cg/op_table.py +22 -4
  76. package/md_cg/probe_c_ledger_integrity.py +258 -0
  77. package/md_cg/probe_d_retirement_discipline.py +263 -0
  78. package/md_cg/reconcile.py +9 -11
  79. package/md_cg/review_cli.py +6 -1
  80. package/md_cg/rollback.py +16 -1
  81. package/md_cg/run_tests.py +30 -1
  82. package/md_cg/scopeselect.py +214 -0
  83. package/md_cg/scrub.py +160 -23
  84. package/md_cg/security.py +4 -2
  85. package/md_cg/state_extract.py +149 -0
  86. package/md_cg/state_slots.py +58 -10
  87. package/md_cg/structboost.py +179 -0
  88. package/md_cg/test_alternatives_historical.py +162 -0
  89. package/md_cg/test_b2_sensitivity_landing.py +226 -223
  90. package/md_cg/test_b3_merge_keeps_content.py +608 -583
  91. package/md_cg/test_bucket_cards.py +85 -0
  92. package/md_cg/test_bucket_day_order.py +74 -0
  93. package/md_cg/test_bucket_quota.py +79 -0
  94. package/md_cg/test_bucket_recency_guards.py +75 -0
  95. package/md_cg/test_bucket_three_causes.py +83 -0
  96. package/md_cg/test_bucketindex.py +130 -0
  97. package/md_cg/test_bucketscope_early.py +71 -0
  98. package/md_cg/test_cond_term_fold.py +183 -0
  99. package/md_cg/test_cond_term_fold_gate.py +1210 -0
  100. package/md_cg/test_cond_term_neg_scope.py +147 -0
  101. package/md_cg/test_cond_terms_colon.py +348 -0
  102. package/md_cg/test_detrerank.py +157 -0
  103. package/md_cg/test_gate_four_kpi.py +136 -0
  104. package/md_cg/test_generation_guard.py +76 -43
  105. package/md_cg/test_issue192_move_layer_indices_guard.py +48 -0
  106. package/md_cg/test_issue362_neg_condition.py +44 -7
  107. package/md_cg/test_issue39_utf8_stdio.py +572 -572
  108. package/md_cg/test_issue413_preimage_failclosed.py +147 -9
  109. package/md_cg/test_issue444_scrub_evidence_plaintext.py +14 -8
  110. package/md_cg/test_issue677_flush_batch_io.py +139 -0
  111. package/md_cg/test_issue677_info_fast.py +82 -0
  112. package/md_cg/test_issue677_remember_dedupe.py +106 -0
  113. package/md_cg/test_issue712_tokens_sessions_read.py +199 -0
  114. package/md_cg/test_issue722_strict_conditions.py +96 -0
  115. package/md_cg/test_issue730_narrowing_audit.py +121 -0
  116. package/md_cg/test_issue733_verify_override.py +193 -0
  117. package/md_cg/test_issue733_verify_override_and_overwrite_inherit.py +315 -0
  118. package/md_cg/test_issue740_filelock_fd_leak.py +218 -0
  119. package/md_cg/test_issue741_content_hash_same_source.py +158 -0
  120. package/md_cg/test_issue747_slot_contradiction.py +125 -0
  121. package/md_cg/test_issue754_nested_root_guard.py +197 -0
  122. package/md_cg/test_issue757_index_hash_compare.py +85 -0
  123. package/md_cg/test_issue758_disk_hash_single.py +67 -0
  124. package/md_cg/test_issue759_twophase_hash.py +67 -0
  125. package/md_cg/test_issue768_overwrite_time_window_anchor.py +135 -0
  126. package/md_cg/test_issue789_log_plaintext_probe.py +100 -0
  127. package/md_cg/test_issue790_verb_negation.py +77 -0
  128. package/md_cg/test_issue810_root_guard.py +71 -0
  129. package/md_cg/test_issue812_info_index_stale.py +78 -0
  130. package/md_cg/test_issue827_weaken_dedup.py +361 -0
  131. package/md_cg/test_issue829_calibration_positive_gate.py +473 -0
  132. package/md_cg/test_kernel_iface_contracts.py +18 -0
  133. package/md_cg/test_md_cg_no_hive_dep.py +238 -17
  134. package/md_cg/test_n204_n205_n226_n227_n228_n229_exit_gates.py +545 -542
  135. package/md_cg/test_n209_verify_write_face_gates.py +5 -2
  136. package/md_cg/test_neg_condition_hits.py +336 -333
  137. package/md_cg/test_probe_cd_shipped.py +385 -0
  138. package/md_cg/test_recent_tail.py +93 -0
  139. package/md_cg/test_run_tests_entry_gates.py +110 -0
  140. package/md_cg/test_scopeselect.py +70 -0
  141. package/md_cg/test_scopeselect_clock.py +70 -0
  142. package/md_cg/test_scrub_source_line_false_positive.py +64 -0
  143. package/md_cg/test_session_attribution_consistency.py +835 -813
  144. package/md_cg/test_state_extract_shipped.py +162 -0
  145. package/md_cg/test_state_ledger_chain.py +207 -0
  146. package/md_cg/test_state_ledger_e2e.py +145 -0
  147. package/md_cg/test_structboost.py +102 -0
  148. package/md_cg/test_timeboost.py +83 -0
  149. package/md_cg/test_timeboost_relativedate.py +71 -0
  150. package/md_cg/test_topicagg.py +129 -0
  151. package/md_cg/test_twophase.py +286 -286
  152. package/md_cg/timeboost.py +223 -0
  153. package/md_cg/tokens.py +55 -7
  154. package/md_cg/topicagg.py +142 -0
  155. package/md_cg/twophase.py +15 -6
  156. package/md_cg/whitebox_kb/wisdom/code_compose.py +33 -5
  157. package/md_cg/whitebox_kb/wisdom/compose_engine.py +5 -1
  158. package/md_cg/whitebox_kb/wisdom/role_compose.py +271 -268
  159. package/md_cg/writepipe.py +35 -3
  160. package/package.json +4 -1
  161. package/scripts/workspace_index.py +2 -0
  162. package/src/hooks.ts +182 -34
  163. package/src/index.ts +19 -3
  164. package/src/lib/console_web.mjs +30 -3
  165. package/src/lib/hook_audit.ts +15 -5
  166. package/src/lib/mdcg_client.ts +8 -4
  167. package/src/lib/prompt_safety.ts +73 -1
  168. package/src/lib/token_store.ts +5 -2
  169. package/src/tools.ts +5 -3
  170. package/ui/minimal/integrity.json +2 -2
  171. package/ui/minimal/payload/build-ui.mjs +41 -2
  172. package/ui/minimal/payload/lib/client.js +29 -3
  173. package/ui/minimal/payload/lib/lib/console_web.mjs +30 -3
  174. package/ui/minimal/payload/src/lib/console_web.mjs +30 -3
  175. package/ui/minimal/payload/web/app.js +3 -1
  176. package/ui/minimal/payload/web/client.js +30 -3
  177. package/web/app.js +3 -1
  178. package/web/client.js +30 -3
  179. package/zcode/AGENTS.md +1 -1
@@ -33,8 +33,12 @@ async function readBody(req) {
33
33
  // 空值被闭包固化,此后每次请求都命中 503「宿主鉴权不可用」,宿主就绪也不会自愈。
34
34
  // 现在改为**每次请求实时取**:服务晚到也能自愈。
35
35
  // 兼容:传的不是函数(旧调用方式/直接给实例)时按常量包裹,行为与旧版一致。
36
- export function createConsoleHandler(mdcg, config, assets, getConnection) {
36
+ // issue #699 第二层(2026-11-04):503 分不清「服务没注入」与「已注册未就绪」。
37
+ // 第 5 参 probeConnection 用 `ctx.get(name, false)` 做诊断:strict=false 时即便 fiber 未就绪
38
+ // 也能看到 impl 存在 ⇒ 可区分 not_injected / not_ready。诊断失败不影响主判据。
39
+ export function createConsoleHandler(mdcg, config, assets, getConnection, probeConnection) {
37
40
  const connectionOf = typeof getConnection === 'function' ? getConnection : () => getConnection
41
+ const probeOf = typeof probeConnection === 'function' ? probeConnection : null
38
42
  const csrf = randomBytes(32).toString('hex');
39
43
  let catalog = null;
40
44
  const tools = async () => catalog ?? (catalog = await mdcg.bridge.listTools());
@@ -42,7 +46,29 @@ export function createConsoleHandler(mdcg, config, assets, getConnection) {
42
46
  try {
43
47
  const path = new URL(req.url, 'http://localhost').pathname;
44
48
  const connection = connectionOf()
45
- if (!connection || typeof connection.admit !== 'function') return reply(res, 503, { error: '宿主鉴权服务尚未就绪,请稍后重试' });
49
+ if (!connection || typeof connection.admit !== 'function') {
50
+ // 三态(#699 复核):not_admit = 服务存在但不提供 admit(服务名撞车/版本不兼容的
51
+ // 唯一可识别指纹);not_injected = 探测到该名字下没有 impl;not_ready = 有 impl 但未就绪。
52
+ // 诊断异常必须可观测(probe_failed),不得默认退回 not_ready 而把「没注入」误报成「未就绪」。
53
+ let reason = connection ? 'not_admit' : 'not_ready'
54
+ if (!connection) {
55
+ try {
56
+ const p = probeOf ? probeOf() : null
57
+ if (p && p.any === false) reason = 'not_injected'
58
+ } catch { reason = 'probe_failed' }
59
+ }
60
+ return reply(res, 503, {
61
+ error: '宿主鉴权服务尚未就绪,请稍后重试',
62
+ reason,
63
+ hint: reason === 'not_injected'
64
+ ? '本插件看不到 connection 服务(inject 声明/服务名不匹配);请把本回执贴到 issue #699'
65
+ : reason === 'not_admit'
66
+ ? 'connection 服务存在但不提供 admit(服务名撞车/版本不兼容);请把本回执贴到 issue #699'
67
+ : reason === 'probe_failed'
68
+ ? '诊断探针异常;请把本回执贴到 issue #699'
69
+ : '服务已注册但尚未就绪;若持续出现请把本回执贴到 issue #699',
70
+ })
71
+ }
46
72
  const admission = connection.admit(req);
47
73
  if ('rejection' in admission) return reply(res, admission.rejection, { error: admission.rejection === 401 ? '未登录,请返回 DSH 登录' : '请求来源不可信' });
48
74
  if (req.method === 'GET' && assets[path]) {
@@ -96,7 +122,8 @@ export function installConsoleWeb(ctx, config, disposers, mdcg) {
96
122
  '/plugins/lingshu/entry.js': [asset('entry.js'), 'application/javascript; charset=utf-8'],
97
123
  };
98
124
  // issue #699:传**取值函数**(每次请求实时取),不再把挂载瞬间的值闭包固化。
99
- const handler = createConsoleHandler(mdcg, config, assets, () => ctx.get('connection'));
125
+ const handler = createConsoleHandler(mdcg, config, assets, () => ctx.get('connection'),
126
+ () => ({ any: !!ctx.get('connection', false) }));
100
127
  for (const path of ['/lingshu', '/lingshu/', '/plugins/lingshu']) disposers.push(web.register({ kind: path === '/plugins/lingshu' ? 'prefix' : 'exact', path, handler }));
101
128
  disposers.push(web.tapIndex(html => html.includes('data-lingshu-entry') ? html : html.replace('</body>', '<script data-lingshu-entry src="/plugins/lingshu/entry.js"></script></body>')));
102
129
  ctx.logger.info('dsh-memory: 极简灵枢控制台已挂载 /lingshu(复用唯一大脑桥)');
@@ -1,5 +1,6 @@
1
1
  /** 三处过滤分支的成因(与 hooks.ts 一一对应:子代理会话 / 中继消息 / kind 非 user)。 */
2
- export type HookFilterReason = 'subagent' | 'relay' | 'kind';
2
+ /** issue #695:`session_excluded` = 会话在 memory.excludeSessions 里(按会话显式排除)。 */
3
+ export type HookFilterReason = 'subagent' | 'relay' | 'kind' | 'session_excluded';
3
4
  /** 写入路径的角色(与 md_cg 对 DSH 会话事件的 role 约定一致)。 */
4
5
  export type HookWriteRole = 'user' | 'assistant' | 'tool';
5
6
  /** 跳过写入的成因。 */
@@ -55,7 +56,7 @@ export declare class HookAuditRecorder {
55
56
  /** #606:收尾时只读最新盘面,返回一行累计计数;缺失/损坏/不可读均静默。
56
57
  * written 沿用“成功发起”口径,不能当成成功落库数;不读取 last/kinds 等文本进日志。 */
57
58
  summary(): string | null;
58
- /** 一条**被设计滤除**的消息(三处过滤分支各调一次)。 */
59
+ /** 一条**被设计滤除**的消息(各过滤分支各调一次)。 */
59
60
  filtered(reason: HookFilterReason, kind?: string): void;
60
61
  /** `source.kind` 分布(每条**进入消息级处理**的事件调一次,含被滤与放行)。 */
61
62
  observeKind(kind: string): void;
@@ -57,7 +57,9 @@ const MAX_LAST = 20;
57
57
  const MAX_KINDS = 32;
58
58
  /** kinds 归并桶。 */
59
59
  const OTHER_KIND = 'other';
60
- const FILTER_REASONS = ['subagent', 'relay', 'kind'];
60
+ const FILTER_REASONS = ['subagent', 'relay', 'kind', 'session_excluded'];
61
+ /** 只在**新增**键上允许旧盘面缺省(前向兼容),旧键缺失仍判坏盘面。 */
62
+ const OPTIONAL_COUNT_KEYS = new Set(['session_excluded']);
61
63
  const WRITE_ROLES = ['user', 'assistant', 'tool'];
62
64
  const SKIP_REASONS = ['sanitized', 'not_ready', 'failed'];
63
65
  /** `source.kind` 的规范化取值:非字符串(含缺字段)或空串一律记 "undefined"
@@ -82,7 +84,7 @@ function nowIso() {
82
84
  function emptyState() {
83
85
  return {
84
86
  counts: {
85
- filtered: { subagent: 0, relay: 0, kind: 0 },
87
+ filtered: { subagent: 0, relay: 0, kind: 0, session_excluded: 0 },
86
88
  written: { user: 0, assistant: 0, tool: 0 },
87
89
  skipped: { sanitized: 0, not_ready: 0, failed: 0 },
88
90
  },
@@ -96,13 +98,21 @@ function emptyState() {
96
98
  function countOf(v) {
97
99
  return typeof v === 'number' && Number.isFinite(v) && v >= 0 ? Math.floor(v) : 0;
98
100
  }
99
- /** 摘要只接受完整的非负安全整数桶;坏盘面不伪装成零计数。 */
101
+ /** 摘要只接受非负安全整数桶;**缺键按 0 计**(版本前向兼容:旧盘面没有新增 reason),
102
+ * 形态不符仍返回 null(坏盘面不伪装成零计数)。 */
100
103
  function sumCounts(bucket, keys) {
101
104
  if (!bucket || typeof bucket !== 'object' || Array.isArray(bucket))
102
105
  return null;
103
106
  let total = 0;
104
107
  for (const key of keys) {
105
108
  const value = bucket[key];
109
+ // 只对**新增**键放行缺省(旧盘面没有它);旧三项缺键仍判坏——
110
+ // 否则「盘面被手改删键」会被伪装成健康零计数。
111
+ if (value === undefined) {
112
+ if (OPTIONAL_COUNT_KEYS.has(key))
113
+ continue;
114
+ return null;
115
+ }
106
116
  if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0)
107
117
  return null;
108
118
  total += value;
@@ -197,7 +207,7 @@ export class HookAuditRecorder {
197
207
  return null;
198
208
  }
199
209
  }
200
- /** 一条**被设计滤除**的消息(三处过滤分支各调一次)。 */
210
+ /** 一条**被设计滤除**的消息(各过滤分支各调一次)。 */
201
211
  filtered(reason, kind) {
202
212
  this.#mutate((s) => {
203
213
  s.counts.filtered[reason] += 1;
@@ -213,8 +213,11 @@ export declare class MdcgClient {
213
213
  * `max(1, recent_limit or 10)` 归一(`mdcos.py:3309`)。
214
214
  *
215
215
  * ⚠️ 两条服务端事实(决定注入侧的可达性,勿据本方法名臆测):
216
- * ① `recent` 段取 `recent_events(limit=recent_limit)` —— **不按 session
217
- * 过滤**(近期事件是运行态滚动窗口,会话归属只写在每条事件的 meta 里);
216
+ * ① `recent` 段在 `session` 为真值时由服务端**严格按会话过滤**(`meta.session`
217
+ * 精确相等;缺 `meta.session` 的事件被丢弃——最坏空窗口,杜绝错块);
218
+ * `session` 显式传 `'*'` 时不过滤(跨会话汇总的合法用法);仅当 `session`
219
+ * 为 falsy 时才退回全局窗口,并在 `pack.degraded` 追加
220
+ * `recent_global_window`(注入侧据此 fail-closed,见 src/hooks.ts)。
218
221
  * ② budget 是**整包**预算:库内 notes/tasks/self_state 占位越多,同样
219
222
  * budget 下 recent 段被裁得越短(实测:空库 + 10 条窗口条目,
220
223
  * budget_tokens=600 → recent 8 条;1200 → 10 条)。
@@ -42,6 +42,7 @@ import { pythonPathValue, runRoot } from './datapath.js';
42
42
  // 用同一函数算出租户——N62 之后服务端对「令牌记录租户 ≠ 入参租户」fail-closed,
43
43
  // 两侧各算一遍就必然分叉(签发按 default、运行按 work ⇒ rc=3 拒启)。
44
44
  import { effectiveTenant } from './token_store.js';
45
+ import { stripLoneSurrogates, truncateSafe } from './prompt_safety.js'; // issue #762
45
46
  const DEFAULT_ARGS = ['-m', 'md_cg.mcp_server'];
46
47
  /**
47
48
  * MCP 子进程环境:**唯一构造点**(导出即为了让机械守卫能断言它——
@@ -253,8 +254,11 @@ export class MdcgClient {
253
254
  * `max(1, recent_limit or 10)` 归一(`mdcos.py:3309`)。
254
255
  *
255
256
  * ⚠️ 两条服务端事实(决定注入侧的可达性,勿据本方法名臆测):
256
- * ① `recent` 段取 `recent_events(limit=recent_limit)` —— **不按 session
257
- * 过滤**(近期事件是运行态滚动窗口,会话归属只写在每条事件的 meta 里);
257
+ * ① `recent` 段在 `session` 为真值时由服务端**严格按会话过滤**(`meta.session`
258
+ * 精确相等;缺 `meta.session` 的事件被丢弃——最坏空窗口,杜绝错块);
259
+ * `session` 显式传 `'*'` 时不过滤(跨会话汇总的合法用法);仅当 `session`
260
+ * 为 falsy 时才退回全局窗口,并在 `pack.degraded` 追加
261
+ * `recent_global_window`(注入侧据此 fail-closed,见 src/hooks.ts)。
258
262
  * ② budget 是**整包**预算:库内 notes/tasks/self_state 占位越多,同样
259
263
  * budget 下 recent 段被裁得越短(实测:空库 + 10 条窗口条目,
260
264
  * budget_tokens=600 → recent 8 条;1200 → 10 条)。
@@ -316,7 +320,7 @@ export class MdcgClient {
316
320
  if (best && best.score > 0 && STRONG_BASIS.has(best.basis)) {
317
321
  return {
318
322
  judgment: `采纳:认知图已有强依据节点 ${best.id}(basis=${best.basis})`,
319
- best: best.content.slice(0, 200),
323
+ best: truncateSafe(stripLoneSurrogates(best.content), 200), // issue #762
320
324
  d_norm: Math.min(1, best.score),
321
325
  record_id: best.id,
322
326
  };
@@ -324,7 +328,7 @@ export class MdcgClient {
324
328
  if (best && best.score > 0) {
325
329
  return {
326
330
  judgment: `待定:命中节点 ${best.id} 但依据不足(basis=${best.basis || 'unknown'})`,
327
- best: best.content.slice(0, 200),
331
+ best: truncateSafe(stripLoneSurrogates(best.content), 200), // issue #762
328
332
  d_norm: -1,
329
333
  record_id: best.id,
330
334
  };
@@ -60,6 +60,30 @@
60
60
  * 例:`{{.Architecture}}` → `{ {.Architecture}}`;`{{{a}}}` → `{ { {a}}}`。
61
61
  */
62
62
  export declare function escapePromptBraces(text: string): string;
63
+ /** 文本的**码元安全截断**(issue #762):最多保留 `maxUnits` 个 UTF-16 码元,
64
+ * 且**绝不劈开代理对**(emoji / 增补平面字符)。
65
+ *
66
+ * 为什么必须:注入面此前用 `s.slice(0, max)`,预算落点若恰好压在 emoji 两个码元之间,
67
+ * 截断结果就是孤立高位代理 `\uD83D`;`JSON.stringify` 会把它写成 `"\ud83d"`——
68
+ * **合法 JSON 文本、非法 Unicode 码元**,严格校验的服务端把整条请求拒掉
69
+ * (实测 400 INVALID_REQUEST、0 token 输出)。而注入文本每轮重拼、每轮写进对话历史,
70
+ * 一次劈开就让该会话**永久**不可用(历史只增不改)。
71
+ *
72
+ * 语义:预算单位仍是 **UTF-16 码元**(与既有 `RECALL_MAX_CHARS` 等常量一致,输出体积
73
+ * 不变),只是不再把代理对拆开。
74
+ *
75
+ * **输出恒不含孤立代理**(#742 复核对 #765 的采纳):原文自带的孤立代理也会被清掉——
76
+ * 此前只保证「不新造」,未挂 strip 的调用点(如 `role`、`index.ts` 的 reason)只能靠
77
+ * 出口兜底;现在截断本身即安全,任何调用点都拿不到半个字符。
78
+ */
79
+ export declare function truncateSafe(text: string, maxUnits: number): string;
80
+ /** 移除**孤立代理**(issue #762):合法代理对原样保留,落单的高位/低位代理丢弃。
81
+ *
82
+ * 幂等;无代理的文本走快路径原样返回(零改写,保真)。
83
+ * 用途:注入块**出口卫生**——来源不止记忆(工具输出 / 文件名 / 网页抓取都可能带
84
+ * 半个字符),在共同出口清一次胜过到处补。
85
+ */
86
+ export declare function stripLoneSurrogates(text: string): string;
63
87
  /** 边界标记名——**唯一**来源:开/闭标记、打断判据都从它派生(不许各处手写字符串)。 */
64
88
  export declare const UNTRUSTED_MEMORY_TAG = "untrusted-memory";
65
89
  /** 开界标记(注入块的左边界)。 */
@@ -74,6 +74,78 @@ export function escapePromptBraces(text) {
74
74
  }
75
75
  return out;
76
76
  }
77
+ // ---------------------------------------------------------------- 代理对安全(issue #762)
78
+ /** 文本的**码元安全截断**(issue #762):最多保留 `maxUnits` 个 UTF-16 码元,
79
+ * 且**绝不劈开代理对**(emoji / 增补平面字符)。
80
+ *
81
+ * 为什么必须:注入面此前用 `s.slice(0, max)`,预算落点若恰好压在 emoji 两个码元之间,
82
+ * 截断结果就是孤立高位代理 `\uD83D`;`JSON.stringify` 会把它写成 `"\ud83d"`——
83
+ * **合法 JSON 文本、非法 Unicode 码元**,严格校验的服务端把整条请求拒掉
84
+ * (实测 400 INVALID_REQUEST、0 token 输出)。而注入文本每轮重拼、每轮写进对话历史,
85
+ * 一次劈开就让该会话**永久**不可用(历史只增不改)。
86
+ *
87
+ * 语义:预算单位仍是 **UTF-16 码元**(与既有 `RECALL_MAX_CHARS` 等常量一致,输出体积
88
+ * 不变),只是不再把代理对拆开。
89
+ *
90
+ * **输出恒不含孤立代理**(#742 复核对 #765 的采纳):原文自带的孤立代理也会被清掉——
91
+ * 此前只保证「不新造」,未挂 strip 的调用点(如 `role`、`index.ts` 的 reason)只能靠
92
+ * 出口兜底;现在截断本身即安全,任何调用点都拿不到半个字符。
93
+ */
94
+ export function truncateSafe(text, maxUnits) {
95
+ // 预算语义固定(#762 复核):NaN / -Infinity 这类非有限值 **fail-closed** 到 ''——
96
+ // 旧实现里 `units + step > NaN` 恒假 ⇒ 返回全文,是「截空→全量」的失败开放反转;
97
+ // `+Infinity` 表示无上限(原样返回)。小数按 floor 收口(与 `slice` 的隐式取整一致)。
98
+ if (!Number.isFinite(maxUnits))
99
+ return maxUnits > 0 ? stripLoneSurrogates(text) : '';
100
+ const max = Math.floor(maxUnits);
101
+ if (max <= 0)
102
+ return '';
103
+ if (text.length <= max)
104
+ return stripLoneSurrogates(text);
105
+ let units = 0;
106
+ let i = 0;
107
+ while (i < text.length) {
108
+ const c = text.charCodeAt(i);
109
+ const isHigh = c >= 0xd800 && c <= 0xdbff;
110
+ const next = i + 1 < text.length ? text.charCodeAt(i + 1) : 0;
111
+ const isPair = isHigh && next >= 0xdc00 && next <= 0xdfff;
112
+ const step = isPair ? 2 : 1;
113
+ if (units + step > maxUnits)
114
+ break;
115
+ units += step;
116
+ i += step;
117
+ }
118
+ return stripLoneSurrogates(text.slice(0, i));
119
+ }
120
+ /** 移除**孤立代理**(issue #762):合法代理对原样保留,落单的高位/低位代理丢弃。
121
+ *
122
+ * 幂等;无代理的文本走快路径原样返回(零改写,保真)。
123
+ * 用途:注入块**出口卫生**——来源不止记忆(工具输出 / 文件名 / 网页抓取都可能带
124
+ * 半个字符),在共同出口清一次胜过到处补。
125
+ */
126
+ export function stripLoneSurrogates(text) {
127
+ if (!/[\uD800-\uDFFF]/.test(text))
128
+ return text;
129
+ let out = '';
130
+ for (let i = 0; i < text.length; i++) {
131
+ const c = text.charCodeAt(i);
132
+ if (c >= 0xd800 && c <= 0xdbff) {
133
+ const n = i + 1 < text.length ? text.charCodeAt(i + 1) : 0;
134
+ if (n >= 0xdc00 && n <= 0xdfff) {
135
+ out += text.charAt(i) + text.charAt(i + 1);
136
+ i++;
137
+ }
138
+ // 落单高位:丢弃(半个字符本来就是非法码元,保留它只会废掉整条请求)
139
+ }
140
+ else if (c >= 0xdc00 && c <= 0xdfff) {
141
+ // 落单低位:丢弃
142
+ }
143
+ else {
144
+ out += text.charAt(i);
145
+ }
146
+ }
147
+ return out;
148
+ }
77
149
  // ---------------------------------------------------------------- 不可信记忆边界(H5)
78
150
  /** 边界标记名——**唯一**来源:开/闭标记、打断判据都从它派生(不许各处手写字符串)。 */
79
151
  export const UNTRUSTED_MEMORY_TAG = 'untrusted-memory';
@@ -156,8 +228,12 @@ export function neutralizeUntrustedBoundary(text) {
156
228
  * ——注入块按 v0.4.8 契约每步都 push,输出必须逐字节稳定(否则宿主每步新增快照)。
157
229
  */
158
230
  export function renderUntrustedMemoryBlock(payload) {
231
+ // issue #762(2026-11-04):**出口卫生**——载荷里的孤立代理(半个 emoji)会被宿主
232
+ // `JSON.stringify` 写成 `"\ud83d"`(合法 JSON 文本、非法 Unicode 码元),严格校验的
233
+ // 服务端把**整条请求**拒掉(400 INVALID_REQUEST、0 token),而注入文本每轮重拼、每轮
234
+ // 写进对话历史 ⇒ 一次就永久。三个注入块的共同出口在此兜底清一次(幂等、合法对不动)。
159
235
  return `${UNTRUSTED_MEMORY_NOTICE}\n`
160
236
  + `${UNTRUSTED_MEMORY_OPEN}\n`
161
- + `${neutralizeUntrustedBoundary(payload)}\n`
237
+ + `${neutralizeUntrustedBoundary(stripLoneSurrogates(payload))}\n`
162
238
  + `${UNTRUSTED_MEMORY_CLOSE}`;
163
239
  }
@@ -55,6 +55,7 @@ import { dirname, join, resolve } from 'node:path';
55
55
  // Python 侧令牌记录落 `<家目录>/.mdcg/_tokens.json`:密钥环被写进插件包目录,
56
56
  // pnpm 更新整目录替换即丢失(下次启动重签新令牌,旧令牌仍在且未吊销)。
57
57
  import { expandHome, pythonPathValue, runRoot } from './datapath.js';
58
+ import { stripLoneSurrogates, truncateSafe } from './prompt_safety.js'; // issue #762:错误详情是模型可见文本
58
59
  /** 当前生效租户(**单点**:签发、密钥环复核、MCP 子进程三处共用)。
59
60
  *
60
61
  * 优先级与 `mdcgChildEnv()` 的 env 叠加顺序同口径:
@@ -160,7 +161,8 @@ function issueToken(python, role, actor, clearance, tenant, env) {
160
161
  if (r.error)
161
162
  return { error: r.error };
162
163
  if (!r.ok) {
163
- const detail = (r.stderr || r.stdout || '').trim().replace(/\s+/g, ' ').slice(0, 200);
164
+ // issue #762:错误详情可能进工具回执(模型可见)——先清孤代理、再码元安全截断。
165
+ const detail = truncateSafe(stripLoneSurrogates((r.stderr || r.stdout || '').trim().replace(/\s+/g, ' ')), 200);
164
166
  return { error: `md_cg.tokens issue 退出码 ${r.status}${detail ? `:${detail}` : ''}` };
165
167
  }
166
168
  try {
@@ -216,7 +218,8 @@ function checkKeyring(python, keyringPath, tenant, env) {
216
218
  }
217
219
  return { status: 'ok', reason: '', tokenId };
218
220
  }
219
- const detail = (r.stderr || r.stdout || '').trim().replace(/\s+/g, ' ').slice(0, 200);
221
+ // issue #762:错误详情可能进工具回执(模型可见)——先清孤代理、再码元安全截断。
222
+ const detail = truncateSafe(stripLoneSurrogates((r.stderr || r.stdout || '').trim().replace(/\s+/g, ' ')), 200);
220
223
  // 令牌库损坏:`_load` 回落空表后报「令牌不存在」,必须按告警先分出来(N198)。
221
224
  if (/令牌库损坏|令牌库不可读|拒绝整份写回/.test(detail)) {
222
225
  return { status: 'blocked', reason: `令牌库损坏:${detail}` };
package/lib/tools.js CHANGED
@@ -8,7 +8,7 @@
8
8
  // 运行时导入写 `.js`(本仓口径:type-only 才写 `.ts`,tsconfig 未开
9
9
  // allowImportingTsExtensions —— 值导入写 `.ts` 会 TS5097 编译失败)。
10
10
  import { attributeSession } from './lib/session_state.js';
11
- import { neutralizeUntrustedBoundary } from './lib/prompt_safety.js';
11
+ import { neutralizeUntrustedBoundary, stripLoneSurrogates, truncateSafe } from './lib/prompt_safety.js';
12
12
  /** 默认暴露的核心工具集合:**记忆面已基元化**,只注册 `cg` / `stg` 两个认知基元。
13
13
  *
14
14
  * 三层拆分 S4 收敛后,插件工具面真源是 `md_cg.mcp_server`(不再是 pip aeis);
@@ -221,9 +221,11 @@ export async function registerLingshuTools(ctx, bridge, opts) {
221
221
  // ②兜底上限(服务端已有 offset 分页,插件层只兜一个远大于单页的硬上限,
222
222
  // 防止一次把整库搬进上下文;截断必须显式标注,不静默)。
223
223
  const raw = extractText(value.content ?? []);
224
- const safe = neutralizeUntrustedBoundary(raw);
224
+ // issue #762:工具返回同样是模型上下文的一部分——半个 emoji 会让宿主
225
+ // JSON.stringify 产出 "\ud83d" ⇒ 整条请求 400。出口先清孤立代理。
226
+ const safe = neutralizeUntrustedBoundary(stripLoneSurrogates(raw));
225
227
  const text = safe.length > TOOL_RENDER_MAX_CHARS
226
- ? safe.slice(0, TOOL_RENDER_MAX_CHARS)
228
+ ? truncateSafe(safe, TOOL_RENDER_MAX_CHARS) // issue #762:不劈代理对
227
229
  + `
228
230
  …[已截断:工具返回超过插件上限 ${TOOL_RENDER_MAX_CHARS} 字符]`
229
231
  : safe;
@@ -0,0 +1,231 @@
1
+ # -*- coding: utf-8 -*-
2
+ """日桶 / 会话桶索引(bucketindex)——把「时间」与「会话身份」真正用起来。
3
+
4
+ 实测现状(主库 34,218 节点,2026-11-09):
5
+ · `created_at` 覆盖 **100%**,按天聚集(09-29 有 2733 条、11-08 有 2516 条);
6
+ · `session` 覆盖 **99.4%**,但其中 **48% 是 `unattributed`**(无法归属);
7
+ · `bucket` 字段**不是**日桶/会话桶,而是**条件桶**(`cond_<topic>_<hash>`)——别混用。
8
+
9
+ 所以两件事必须显式建出来:
10
+ · **日桶** `day:YYYY-MM-DD`:由 `created_at` 确定性派生(不新增写入代价);
11
+ · **会话桶** `session:<sid>`:由 `frontmatter.session` 派生,`unattributed` 单独成桶不与他人合并。
12
+
13
+ 索引文件(落库根目录,按需重建):
14
+ · `_days.json` {day: [node_id, ...]}
15
+ · `_sessions.json` {session: [node_id, ...]}
16
+
17
+ 为什么用索引:查询期扫 34k 节点按日期过滤实测 **2–17 秒**(见 timeboost.scoped_recall 注释),
18
+ 索引后是字典查找 + O(命中数) 取节点。
19
+ """
20
+ from __future__ import annotations
21
+
22
+ import json
23
+ import os
24
+ import time
25
+
26
+ from .bm25 import tokenize as _bm25_tokenize
27
+
28
+ DAYS_FILE = "_days.json"
29
+ SESSIONS_FILE = "_sessions.json"
30
+ TERMS_FILE = "_bucketterms.json"
31
+ SKEL_FILE = "_bucketskel.json"
32
+ UNATTRIBUTED = "unattributed"
33
+ #: 桶骨架:每节点/每桶保留的字符数(供子串共现,bench 口径)
34
+ SKEL_CHARS_PER_NODE = 600
35
+ SKEL_CHARS_PER_BUCKET = 20000
36
+
37
+
38
+ def day_of(ts):
39
+ """epoch 秒 → 本地日期字符串;不可解析返回 None。"""
40
+ try:
41
+ return time.strftime("%Y-%m-%d", time.localtime(float(ts)))
42
+ except (TypeError, ValueError, OSError):
43
+ return None
44
+
45
+
46
+ def _fm(rec):
47
+ if not isinstance(rec, dict):
48
+ return {}
49
+ fm = rec.get("frontmatter")
50
+ return fm if isinstance(fm, dict) and fm else rec
51
+
52
+
53
+ def build(store, write=True, with_content=False, content_limit=400):
54
+ """从索引面重建两个桶。返回 {days, sessions, nodes, unattributed}。"""
55
+ idx = getattr(store, "index", {}) or {}
56
+ content_terms = 0
57
+ nodes = idx.get("nodes") or {}
58
+ days = {}
59
+ sessions = {}
60
+ unattributed = 0
61
+ for nid, rec in nodes.items():
62
+ fm = _fm(rec)
63
+ d = day_of(fm.get("created_at"))
64
+ if d:
65
+ days.setdefault(d, []).append(nid)
66
+ sid = str(fm.get("session") or "") or UNATTRIBUTED
67
+ if sid == UNATTRIBUTED:
68
+ unattributed += 1
69
+ sessions.setdefault(sid, []).append(nid)
70
+ # 桶词表:{bucket_key: {term: 次数}} —— 供 scopeselect 打分(查询期只做字典运算)
71
+ terms = {}
72
+ skel = {}
73
+ for nid, rec in nodes.items():
74
+ fm = _fm(rec)
75
+ d0 = day_of(fm.get("created_at"))
76
+ sid0 = str(fm.get("session") or "") or UNATTRIBUTED
77
+ names = []
78
+ if d0:
79
+ names.append("day:" + d0)
80
+ if sid0 != UNATTRIBUTED:
81
+ names.append("session:" + sid0)
82
+ if not names:
83
+ continue
84
+ blob = []
85
+ for key in ("tags", "bucket_zh", "bucket", "role", "content_kind"):
86
+ val = fm.get(key)
87
+ if isinstance(val, (list, tuple)):
88
+ blob.extend(str(x) for x in val)
89
+ elif val:
90
+ blob.append(str(val))
91
+ # 与检索面**同口径**分词(bm25.tokenize:汉字单字 + 相邻二元)。
92
+ # 早期版本按标点切整句,查询里的短词(「商人」「蒙德城广场」)整词匹配不上,
93
+ # 生产共现实测只有 34%;换成 n-gram 粒度后才可能与 bench 的「子串语义」对齐。
94
+ text = " ".join(blob).lower()
95
+ if with_content:
96
+ node = store.get(nid)
97
+ body = str((node or {}).get("content") or "")[:content_limit * 8].lower()
98
+ if body:
99
+ text = text + " " + body
100
+ content_terms += 1
101
+ toks = list(_bm25_tokenize(text))
102
+ skel_part = (body if with_content else text)[:SKEL_CHARS_PER_NODE]
103
+ for bucket in names:
104
+ skel[bucket] = (skel.get(bucket, "") + " " + skel_part)[:SKEL_CHARS_PER_BUCKET]
105
+ bag = terms.setdefault(bucket, {})
106
+ for t in toks[:content_limit]:
107
+ bag[t] = bag.get(t, 0) + 1
108
+ out = {"content_enriched": content_terms, "days": len(days), "sessions": len(sessions),
109
+ "nodes": len(nodes), "unattributed": unattributed}
110
+ if write:
111
+ root = getattr(store, "root", None)
112
+ if root:
113
+ for name, data in ((DAYS_FILE, days), (SESSIONS_FILE, sessions),
114
+ (TERMS_FILE, terms), (SKEL_FILE, skel)):
115
+ path = os.path.join(root, name)
116
+ tmp = path + ".tmp"
117
+ with open(tmp, "w", encoding="utf-8", newline="\n") as fh:
118
+ json.dump(data, fh, ensure_ascii=False)
119
+ os.replace(tmp, path)
120
+ return out
121
+
122
+
123
+ def _load(store, name):
124
+ root = getattr(store, "root", None)
125
+ if not root:
126
+ return {}
127
+ path = os.path.join(root, name)
128
+ if not os.path.exists(path):
129
+ return {}
130
+ try:
131
+ with open(path, encoding="utf-8") as fh:
132
+ return json.load(fh)
133
+ except (OSError, json.JSONDecodeError):
134
+ return {}
135
+
136
+
137
+ def day_ids(store, day):
138
+ return list(_load(store, DAYS_FILE).get(day) or ())
139
+
140
+
141
+ def session_ids(store, session):
142
+ return list(_load(store, SESSIONS_FILE).get(str(session)) or ())
143
+
144
+
145
+ def all_days(store):
146
+ """全部日桶键(升序未排序,调用方自行排序)。"""
147
+ return list(_load(store, DAYS_FILE).keys())
148
+
149
+
150
+ #: 自动重建:元数据文件(记录上次重建时间与规模)。
151
+ META_FILE = "_bucketindex_meta.json"
152
+ #: 缺省重建间隔(小时):每日收尾一次 ⇒ 20 小时���给抖动余量)。
153
+ DEFAULT_INTERVAL_H = 20.0
154
+ #: 自动重建开关的环境变量(缺省开;0=关)。
155
+ AUTO_ENV = "MDCG_BUCKET_AUTO"
156
+ INTERVAL_ENV = "MDCG_BUCKET_INTERVAL_H"
157
+
158
+ _RUNNING = {"on": False}
159
+
160
+
161
+ def _meta_path(store):
162
+ root = getattr(store, "root", None)
163
+ return os.path.join(root, META_FILE) if root else None
164
+
165
+
166
+ def last_build_ts(store):
167
+ p = _meta_path(store)
168
+ if not p or not os.path.exists(p):
169
+ return 0.0
170
+ try:
171
+ with open(p, encoding="utf-8") as fh:
172
+ return float(json.load(fh).get("ts") or 0.0)
173
+ except (OSError, json.JSONDecodeError, TypeError, ValueError):
174
+ return 0.0
175
+
176
+
177
+ def _write_meta(store, stats, ts):
178
+ p = _meta_path(store)
179
+ if not p:
180
+ return
181
+ try:
182
+ payload = dict(stats)
183
+ payload["ts"] = ts
184
+ tmp = p + ".tmp"
185
+ with open(tmp, "w", encoding="utf-8", newline="\n") as fh:
186
+ json.dump(payload, fh, ensure_ascii=False)
187
+ os.replace(tmp, p)
188
+ except OSError:
189
+ pass
190
+
191
+
192
+ def maybe_auto_rebuild(store, interval_h=None, background=True):
193
+ """每日收尾式自动重建:距上次重建超过 interval 小时才重建。
194
+
195
+ 为什么这样设计:主库重建 3–5 秒,**不能**卡在写入或查询路径上,
196
+ 故(a)只在「陈旧」时触发,(b)缺省放后台线程跑;
197
+ 并有模块级 `_RUNNING` 防重入(同一进程内不会并发重建)。
198
+
199
+ 返回 {"rebuilt": bool, "reason": str, "age_h": float, ...},便于调用方审计。
200
+ """
201
+ if os.environ.get("MDCG_BUCKET_AUTO", "1") == "0":
202
+ return {"rebuilt": False, "reason": "disabled"}
203
+ if interval_h is not None: # 显式参数优先(0 = 强制重建)
204
+ interval = float(interval_h)
205
+ else:
206
+ try:
207
+ interval = float(os.environ.get("MDCG_BUCKET_INTERVAL_H", "20"))
208
+ except ValueError:
209
+ interval = DEFAULT_INTERVAL_H
210
+ age_h = (time.time() - last_build_ts(store)) / 3600.0
211
+ if last_build_ts(store) > 0 and age_h < interval:
212
+ return {"rebuilt": False, "reason": "fresh", "age_h": round(age_h, 2)}
213
+ if _RUNNING["on"]:
214
+ return {"rebuilt": False, "reason": "running", "age_h": round(age_h, 2)}
215
+
216
+ def _job():
217
+ _RUNNING["on"] = True
218
+ try:
219
+ stats = build(store, write=True)
220
+ _write_meta(store, stats, time.time())
221
+ except Exception: # noqa: BLE001 —— 后台失败不得影响主流程
222
+ pass
223
+ finally:
224
+ _RUNNING["on"] = False
225
+
226
+ if background:
227
+ import threading
228
+ threading.Thread(target=_job, daemon=True).start()
229
+ return {"rebuilt": True, "reason": "stale", "age_h": round(age_h, 2), "async": True}
230
+ _job()
231
+ return {"rebuilt": True, "reason": "stale", "age_h": round(age_h, 2), "async": False}