@furongjun1999/dsh-memory 0.9.22 → 0.9.23

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 (103) hide show
  1. package/CHANGELOG.en.md +404 -0
  2. package/CHANGELOG.md +45 -0
  3. package/README.en.md +240 -0
  4. package/README.md +3 -1
  5. package/docs/README.md +2 -0
  6. package/docs/en/README.md +190 -0
  7. package/docs/en/TRANSLATION.md +78 -0
  8. package/docs/en/TRANSLATION_MANIFEST.json +170 -0
  9. package/docs/en/TRANSLATION_REPORT.md +11 -0
  10. package/docs/en/dev/README.md +10 -0
  11. package/docs/en/dev/coding-testing.md +72 -0
  12. package/docs/en/dev/switch-matrix.md +10 -0
  13. package/docs/en/glossary.md +97 -0
  14. package/docs/en/harnesses/claude.md +100 -0
  15. package/docs/en/harnesses/codebuddy.md +93 -0
  16. package/docs/en/harnesses/codex.md +88 -0
  17. package/docs/en/harnesses/dsh.md +84 -0
  18. package/docs/en/harnesses/zcode.md +42 -0
  19. package/docs/en/mdcg/ccg.md +32 -0
  20. package/docs/en/mdcg/generated-docs.md +20 -0
  21. package/docs/en/mdcg/guardrail-charter.md +170 -0
  22. package/docs/en/mdcg/mcp-tool-names.md +43 -0
  23. package/docs/en/mdcg/multi-harness.md +43 -0
  24. package/docs/en/mdcg/recall-metadata.md +30 -0
  25. package/docs/en/mdcg/world-model-endpoint.md +379 -0
  26. package/docs/en/mdcg/write-aliases.md +130 -0
  27. package/docs/en/ops/README.md +11 -0
  28. package/docs/en/ops/environment-known-issues.md +244 -0
  29. package/docs/en/ops/install.md +72 -0
  30. package/docs/en/ops/operations-troubleshooting.md +86 -0
  31. package/docs/en/ops/permissions-review.md +79 -0
  32. package/docs/en/ops/release-governance.md +49 -0
  33. package/docs/en/ops/tool-name-migration.md +30 -0
  34. package/docs/en/ops/ui-install-troubleshooting.md +53 -0
  35. package/docs/en/standards/ai-coding-standard-checklist.md +71 -0
  36. package/docs/en/standards/ai-coding-standard-lingshu.md +47 -0
  37. package/docs/en/standards/ai-coding-standard.md +185 -0
  38. package/docs/en/ui/minimal.md +62 -0
  39. package/docs/mdcg/cogmap_ops.md +15 -15
  40. package/lib/hooks.d.ts +22 -0
  41. package/lib/hooks.js +124 -32
  42. package/lib/index.js +19 -3
  43. package/lib/lib/console_web.mjs +30 -3
  44. package/lib/lib/hook_audit.d.ts +3 -2
  45. package/lib/lib/hook_audit.js +14 -4
  46. package/lib/lib/mdcg_client.d.ts +5 -2
  47. package/lib/lib/mdcg_client.js +8 -4
  48. package/lib/lib/prompt_safety.d.ts +24 -0
  49. package/lib/lib/prompt_safety.js +77 -1
  50. package/lib/lib/token_store.js +5 -2
  51. package/lib/tools.js +5 -3
  52. package/md_cg/fsutil.py +80 -25
  53. package/md_cg/mcp_server.py +5761 -5557
  54. package/md_cg/mdcg.py +570 -73
  55. package/md_cg/mdcos.py +36 -11
  56. package/md_cg/nodefile.py +147 -23
  57. package/md_cg/op_table.py +14 -4
  58. package/md_cg/reconcile.py +9 -11
  59. package/md_cg/rollback.py +16 -1
  60. package/md_cg/scrub.py +94 -14
  61. package/md_cg/security.py +4 -2
  62. package/md_cg/test_cond_term_fold.py +183 -0
  63. package/md_cg/test_cond_terms_colon.py +348 -0
  64. package/md_cg/test_generation_guard.py +63 -42
  65. package/md_cg/test_issue362_neg_condition.py +44 -7
  66. package/md_cg/test_issue39_utf8_stdio.py +3 -3
  67. package/md_cg/test_issue444_scrub_evidence_plaintext.py +14 -8
  68. package/md_cg/test_issue677_flush_batch_io.py +139 -0
  69. package/md_cg/test_issue677_info_fast.py +82 -0
  70. package/md_cg/test_issue677_remember_dedupe.py +106 -0
  71. package/md_cg/test_issue712_tokens_sessions_read.py +199 -0
  72. package/md_cg/test_issue722_strict_conditions.py +96 -0
  73. package/md_cg/test_issue730_narrowing_audit.py +121 -0
  74. package/md_cg/test_issue733_verify_override.py +193 -0
  75. package/md_cg/test_issue733_verify_override_and_overwrite_inherit.py +315 -0
  76. package/md_cg/test_issue740_filelock_fd_leak.py +218 -0
  77. package/md_cg/test_issue741_content_hash_same_source.py +158 -0
  78. package/md_cg/test_issue747_slot_contradiction.py +125 -0
  79. package/md_cg/test_issue754_nested_root_guard.py +197 -0
  80. package/md_cg/test_issue757_index_hash_compare.py +85 -0
  81. package/md_cg/test_issue758_disk_hash_single.py +67 -0
  82. package/md_cg/test_issue759_twophase_hash.py +67 -0
  83. package/md_cg/test_n204_n205_n226_n227_n228_n229_exit_gates.py +545 -542
  84. package/md_cg/test_n209_verify_write_face_gates.py +5 -2
  85. package/md_cg/test_neg_condition_hits.py +336 -333
  86. package/md_cg/test_scrub_source_line_false_positive.py +64 -0
  87. package/md_cg/test_twophase.py +286 -286
  88. package/md_cg/tokens.py +55 -7
  89. package/md_cg/twophase.py +15 -6
  90. package/md_cg/writepipe.py +35 -3
  91. package/package.json +137 -134
  92. package/scripts/workspace_index.py +2 -0
  93. package/src/hooks.ts +139 -33
  94. package/src/index.ts +19 -3
  95. package/src/lib/console_web.mjs +30 -3
  96. package/src/lib/hook_audit.ts +15 -5
  97. package/src/lib/mdcg_client.ts +8 -4
  98. package/src/lib/prompt_safety.ts +73 -1
  99. package/src/lib/token_store.ts +5 -2
  100. package/src/tools.ts +5 -3
  101. package/ui/minimal/integrity.json +2 -2
  102. package/ui/minimal/payload/lib/lib/console_web.mjs +30 -3
  103. package/ui/minimal/payload/src/lib/console_web.mjs +30 -3
@@ -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;
package/md_cg/fsutil.py CHANGED
@@ -131,44 +131,75 @@ class FileLock:
131
131
 
132
132
  # 生效条件:先按 self.path 建父目录并 open(self.path, "a+b"),再在 self.timeout 到期前每 self.poll 秒尝试加锁(IS_WIN 用 msvcrt.locking(LK_NBLCK),否则 fcntl.flock(LOCK_EX|LOCK_NB));成功即置 self.acquired=True 并返回 self;OSError 的 errno 不在 (EACCES, EAGAIN, EDEADLK) 时直接 raise,超时后 self.strict 为真抛 TimeoutError、否则返回 self 放行。
133
133
  def __enter__(self):
134
+ # issue #740:**进入前先清掉可能的旧句柄**(重复 enter / 上次未 exit)——
135
+ # 否则旧 fd 静默泄漏;POSIX 下还会与自己的旧 fd 互斥(表现为「卡到超时」)。
136
+ if getattr(self, "_f", None) is not None:
137
+ self._close_fd()
138
+ self.acquired = False
134
139
  os.makedirs(os.path.dirname(os.path.abspath(self.path)) or ".", exist_ok=True)
135
140
  self._f = open(self.path, "a+b")
136
- deadline = time.time() + self.timeout
137
- while True:
138
- try:
139
- if IS_WIN:
140
- self._f.seek(0)
141
- msvcrt.locking(self._f.fileno(), msvcrt.LK_NBLCK, 1)
142
- else:
143
- fcntl.flock(self._f.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
144
- self.acquired = True
145
- return self
146
- except OSError as e:
147
- if e.errno not in (errno.EACCES, errno.EAGAIN, errno.EDEADLK):
148
- raise
149
- if time.time() > deadline:
150
- if self.strict:
151
- raise TimeoutError(
152
- f"FileLock 超时未获锁(strict):{self.path}")
153
- return self # 放行,不阻断写路径
154
- time.sleep(self.poll)
141
+ try:
142
+ # #740:`try` **必须紧贴 open 之后**——`time.time() + self.timeout` 本身就可能
143
+ # 抛(timeout 为 None/字符串时 TypeError),那时 fd 已打开而 `__exit__` 不会
144
+ # 被调用(with 的清理只在 __enter__ 正常返回后才注册)。
145
+ deadline = time.time() + self.timeout
146
+ while True:
147
+ try:
148
+ if IS_WIN:
149
+ self._f.seek(0)
150
+ msvcrt.locking(self._f.fileno(), msvcrt.LK_NBLCK, 1)
151
+ else:
152
+ fcntl.flock(self._f.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
153
+ self.acquired = True
154
+ return self
155
+ except OSError as e:
156
+ if e.errno not in (errno.EACCES, errno.EAGAIN, errno.EDEADLK):
157
+ raise
158
+ if time.time() > deadline:
159
+ if self.strict:
160
+ raise TimeoutError(
161
+ f"FileLock 超时未获锁(strict):{self.path}")
162
+ # 非 strict:放行且**显式**标记未持锁(实例复用时靠它区分)。
163
+ self.acquired = False
164
+ return self
165
+ time.sleep(self.poll)
166
+ except BaseException:
167
+ # #740:任何异常路径(含 KeyboardInterrupt / SystemExit / TypeError)都先关 fd
168
+ # 再原样上抛——清理本身绝不抛(否则会遮蔽原始异常)。
169
+ self._close_fd()
170
+ raise
171
+
172
+ def _close_fd(self):
173
+ """关句柄并复位状态(#740:**单点关闭**,幂等、绝不抛)。
174
+
175
+ - `getattr` 兜底:`__init__` 之前的异常/兼容旧实例时不出现 AttributeError;
176
+ - 吞 `(OSError, ValueError)`:重复 close(ValueError: I/O operation on closed file)
177
+ 与平台错误都不该冒泡——清理函数抛异常会遮蔽原始异常。
178
+ """
179
+ f = getattr(self, "_f", None)
180
+ self._f = None
181
+ self.acquired = False
182
+ if f is None:
183
+ return
184
+ try:
185
+ f.close()
186
+ except (OSError, ValueError):
187
+ pass
155
188
 
156
189
  # 生效条件:self.acquired 为真时按 IS_WIN 用 msvcrt.locking(LK_UNLCK) 或 fcntl.flock(LOCK_UN) 解锁(OSError 被吞掉);finally 中只要 self._f 为真就 close,随后 self._f=None、self.acquired=False。
157
190
  def __exit__(self, *exc):
158
191
  try:
159
- if self.acquired:
192
+ # #740:`_f` 可能已是 None(进入失败/已关)——显式判空,别让 finally 崩。
193
+ if self.acquired and getattr(self, "_f", None) is not None:
160
194
  if IS_WIN:
161
195
  self._f.seek(0)
162
196
  msvcrt.locking(self._f.fileno(), msvcrt.LK_UNLCK, 1)
163
197
  else:
164
198
  fcntl.flock(self._f.fileno(), fcntl.LOCK_UN)
165
- except OSError:
199
+ except (OSError, ValueError):
166
200
  pass
167
201
  finally:
168
- if self._f:
169
- self._f.close()
170
- self._f = None
171
- self.acquired = False
202
+ self._close_fd() # 单点关闭(幂等,绝不抛)
172
203
 
173
204
 
174
205
  # 生效条件:作为 `with` 的空上下文——进入返回自身、退出返回 False(不吞异常)。
@@ -1006,6 +1037,30 @@ class ShardedLog:
1006
1037
  separators=(",", ":")) + "\n")
1007
1038
  self._fh.flush()
1008
1039
 
1040
+ # 生效条件:records 为 list[dict](空列表直接返回 0);句柄按需打开,**一次 write + 一次 flush**
1041
+ # (#677 C 根治:把「每条 flush」降为「每批一次」——锁内 IO 次数从 O(N) 降为 O(1),
1042
+ # 而整批仍在调用方的同一个 FileLock 内,与 compact 的 read→clear 互斥语义不变)。
1043
+ def append_many(self, records):
1044
+ recs = list(records or [])
1045
+ if not recs:
1046
+ return 0
1047
+ if self._fh is None:
1048
+ ensure_shard_dir(self.dir, "append")
1049
+ self._fh = open(self.path, "a", encoding="utf-8", newline="\n")
1050
+ # #677 C 复核:上次崩溃可能留下**残尾**(末字节不是换行)。不补一个换行就追加,
1051
+ # 新批第 1 条会与残尾粘成一行——语法完整但解析失败,重放游标照样推进 ⇒
1052
+ # 残尾与那条好记录一起永久丢失(与 append_jsonl 的 ends_mid_line 同一防线)。
1053
+ if ends_mid_line(self.path):
1054
+ self._fh.write("\n")
1055
+ out = []
1056
+ for record in recs:
1057
+ self._seq += 1
1058
+ out.append(json.dumps(dict(record, _t=time.time(), _s=self._seq),
1059
+ ensure_ascii=False, separators=(",", ":")))
1060
+ self._fh.write("\n".join(out) + "\n")
1061
+ self._fh.flush()
1062
+ return len(out)
1063
+
1009
1064
  # 生效条件:幂等;self._fh 为真值时 flush 并关闭句柄、再把 self._fh 置 None,为 None 时直接返回不报错;
1010
1065
  def close(self):
1011
1066
  if self._fh: