@furongjun1999/dsh-memory 0.9.6 → 0.9.7

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 (216) hide show
  1. package/data/policy.json +38 -38
  2. package/docs/discipline/templates/spec.txt.tmpl +1 -1
  3. package/dsh/cordis.yml.example +139 -139
  4. package/lib/hooks.d.ts +19 -0
  5. package/lib/hooks.js +29 -6
  6. package/lib/index.js +11 -2
  7. package/lib/lib/hook_audit.js +38 -2
  8. package/lib/lib/prompt_safety.js +14 -3
  9. package/lib/tools.d.ts +7 -0
  10. package/lib/tools.js +22 -1
  11. package/md_cg/_guard_kit.py +121 -121
  12. package/md_cg/anchor.py +114 -114
  13. package/md_cg/audit.py +15 -2
  14. package/md_cg/chain.py +3 -2
  15. package/md_cg/config_registry_guard.py +487 -487
  16. package/md_cg/conformance.py +747 -747
  17. package/md_cg/consolidate.py +1793 -1793
  18. package/md_cg/crypto.py +794 -794
  19. package/md_cg/hyperedge.py +262 -262
  20. package/md_cg/interface_schema.py +146 -146
  21. package/md_cg/lifecycle.py +426 -426
  22. package/md_cg/mdcos.py +12 -8
  23. package/md_cg/predict.py +1103 -1103
  24. package/md_cg/protect.py +654 -654
  25. package/md_cg/provenance.py +606 -606
  26. package/md_cg/queue_health.py +130 -130
  27. package/md_cg/refine.py +613 -613
  28. package/md_cg/retrieve.py +128 -128
  29. package/md_cg/revise.py +140 -140
  30. package/md_cg/rollback.py +657 -657
  31. package/md_cg/rollback_cli.py +124 -124
  32. package/md_cg/rotate.py +346 -346
  33. package/md_cg/routing.py +490 -490
  34. package/md_cg/self_surface.py +50 -50
  35. package/md_cg/semantic/canonical.py +144 -144
  36. package/md_cg/semantic/zh_en_atoms.py +141 -141
  37. package/md_cg/sources.py +1091 -1091
  38. package/md_cg/stg.py +3 -2
  39. package/md_cg/test_audit_rotate_parity.py +279 -279
  40. package/md_cg/test_autonomy_modes.py +2013 -2013
  41. package/md_cg/test_cn_recall_grams.py +206 -206
  42. package/md_cg/test_code_kind_forbidden.py +101 -0
  43. package/md_cg/test_condaccept.py +156 -156
  44. package/md_cg/test_condgate.py +141 -141
  45. package/md_cg/test_heartbeat_ledger.py +557 -557
  46. package/md_cg/test_i50e_readside_protection.py +658 -658
  47. package/md_cg/test_issue111_gate_order.py +76 -76
  48. package/md_cg/test_issue111_scoring_contract.py +86 -86
  49. package/md_cg/test_issue121_calibration_bounds.py +293 -293
  50. package/md_cg/test_issue145_sleep_no_silent_rollback.py +167 -167
  51. package/md_cg/test_issue147_pack_id_escape.py +378 -378
  52. package/md_cg/test_issue148_merge_downgrade_leak.py +192 -192
  53. package/md_cg/test_issue149_accel_default_face.py +248 -248
  54. package/md_cg/test_issue150_empty_query_terms.py +328 -328
  55. package/md_cg/test_issue151_153_157_write_cache_index.py +151 -151
  56. package/md_cg/test_issue152_sealed_postings.py +309 -309
  57. package/md_cg/test_issue153b_index_generation_invalidation.py +142 -142
  58. package/md_cg/test_issue157b_index_remainder.py +344 -344
  59. package/md_cg/test_issue189_conclusion_bidirectional.py +223 -223
  60. package/md_cg/test_issue191_import_trust.py +382 -382
  61. package/md_cg/test_issue193_write_scope.py +378 -378
  62. package/md_cg/test_issue212_writeface_gaps.py +349 -349
  63. package/md_cg/test_issue214_reject_sensitivity.py +266 -266
  64. package/md_cg/test_issue215_condition_source_gap.py +272 -272
  65. package/md_cg/test_issue216_clash_routes.py +214 -214
  66. package/md_cg/test_issue217_slot_routes.py +248 -248
  67. package/md_cg/test_issue218_postcondition_value_blind.py +222 -222
  68. package/md_cg/test_issue258_pack_sensitivity.py +468 -468
  69. package/md_cg/test_issue265_coldverify_multiproc.py +438 -438
  70. package/md_cg/test_issue274_read_node_id_none.py +341 -341
  71. package/md_cg/test_issue275_layer_param.py +250 -250
  72. package/md_cg/test_issue277_node_id_traversal.py +384 -384
  73. package/md_cg/test_issue278_neg_separated_tension.py +271 -271
  74. package/md_cg/test_issue278_neg_window.py +294 -294
  75. package/md_cg/test_issue278_negative_layering.py +83 -83
  76. package/md_cg/test_issue284_skip_not_pass.py +291 -291
  77. package/md_cg/test_issue294_flywheel_sensitivity.py +573 -573
  78. package/md_cg/test_issue301_baseline_corpus_gate.py +245 -245
  79. package/md_cg/test_issue303_design_boundaries.py +262 -262
  80. package/md_cg/test_issue315_merge_branch_sensitivity.py +383 -383
  81. package/md_cg/test_issue319_tenant_unregistered_bypass.py +256 -256
  82. package/md_cg/test_issue321_mcp_deep_json.py +304 -304
  83. package/md_cg/test_issue322_node_write_lock.py +727 -727
  84. package/md_cg/test_issue324_write_size_fields.py +214 -214
  85. package/md_cg/test_issue325_audit_poison.py +229 -229
  86. package/md_cg/test_issue326_ingest_auto_whitelist.py +331 -331
  87. package/md_cg/test_issue326_key_perms.py +355 -355
  88. package/md_cg/test_issue326_twin_parser_parity.py +323 -323
  89. package/md_cg/test_issue326_vm_call_frame.py +569 -569
  90. package/md_cg/test_issue345_writelimit_effective_sens.py +233 -233
  91. package/md_cg/test_issue346_overwrite_sensitivity_gate.py +424 -424
  92. package/md_cg/test_issue348_insight_verify_op.py +199 -199
  93. package/md_cg/test_issue348_merge_rmw_lock.py +345 -345
  94. package/md_cg/test_issue350_casefold_collision.py +235 -235
  95. package/md_cg/test_issue351_ingest_root_fallback.py +201 -201
  96. package/md_cg/test_issue352_imgaudit.py +418 -418
  97. package/md_cg/test_issue352_pathsjson.py +537 -537
  98. package/md_cg/test_issue352_refindex.py +412 -412
  99. package/md_cg/test_issue352_rollback.py +604 -604
  100. package/md_cg/test_issue354_p2_writelimit_toctou.py +327 -327
  101. package/md_cg/test_issue354_rust_index_containment.py +571 -571
  102. package/md_cg/test_issue354_rust_wal_containment.py +606 -606
  103. package/md_cg/test_issue358_truncation_observable.py +247 -247
  104. package/md_cg/test_issue360_tidy_private_excerpt.py +195 -195
  105. package/md_cg/test_issue361_blindspot_not_silent_drop.py +494 -494
  106. package/md_cg/test_issue362_neg_condition.py +468 -468
  107. package/md_cg/test_issue363_lexical_idf.py +275 -275
  108. package/md_cg/test_issue370_readcache_assembly.py +488 -488
  109. package/md_cg/test_issue376_heartbeat_failed.py +293 -293
  110. package/md_cg/test_issue377_layer_protect_stamp.py +324 -324
  111. package/md_cg/test_issue378_protected_floor.py +310 -310
  112. package/md_cg/test_issue383_state_event_write_gate.py +462 -462
  113. package/md_cg/test_issue397_sens_eff_wiring.py +435 -435
  114. package/md_cg/test_issue398_toolface_op_parity.py +511 -511
  115. package/md_cg/test_issue399_hive_json_shape.py +317 -317
  116. package/md_cg/test_issue401_wisdom_codegen.py +295 -295
  117. package/md_cg/test_issue404_heal_receipt.py +389 -389
  118. package/md_cg/test_issue409_compact_index_completeness.py +509 -509
  119. package/md_cg/test_issue410_verify_demote_write.py +366 -366
  120. package/md_cg/test_issue411_scrub_idempotence.py +575 -575
  121. package/md_cg/test_issue412_discipline_producer_parity.py +311 -311
  122. package/md_cg/test_issue413_preimage_failclosed.py +239 -239
  123. package/md_cg/test_issue413_preimage_twin.py +339 -339
  124. package/md_cg/test_issue415_deps_gate_probe.py +357 -357
  125. package/md_cg/test_issue416_entry_key_subset.py +525 -525
  126. package/md_cg/test_issue417_twophase_merge_landed.py +423 -423
  127. package/md_cg/test_issue425_ingest_library_path.py +331 -331
  128. package/md_cg/test_issue426c_enqueue_not_silent.py +346 -346
  129. package/md_cg/test_issue426e_restore_overwrite_live.py +310 -310
  130. package/md_cg/test_issue426f_paths_gbk_failclosed.py +301 -301
  131. package/md_cg/test_issue427_serve_status_shape.py +191 -191
  132. package/md_cg/test_issue431_432_468_protect_single_point.py +322 -322
  133. package/md_cg/test_issue433_outlook_threshold_single_point.py +278 -278
  134. package/md_cg/test_issue434_435_float_gate.py +90 -90
  135. package/md_cg/test_issue439_sibling_sensitivity_inherit.py +448 -448
  136. package/md_cg/test_issue43_default_policy.py +874 -874
  137. package/md_cg/test_issue444_scrub_evidence_plaintext.py +281 -281
  138. package/md_cg/test_issue445_metacognition_ledger_gate.py +454 -454
  139. package/md_cg/test_issue446_453_403_verified_evidence.py +382 -382
  140. package/md_cg/test_issue450_sensitivity_fallback_reason.py +51 -51
  141. package/md_cg/test_issue450_writegate_unknown_sens.py +203 -203
  142. package/md_cg/test_issue451_audit_actor.py +313 -313
  143. package/md_cg/test_issue452_ingest_root_sensitivity.py +299 -299
  144. package/md_cg/test_issue463_ghost_prune_guard.py +259 -259
  145. package/md_cg/test_issue466_basis_registry.py +469 -469
  146. package/md_cg/test_issue467_identity_sensitivity_parity.py +360 -360
  147. package/md_cg/test_issue469_scrub_override_passthrough.py +126 -126
  148. package/md_cg/test_issue470_wal_event_durable.py +427 -427
  149. package/md_cg/test_issue471_identity_readable.py +136 -136
  150. package/md_cg/test_issue472_audit_chain.py +90 -90
  151. package/md_cg/test_issue472_prune_ledger.py +105 -105
  152. package/md_cg/test_issue472_rollback_degraded.py +81 -81
  153. package/md_cg/test_issue491_compose_sandbox.py +460 -460
  154. package/md_cg/test_issue498_merge_trace_stale_index.py +280 -280
  155. package/md_cg/test_issue511_scoreboard_bad_files.py +256 -256
  156. package/md_cg/test_issue521_rotate_lock_suffix.py +110 -110
  157. package/md_cg/test_issue524_orphan_noise_no_demote.py +88 -88
  158. package/md_cg/test_issue525_read_null_semantics.py +52 -52
  159. package/md_cg/test_issue547_append_jsonl_whitelist.py +114 -114
  160. package/md_cg/test_issue547_audit_durable.py +96 -96
  161. package/md_cg/test_issue557_r2_write_entries_size_gate.py +83 -83
  162. package/md_cg/test_issue559_refine_prefix.py +69 -69
  163. package/md_cg/test_issue562_retired_faces.py +150 -0
  164. package/md_cg/test_issue71_queue_backlog.py +376 -376
  165. package/md_cg/test_issue72_coldverify_controlled_drain.py +420 -420
  166. package/md_cg/test_issue82_credential_rules.py +271 -271
  167. package/md_cg/test_issue91_verifier_sandbox.py +314 -314
  168. package/md_cg/test_issue93_remember_redaction.py +282 -282
  169. package/md_cg/test_logref.py +1141 -1141
  170. package/md_cg/test_md_access_parity.py +330 -330
  171. package/md_cg/test_md_cg_no_hive_dep.py +139 -139
  172. package/md_cg/test_mutation_residue.py +119 -119
  173. package/md_cg/test_mutation_rollback.py +835 -835
  174. package/md_cg/test_n123_derive_expiry_chain.py +210 -210
  175. package/md_cg/test_n209_verify_write_face_gates.py +466 -466
  176. package/md_cg/test_n62_tenant_bind_failclosed.py +200 -200
  177. package/md_cg/test_neg_tail_honesty.py +733 -733
  178. package/md_cg/test_p21_tokens.py +294 -294
  179. package/md_cg/test_p27_docindex.py +792 -792
  180. package/md_cg/test_p28_refcheck.py +1053 -1053
  181. package/md_cg/test_p2_six_elements.py +476 -476
  182. package/md_cg/test_p33_ccg_wiring.py +300 -300
  183. package/md_cg/test_p3_legacy_closure.py +438 -438
  184. package/md_cg/test_p40_refine_worklist.py +244 -244
  185. package/md_cg/test_p4_freshness.py +781 -781
  186. package/md_cg/test_p9c_dedup_hints.py +288 -288
  187. package/md_cg/test_policy_required_ccg.py +444 -444
  188. package/md_cg/test_retr_s5.py +312 -312
  189. package/md_cg/test_s1_ast_judge.py +109 -109
  190. package/md_cg/test_state_event_op.py +521 -521
  191. package/md_cg/test_stgidx_index_parity.py +1024 -1024
  192. package/md_cg/test_sustain_bounded.py +652 -652
  193. package/md_cg/test_trust_edge_reachability.py +405 -405
  194. package/md_cg/test_w7_redlines.py +659 -659
  195. package/md_cg/test_write_return_shape.py +919 -919
  196. package/md_cg/test_writepipe.py +228 -228
  197. package/md_cg/trust.py +1114 -1114
  198. package/md_cg/twophase.py +303 -303
  199. package/md_cg/whitebox.py +536 -536
  200. package/md_cg/whitebox_kb/wisdom/compose_engine.py +1634 -1634
  201. package/md_cg/whitebox_kb/wisdom/core/condition_vm.py +318 -318
  202. package/md_cg/whitebox_kb/wisdom/core/parser.py +1082 -1082
  203. package/md_cg/whitebox_kb/wisdom/md_access.py +490 -490
  204. package/md_cg/whitebox_kb/wisdom/migrate_wisdom.py +497 -497
  205. package/md_cg/whitebox_kb/wisdom/mini_python.py +995 -995
  206. package/md_cg/whitebox_kb/wisdom/net_units.py +2900 -2900
  207. package/md_cg/whitebox_kb/wisdom/semantic_translate.py +4060 -4060
  208. package/md_cg/writepipe.py +1337 -1337
  209. package/package.json +3 -2
  210. package/scripts/workspace_index.py +328 -0
  211. package/src/hooks.ts +30 -6
  212. package/src/index.ts +14 -5
  213. package/src/lib/hook_audit.ts +282 -256
  214. package/src/lib/mdcg_client.ts +469 -469
  215. package/src/lib/prompt_safety.ts +17 -3
  216. package/src/tools.ts +23 -1
@@ -1,256 +1,282 @@
1
- /**
2
- * hook_audit.ts · 自动记忆钩子的**有界落盘审计**(issue #56,诊断面)
3
- *
4
- * 病灶(报告人 jiamajie,v0.7.1 实测):src/hooks.ts 的三处过滤分支(子代理会话 /
5
- * 中继消息 / `source.kind !== 'user'`)只调 `ctx.logger.info`——宿主 logger 不落盘,
6
- * 盘面完全无痕。其它插件按设计注入的 `role:"user"` 消息(如 @michengai/dsh-pua 的
7
- * PUA_RUNTIME_V1 提示)不进记忆库时,从记忆侧只能看到「少了一条」,无法区分
8
- * 「被设计滤除」与「写入失败/漏记」。
9
- *
10
- * 本模块 = **诊断面**,不参与任何写入/过滤判定(红线:哪些消息进记忆一字不动):
11
- * ① 维护一份小 JSON 状态文件(缺省 `~/.dsh/logs/dsh-memory-hook-audit.json`,
12
- * 与 `lingshu-bridge-debug.log` / `dsh-memory-apply-error.log` 同目录同惯例,
13
- * 见 README.md:110);
14
- * ② 每事件只写计数与「最近条目」摘要(action/reason/kind/role),**绝不记录
15
- * 消息内容**(内容可能含隐私/凭据,审计文件是可被随手打开的诊断件);
16
- * ③ 原子写:同目录临时文件 + rename(读者永远不会看到半截 JSON);
17
- * ④ 有界:last 截断到 MAX_LAST=20(无追加式增长);kinds 键数上限 MAX_KINDS,
18
- * 超限归并到 "other"(kind 值域理论上由宿主决定,防异常值把文件撑大);
19
- * ⑤ 静默降级:公共方法全部 try/catch 包死——审计失败绝不冒泡进记忆路径
20
- * (审计是增益,记忆写入必须照常)。
21
- *
22
- * 为什么落盘采用**同步** fs:`session/event` 回调是同步的,异步落盘会引入
23
- * 「多事件并发写同一文件」的乱序与竞态;状态文件只有几 KB,一次同步读(仅首次)
24
- * 加一次全量重写的代价远小于它守护的诊断价值。
25
- *
26
- * 与 ctx.logger.info 的关系:hook 内三行 info 日志**保留不动**(in-memory 实时
27
- * 视图),本审计是**盘面**视图(宿主 logger 不落盘时仍可复盘)。
28
- *
29
- * 边界(如实):
30
- * · 状态是「进程内缓存 + 每次全量重写」,多进程同时写同一路径会互相覆盖
31
- * (插件单实例部署下不构成问题;审计非关键路径,不做跨进程锁);
32
- * · 审计文件损坏/手改致形态不符时按空态重建(数值归零、last 逐条过滤),
33
- * 不抛错、不保留非法内容;
34
- * · `written` 记的是「**成功发起**」的写入(fire-and-forget 的发起时刻),
35
- * 发起后失败另记 `skipped.failed`——与 hooks.ts 的 memorize 两段式对应。
36
- */
37
- import { mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs'
38
- import { homedir } from 'node:os'
39
- import { expandHome } from './datapath.js'
40
- import { dirname, join } from 'node:path'
41
-
42
- /** 三处过滤分支的成因(与 hooks.ts 一一对应:子代理会话 / 中继消息 / kind 非 user)。 */
43
- export type HookFilterReason = 'subagent' | 'relay' | 'kind'
44
- /** 写入路径的角色(与 md_cg 对 DSH 会话事件的 role 约定一致)。 */
45
- export type HookWriteRole = 'user' | 'assistant' | 'tool'
46
- /** 跳过写入的成因。 */
47
- export type HookSkipReason = 'sanitized' | 'not_ready' | 'failed'
48
-
49
- /** last 的一条摘要(**绝不含消息内容**——只有动作、成因、kind 与 role)。 */
50
- export interface HookAuditEntry {
51
- ts: string
52
- action: 'filtered' | 'written' | 'skipped'
53
- reason?: HookFilterReason | HookSkipReason
54
- kind?: string
55
- role?: HookWriteRole
56
- }
57
-
58
- /** 审计状态(= 状态文件的结构)。 */
59
- export interface HookAuditState {
60
- counts: {
61
- /** 三处过滤分支的计数。 */
62
- filtered: Record<HookFilterReason, number>
63
- /** 成功发起的写入计数(按 role 分解)。 */
64
- written: Record<HookWriteRole, number>
65
- /** 跳过写入的计数(脱敏置空 / 认知图未就绪 / 写入失败)。 */
66
- skipped: Record<HookSkipReason, number>
67
- }
68
- /** 进入消息级处理的 `source.kind` 分布(缺字段/空串/非字符串记 "undefined")。 */
69
- kinds: Record<string, number>
70
- /** 最近 ≤MAX_LAST 条摘要。 */
71
- last: HookAuditEntry[]
72
- updated_at: string
73
- }
74
-
75
- /** 缺省审计文件:与桥探针 / apply 探针同目录同惯例(README.md:110)。 */
76
- /**
77
- * 审计根:优先 `DSH_HOME`(隔离/多 home 安装必须显式给),否则 `~/.dsh`。
78
- * issue #554 §7:此前恒用 homedir,隔离 home 下审计写到生产 home,与 brain 分离。
79
- * 兼容 `~` 与 `~/x` 形态;其余按字面路径处理(不做 shell 展开)。
80
- */
81
- function defaultHookAuditPath(): string {
82
- const raw = (process.env.DSH_HOME ?? '').trim()
83
- // 唯一实现:路径展开复用 datapath.expandHome(禁止第二处判据,见 test/datapath-expandhome)。
84
- const root = raw ? expandHome(raw) : join(homedir(), '.dsh')
85
- return join(root, 'logs', 'dsh-memory-hook-audit.json')
86
- }
87
-
88
- export const DEFAULT_HOOK_AUDIT_PATH = defaultHookAuditPath()
89
-
90
- /** last 条数上限(有界性单点——没有它 audit 文件会随会话无限增长)。 */
91
- const MAX_LAST = 20
92
- /** kinds 键数上限(超限归并到 OTHER_KIND,防宿主 kind 值域异常撑大文件)。 */
93
- const MAX_KINDS = 32
94
- /** kinds 归并桶。 */
95
- const OTHER_KIND = 'other'
96
-
97
- const FILTER_REASONS: HookFilterReason[] = ['subagent', 'relay', 'kind']
98
- const WRITE_ROLES: HookWriteRole[] = ['user', 'assistant', 'tool']
99
- const SKIP_REASONS: HookSkipReason[] = ['sanitized', 'not_ready', 'failed']
100
-
101
- /** `source.kind` 的规范化取值:非字符串(含缺字段)或空串一律记 "undefined"
102
- * (不可辨认即无值——空串与缺字段在排障上同义)。 */
103
- export function kindOf(source: unknown): string {
104
- const k = (source as { kind?: unknown } | null | undefined)?.kind
105
- return typeof k === 'string' && k.length > 0 ? k : 'undefined'
106
- }
107
-
108
- function nowIso(): string {
109
- return new Date().toISOString()
110
- }
111
-
112
- function emptyState(): HookAuditState {
113
- return {
114
- counts: {
115
- filtered: { subagent: 0, relay: 0, kind: 0 },
116
- written: { user: 0, assistant: 0, tool: 0 },
117
- skipped: { sanitized: 0, not_ready: 0, failed: 0 },
118
- },
119
- kinds: {},
120
- last: [],
121
- updated_at: nowIso(),
122
- }
123
- }
124
-
125
- /** 计数位:只认有限非负整数,其余归零(防手改/坏文件把计数变成 NaN)。 */
126
- function countOf(v: unknown): number {
127
- return typeof v === 'number' && Number.isFinite(v) && v >= 0 ? Math.floor(v) : 0
128
- }
129
-
130
- /** 盘面内容 → 状态:逐字段归并,形态不符的字段一律丢弃(不信任盘面内容)。 */
131
- function mergeState(raw: unknown): HookAuditState {
132
- const s = emptyState()
133
- if (!raw || typeof raw !== 'object') return s
134
- const r = raw as { counts?: unknown; kinds?: unknown; last?: unknown }
135
- if (r.counts && typeof r.counts === 'object') {
136
- const c = r.counts as { filtered?: unknown; written?: unknown; skipped?: unknown }
137
- const buckets: Array<[Record<string, number>, string[], unknown]> = [
138
- [s.counts.filtered as Record<string, number>, FILTER_REASONS, c.filtered],
139
- [s.counts.written as Record<string, number>, WRITE_ROLES, c.written],
140
- [s.counts.skipped as Record<string, number>, SKIP_REASONS, c.skipped],
141
- ]
142
- for (const [dst, keys, src] of buckets) {
143
- if (!src || typeof src !== 'object') continue
144
- for (const key of keys) dst[key] = countOf((src as Record<string, unknown>)[key])
145
- }
146
- }
147
- if (r.kinds && typeof r.kinds === 'object') {
148
- for (const [k, v] of Object.entries(r.kinds as Record<string, unknown>)) {
149
- if (typeof v === 'number' && Number.isFinite(v) && v > 0) s.kinds[k] = Math.floor(v)
150
- }
151
- }
152
- if (Array.isArray(r.last)) {
153
- for (const e of r.last) {
154
- if (!e || typeof e !== 'object') continue
155
- const entry = e as Partial<HookAuditEntry>
156
- if (typeof entry.ts !== 'string') continue
157
- if (entry.action !== 'filtered' && entry.action !== 'written' && entry.action !== 'skipped') continue
158
- s.last.push(entry as HookAuditEntry)
159
- }
160
- if (s.last.length > MAX_LAST) s.last = s.last.slice(-MAX_LAST)
161
- }
162
- return s
163
- }
164
-
165
- /**
166
- * 有界落盘审计记录器(**静默降级**:任何公共方法都不会抛错)。
167
- *
168
- * 用法(hooks.ts 内):`new HookAuditRecorder(opts.auditPath)`,随后在
169
- * 三处过滤分支与写入/跳过路径各调一次对应方法。审计失败只影响审计自身。
170
- */
171
- export class HookAuditRecorder {
172
- /** 实际生效的审计文件路径(构造时定死,供日志/测试核对)。 */
173
- readonly path: string
174
- /** 进程内状态缓存(首次记录时从盘面载入,此后只增量改内存 + 全量重写)。 */
175
- #state: HookAuditState | null = null
176
-
177
- constructor(path?: string) {
178
- this.path = typeof path === 'string' && path.trim() ? path.trim() : DEFAULT_HOOK_AUDIT_PATH
179
- }
180
-
181
- /** 一条**被设计滤除**的消息(三处过滤分支各调一次)。 */
182
- filtered(reason: HookFilterReason, kind?: string): void {
183
- this.#mutate((s) => {
184
- s.counts.filtered[reason] += 1
185
- s.last.push(kind === undefined
186
- ? { ts: nowIso(), action: 'filtered', reason }
187
- : { ts: nowIso(), action: 'filtered', reason, kind })
188
- })
189
- }
190
-
191
- /** `source.kind` 分布(每条**进入消息级处理**的事件调一次,含被滤与放行)。 */
192
- observeKind(kind: string): void {
193
- this.#mutate((s) => {
194
- const key = this.#boundedKindKey(s, kind)
195
- s.kinds[key] = (s.kinds[key] ?? 0) + 1
196
- })
197
- }
198
-
199
- /** 成功**发起**的写入(按 role;发起后失败另记 skipped.failed)。 */
200
- written(role: HookWriteRole): void {
201
- this.#mutate((s) => {
202
- s.counts.written[role] += 1
203
- s.last.push({ ts: nowIso(), action: 'written', role })
204
- })
205
- }
206
-
207
- /** 跳过写入(脱敏置空 / 认知图未就绪 / 写入失败)。 */
208
- skipped(reason: HookSkipReason, role?: HookWriteRole): void {
209
- this.#mutate((s) => {
210
- s.counts.skipped[reason] += 1
211
- s.last.push(role === undefined
212
- ? { ts: nowIso(), action: 'skipped', reason }
213
- : { ts: nowIso(), action: 'skipped', reason, role })
214
- })
215
- }
216
-
217
- /** 键数有界:已见键原样用;新键在未达上限时收录,达限后统一归并到 "other"。 */
218
- #boundedKindKey(s: HookAuditState, kind: string): string {
219
- if (Object.prototype.hasOwnProperty.call(s.kinds, kind)) return kind
220
- return Object.keys(s.kinds).length >= MAX_KINDS ? OTHER_KIND : kind
221
- }
222
-
223
- /** 读改写 + 原子落盘;整段 try/catch——审计失败静默降级(绝不冒泡进记忆路径)。 */
224
- #mutate(fn: (s: HookAuditState) => void): void {
225
- try {
226
- const s = this.#state ?? (this.#state = this.#load())
227
- fn(s)
228
- if (s.last.length > MAX_LAST) s.last = s.last.slice(-MAX_LAST)
229
- s.updated_at = nowIso()
230
- this.#save(s)
231
- } catch { /* 审计失败静默降级:记忆路径必须照常 */ }
232
- }
233
-
234
- /** 盘面 → 状态;不存在/不可读/坏 JSON/形态不符 → 空态重建(不抛)。 */
235
- #load(): HookAuditState {
236
- try {
237
- return mergeState(JSON.parse(readFileSync(this.path, 'utf8')) as unknown)
238
- } catch {
239
- return emptyState()
240
- }
241
- }
242
-
243
- /** 原子写:同目录临时文件 + rename(临时文件在 rename 失败时清理)。 */
244
- #save(s: HookAuditState): void {
245
- const dir = dirname(this.path)
246
- mkdirSync(dir, { recursive: true })
247
- const tmp = `${this.path}.${process.pid.toString(36)}.${Date.now().toString(36)}.tmp`
248
- writeFileSync(tmp, `${JSON.stringify(s, null, 2)}\n`, 'utf8')
249
- try {
250
- renameSync(tmp, this.path)
251
- } catch (err) {
252
- try { unlinkSync(tmp) } catch { /* 清理失败忽略:残留 .tmp 不影响读路径 */ }
253
- throw err
254
- }
255
- }
256
- }
1
+ /**
2
+ * hook_audit.ts · 自动记忆钩子的**有界落盘审计**(issue #56,诊断面)
3
+ *
4
+ * 病灶(报告人 jiamajie,v0.7.1 实测):src/hooks.ts 的三处过滤分支(子代理会话 /
5
+ * 中继消息 / `source.kind !== 'user'`)只调 `ctx.logger.info`——宿主 logger 不落盘,
6
+ * 盘面完全无痕。其它插件按设计注入的 `role:"user"` 消息(如 @michengai/dsh-pua 的
7
+ * PUA_RUNTIME_V1 提示)不进记忆库时,从记忆侧只能看到「少了一条」,无法区分
8
+ * 「被设计滤除」与「写入失败/漏记」。
9
+ *
10
+ * 本模块 = **诊断面**,不参与任何写入/过滤判定(红线:哪些消息进记忆一字不动):
11
+ * ① 维护一份小 JSON 状态文件(缺省 `~/.dsh/logs/dsh-memory-hook-audit.json`,
12
+ * 与 `lingshu-bridge-debug.log` / `dsh-memory-apply-error.log` 同目录同惯例,
13
+ * 见 README.md:110);
14
+ * ② 每事件只写计数与「最近条目」摘要(action/reason/kind/role),**绝不记录
15
+ * 消息内容**(内容可能含隐私/凭据,审计文件是可被随手打开的诊断件);
16
+ * ③ 原子写:同目录临时文件 + rename(读者永远不会看到半截 JSON);
17
+ * ④ 有界:last 截断到 MAX_LAST=20(无追加式增长);kinds 键数上限 MAX_KINDS,
18
+ * 超限归并到 "other"(kind 值域理论上由宿主决定,防异常值把文件撑大);
19
+ * ⑤ 静默降级:公共方法全部 try/catch 包死——审计失败绝不冒泡进记忆路径
20
+ * (审计是增益,记忆写入必须照常)。
21
+ *
22
+ * 为什么落盘采用**同步** fs:`session/event` 回调是同步的,异步落盘会引入
23
+ * 「多事件并发写同一文件」的乱序与竞态;状态文件只有几 KB,一次同步读(仅首次)
24
+ * 加一次全量重写的代价远小于它守护的诊断价值。
25
+ *
26
+ * 与 ctx.logger.info 的关系:hook 内三行 info 日志**保留不动**(in-memory 实时
27
+ * 视图),本审计是**盘面**视图(宿主 logger 不落盘时仍可复盘)。
28
+ *
29
+ * 边界(如实):
30
+ * · 状态是「进程内缓存 + 每次全量重写」,多进程同时写同一路径会互相覆盖
31
+ * (插件单实例部署下不构成问题;审计非关键路径,不做跨进程锁);
32
+ * · 审计文件损坏/手改致形态不符时按空态重建(数值归零、last 逐条过滤),
33
+ * 不抛错、不保留非法内容;
34
+ * · `written` 记的是「**成功发起**」的写入(fire-and-forget 的发起时刻),
35
+ * 发起后失败另记 `skipped.failed`——与 hooks.ts 的 memorize 两段式对应。
36
+ */
37
+ import { closeSync, mkdirSync, openSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from 'node:fs'
38
+ import { homedir } from 'node:os'
39
+ import { expandHome } from './datapath.js'
40
+ import { dirname, join } from 'node:path'
41
+
42
+ /** 三处过滤分支的成因(与 hooks.ts 一一对应:子代理会话 / 中继消息 / kind 非 user)。 */
43
+ export type HookFilterReason = 'subagent' | 'relay' | 'kind'
44
+ /** 写入路径的角色(与 md_cg 对 DSH 会话事件的 role 约定一致)。 */
45
+ export type HookWriteRole = 'user' | 'assistant' | 'tool'
46
+ /** 跳过写入的成因。 */
47
+ export type HookSkipReason = 'sanitized' | 'not_ready' | 'failed'
48
+
49
+ /** last 的一条摘要(**绝不含消息内容**——只有动作、成因、kind 与 role)。 */
50
+ export interface HookAuditEntry {
51
+ ts: string
52
+ action: 'filtered' | 'written' | 'skipped'
53
+ reason?: HookFilterReason | HookSkipReason
54
+ kind?: string
55
+ role?: HookWriteRole
56
+ }
57
+
58
+ /** 审计状态(= 状态文件的结构)。 */
59
+ export interface HookAuditState {
60
+ counts: {
61
+ /** 三处过滤分支的计数。 */
62
+ filtered: Record<HookFilterReason, number>
63
+ /** 成功发起的写入计数(按 role 分解)。 */
64
+ written: Record<HookWriteRole, number>
65
+ /** 跳过写入的计数(脱敏置空 / 认知图未就绪 / 写入失败)。 */
66
+ skipped: Record<HookSkipReason, number>
67
+ }
68
+ /** 进入消息级处理的 `source.kind` 分布(缺字段/空串/非字符串记 "undefined")。 */
69
+ kinds: Record<string, number>
70
+ /** 最近 ≤MAX_LAST 条摘要。 */
71
+ last: HookAuditEntry[]
72
+ updated_at: string
73
+ }
74
+
75
+ /** 缺省审计文件:与桥探针 / apply 探针同目录同惯例(README.md:110)。 */
76
+ /**
77
+ * 审计根:优先 `DSH_HOME`(隔离/多 home 安装必须显式给),否则 `~/.dsh`。
78
+ * issue #554 §7:此前恒用 homedir,隔离 home 下审计写到生产 home,与 brain 分离。
79
+ * 兼容 `~` 与 `~/x` 形态;其余按字面路径处理(不做 shell 展开)。
80
+ */
81
+ function defaultHookAuditPath(): string {
82
+ const raw = (process.env.DSH_HOME ?? '').trim()
83
+ // 唯一实现:路径展开复用 datapath.expandHome(禁止第二处判据,见 test/datapath-expandhome)。
84
+ const root = raw ? expandHome(raw) : join(homedir(), '.dsh')
85
+ return join(root, 'logs', 'dsh-memory-hook-audit.json')
86
+ }
87
+
88
+ export const DEFAULT_HOOK_AUDIT_PATH = defaultHookAuditPath()
89
+
90
+ /** last 条数上限(有界性单点——没有它 audit 文件会随会话无限增长)。 */
91
+ const MAX_LAST = 20
92
+ /** kinds 键数上限(超限归并到 OTHER_KIND,防宿主 kind 值域异常撑大文件)。 */
93
+ const MAX_KINDS = 32
94
+ /** kinds 归并桶。 */
95
+ const OTHER_KIND = 'other'
96
+
97
+ const FILTER_REASONS: HookFilterReason[] = ['subagent', 'relay', 'kind']
98
+ const WRITE_ROLES: HookWriteRole[] = ['user', 'assistant', 'tool']
99
+ const SKIP_REASONS: HookSkipReason[] = ['sanitized', 'not_ready', 'failed']
100
+
101
+ /** `source.kind` 的规范化取值:非字符串(含缺字段)或空串一律记 "undefined"
102
+ * (不可辨认即无值——空串与缺字段在排障上同义)。 */
103
+ export function kindOf(source: unknown): string {
104
+ const k = (source as { kind?: unknown } | null | undefined)?.kind
105
+ return typeof k === 'string' && k.length > 0 ? k : 'undefined'
106
+ }
107
+
108
+ function nowIso(): string {
109
+ return new Date().toISOString()
110
+ }
111
+
112
+ function emptyState(): HookAuditState {
113
+ return {
114
+ counts: {
115
+ filtered: { subagent: 0, relay: 0, kind: 0 },
116
+ written: { user: 0, assistant: 0, tool: 0 },
117
+ skipped: { sanitized: 0, not_ready: 0, failed: 0 },
118
+ },
119
+ kinds: {},
120
+ last: [],
121
+ updated_at: nowIso(),
122
+ }
123
+ }
124
+
125
+ /** 计数位:只认有限非负整数,其余归零(防手改/坏文件把计数变成 NaN)。 */
126
+ function countOf(v: unknown): number {
127
+ return typeof v === 'number' && Number.isFinite(v) && v >= 0 ? Math.floor(v) : 0
128
+ }
129
+
130
+ /** 盘面内容 → 状态:逐字段归并,形态不符的字段一律丢弃(不信任盘面内容)。 */
131
+ function mergeState(raw: unknown): HookAuditState {
132
+ const s = emptyState()
133
+ if (!raw || typeof raw !== 'object') return s
134
+ const r = raw as { counts?: unknown; kinds?: unknown; last?: unknown }
135
+ if (r.counts && typeof r.counts === 'object') {
136
+ const c = r.counts as { filtered?: unknown; written?: unknown; skipped?: unknown }
137
+ const buckets: Array<[Record<string, number>, string[], unknown]> = [
138
+ [s.counts.filtered as Record<string, number>, FILTER_REASONS, c.filtered],
139
+ [s.counts.written as Record<string, number>, WRITE_ROLES, c.written],
140
+ [s.counts.skipped as Record<string, number>, SKIP_REASONS, c.skipped],
141
+ ]
142
+ for (const [dst, keys, src] of buckets) {
143
+ if (!src || typeof src !== 'object') continue
144
+ for (const key of keys) dst[key] = countOf((src as Record<string, unknown>)[key])
145
+ }
146
+ }
147
+ if (r.kinds && typeof r.kinds === 'object') {
148
+ for (const [k, v] of Object.entries(r.kinds as Record<string, unknown>)) {
149
+ if (typeof v === 'number' && Number.isFinite(v) && v > 0) s.kinds[k] = Math.floor(v)
150
+ }
151
+ }
152
+ if (Array.isArray(r.last)) {
153
+ for (const e of r.last) {
154
+ if (!e || typeof e !== 'object') continue
155
+ const entry = e as Partial<HookAuditEntry>
156
+ if (typeof entry.ts !== 'string') continue
157
+ if (entry.action !== 'filtered' && entry.action !== 'written' && entry.action !== 'skipped') continue
158
+ s.last.push(entry as HookAuditEntry)
159
+ }
160
+ if (s.last.length > MAX_LAST) s.last = s.last.slice(-MAX_LAST)
161
+ }
162
+ return s
163
+ }
164
+
165
+ /**
166
+ * 有界落盘审计记录器(**静默降级**:任何公共方法都不会抛错)。
167
+ *
168
+ * 用法(hooks.ts 内):`new HookAuditRecorder(opts.auditPath)`,随后在
169
+ * 三处过滤分支与写入/跳过路径各调一次对应方法。审计失败只影响审计自身。
170
+ */
171
+ export class HookAuditRecorder {
172
+ /** 实际生效的审计文件路径(构造时定死,供日志/测试核对)。 */
173
+ readonly path: string
174
+ /** 进程内状态缓存(首次记录时从盘面载入,此后只增量改内存 + 全量重写)。 */
175
+ #state: HookAuditState | null = null
176
+
177
+ constructor(path?: string) {
178
+ this.path = typeof path === 'string' && path.trim() ? path.trim() : DEFAULT_HOOK_AUDIT_PATH
179
+ }
180
+
181
+ /** 一条**被设计滤除**的消息(三处过滤分支各调一次)。 */
182
+ filtered(reason: HookFilterReason, kind?: string): void {
183
+ this.#mutate((s) => {
184
+ s.counts.filtered[reason] += 1
185
+ s.last.push(kind === undefined
186
+ ? { ts: nowIso(), action: 'filtered', reason }
187
+ : { ts: nowIso(), action: 'filtered', reason, kind })
188
+ })
189
+ }
190
+
191
+ /** `source.kind` 分布(每条**进入消息级处理**的事件调一次,含被滤与放行)。 */
192
+ observeKind(kind: string): void {
193
+ this.#mutate((s) => {
194
+ const key = this.#boundedKindKey(s, kind)
195
+ s.kinds[key] = (s.kinds[key] ?? 0) + 1
196
+ })
197
+ }
198
+
199
+ /** 成功**发起**的写入(按 role;发起后失败另记 skipped.failed)。 */
200
+ written(role: HookWriteRole): void {
201
+ this.#mutate((s) => {
202
+ s.counts.written[role] += 1
203
+ s.last.push({ ts: nowIso(), action: 'written', role })
204
+ })
205
+ }
206
+
207
+ /** 跳过写入(脱敏置空 / 认知图未就绪 / 写入失败)。 */
208
+ skipped(reason: HookSkipReason, role?: HookWriteRole): void {
209
+ this.#mutate((s) => {
210
+ s.counts.skipped[reason] += 1
211
+ s.last.push(role === undefined
212
+ ? { ts: nowIso(), action: 'skipped', reason }
213
+ : { ts: nowIso(), action: 'skipped', reason, role })
214
+ })
215
+ }
216
+
217
+ /** 键数有界:已见键原样用;新键在未达上限时收录,达限后统一归并到 "other"。 */
218
+ #boundedKindKey(s: HookAuditState, kind: string): string {
219
+ if (Object.prototype.hasOwnProperty.call(s.kinds, kind)) return kind
220
+ return Object.keys(s.kinds).length >= MAX_KINDS ? OTHER_KIND : kind
221
+ }
222
+
223
+ /** 读改写 + 原子落盘;整段 try/catch——审计失败静默降级(绝不冒泡进记忆路径)。 */
224
+ #mutate(fn: (s: HookAuditState) => void): void {
225
+ // #563④:审计文件被同用户的多个 DSH 进程共用;此前 #state 只在首次载入、写回整份 rename 覆盖
226
+ // ⇒ 并发时后写者用内存态盖掉他人计数(实测 400→201 / 400→311)。现改为锁内 重读→改→写。
227
+ if (!this.#acquireLock()) return
228
+ try {
229
+ const s = this.#load()
230
+ fn(s)
231
+ if (s.last.length > MAX_LAST) s.last = s.last.slice(-MAX_LAST)
232
+ s.updated_at = nowIso()
233
+ this.#save(s)
234
+ this.#state = s
235
+ } catch { /* 审计失败静默降级:记忆路径必须照常 */ }
236
+ finally { this.#releaseLock() }
237
+ }
238
+
239
+ /** 跨进程排他锁:独占创建 `${path}.lock`;陈旧锁(>5s)清掉;超时返回 false(静默降级)。 */
240
+ #acquireLock(timeoutMs = 800): boolean {
241
+ const lock = `${this.path}.lock`
242
+ const t0 = Date.now()
243
+ for (;;) {
244
+ try {
245
+ closeSync(openSync(lock, 'wx'))
246
+ return true
247
+ } catch {
248
+ try { if (Date.now() - statSync(lock).mtimeMs > 5000) unlinkSync(lock) } catch { /* 已释放 */ }
249
+ if (Date.now() - t0 > timeoutMs) return false
250
+ const until = Date.now() + 5
251
+ while (Date.now() < until) { /* 自旋 5ms */ }
252
+ }
253
+ }
254
+ }
255
+
256
+ #releaseLock(): void {
257
+ try { unlinkSync(`${this.path}.lock`) } catch { /* 已清理 */ }
258
+ }
259
+
260
+ /** 盘面 → 状态;不存在/不可读/坏 JSON/形态不符 → 空态重建(不抛)。 */
261
+ #load(): HookAuditState {
262
+ try {
263
+ return mergeState(JSON.parse(readFileSync(this.path, 'utf8')) as unknown)
264
+ } catch {
265
+ return emptyState()
266
+ }
267
+ }
268
+
269
+ /** 原子写:同目录临时文件 + rename(临时文件在 rename 失败时清理)。 */
270
+ #save(s: HookAuditState): void {
271
+ const dir = dirname(this.path)
272
+ mkdirSync(dir, { recursive: true })
273
+ const tmp = `${this.path}.${process.pid.toString(36)}.${Date.now().toString(36)}.tmp`
274
+ writeFileSync(tmp, `${JSON.stringify(s, null, 2)}\n`, 'utf8')
275
+ try {
276
+ renameSync(tmp, this.path)
277
+ } catch (err) {
278
+ try { unlinkSync(tmp) } catch { /* 清理失败忽略:残留 .tmp 不影响读路径 */ }
279
+ throw err
280
+ }
281
+ }
282
+ }