@jjh32456/dsh-longlive 1.6.7 → 1.8.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 (289) hide show
  1. package/CHANGELOG.md +70 -1508
  2. package/LICENSE +1 -1
  3. package/QUICKSTART.md +34 -13
  4. package/README.en.md +18 -7
  5. package/README.md +34 -9
  6. package/SPEC.md +5 -5
  7. package/cordis.patch.yml +23 -9
  8. package/docs/ANSWER-GUARD.md +92 -0
  9. package/docs/ARCHITECTURE.md +4 -3
  10. package/docs/AUTO-RECALL-WIRING.md +1 -1
  11. package/docs/AUTO-RECALL.md +15 -9
  12. package/docs/CONFIG.md +168 -35
  13. package/docs/ERRORS.md +17 -5
  14. package/docs/FAQ.md +7 -7
  15. package/docs/FEATURES.md +96 -28
  16. package/docs/MIGRATION-1.6.0.md +2 -2
  17. package/docs/OPERATIONS.md +6 -6
  18. package/docs/PANEL-INTEGRATION.md +6 -0
  19. package/docs/PRIVACY.md +88 -0
  20. package/docs/QUICKSTART.md +5 -5
  21. package/docs/README.en.md +4 -2
  22. package/docs/RESIDENT-WATCHER.md +1 -1
  23. package/docs/SESSION-WATCH.md +6 -6
  24. package/docs/TROUBLESHOOTING.md +4 -4
  25. package/package.json +47 -117
  26. package/runbook.md +2 -2
  27. package/scripts/backfill-auto-cards.mjs +98 -0
  28. package/scripts/install-surgery-task.ps1 +5 -2
  29. package/scripts/lib/session-watch-fixture.mjs +1 -1
  30. package/scripts/longlive-doctor.mjs +6 -0
  31. package/scripts/migrate-180.mjs +163 -0
  32. package/scripts/recall-index-build.mjs +128 -0
  33. package/scripts/session-watch-drill.mjs +1 -1
  34. package/scripts/surgery-run.cmd +1 -1
  35. package/scripts/unattended-surgery.ps1 +5 -2
  36. package/scripts/verify-card-anchors.mjs +138 -0
  37. package/src/actions/audit.js +125 -0
  38. package/src/actions/evidence.js +122 -0
  39. package/src/actions/fs.js +162 -0
  40. package/src/activity/index.js +760 -0
  41. package/src/activity/model.js +351 -0
  42. package/src/activity/store.js +644 -0
  43. package/src/activity/thinking.js +176 -0
  44. package/src/adapters/constants.js +11 -0
  45. package/src/adapters/engram/data/aliases.json +51 -0
  46. package/src/adapters/engram/data/policy.json +8 -0
  47. package/src/adapters/engram/data/routing-rules.json +546 -0
  48. package/src/adapters/engram/index.js +235 -0
  49. package/src/adapters/registry.js +315 -0
  50. package/src/answer/audit.js +193 -0
  51. package/src/answer/evidence.js +30 -0
  52. package/src/answer/guard.js +1370 -0
  53. package/src/answer/index.js +1067 -0
  54. package/src/answer/query.js +111 -0
  55. package/src/answer/second-hop.mjs +101 -0
  56. package/src/auto-truncate.js +1 -1
  57. package/src/config.js +171 -47
  58. package/src/deps.js +6 -4
  59. package/src/features.js +182 -6
  60. package/src/heartbeat.js +156 -23
  61. package/src/identity/handover.js +52 -1
  62. package/src/identity/index.js +13 -5
  63. package/src/identity/inject-position.js +2 -2
  64. package/src/index.js +97 -7
  65. package/src/lifecycle/gap-clocks.js +328 -0
  66. package/src/lifecycle/index.js +269 -0
  67. package/src/live.js +22 -2
  68. package/src/memory/activity-capture.js +229 -0
  69. package/src/memory/anchors.js +194 -0
  70. package/src/memory/audit-records.js +222 -0
  71. package/src/memory/auto-cards.js +401 -0
  72. package/src/memory/capture.js +442 -0
  73. package/src/memory/card-anchors.js +203 -0
  74. package/src/memory/conflicts.js +106 -0
  75. package/src/memory/decay.js +311 -0
  76. package/src/memory/distill.js +471 -0
  77. package/src/memory/event-index.js +917 -0
  78. package/src/memory/evidence-chain.js +295 -0
  79. package/src/memory/evidence.js +145 -0
  80. package/src/memory/filter-runner.js +1 -1
  81. package/src/memory/filter.js +5 -1
  82. package/src/memory/forget-v2.js +410 -0
  83. package/src/memory/forget.js +71 -0
  84. package/src/memory/frames-activation.js +247 -0
  85. package/src/memory/fts-query.js +174 -0
  86. package/src/memory/governance.js +604 -0
  87. package/src/memory/index.js +1 -0
  88. package/src/memory/l2-gate.js +169 -0
  89. package/src/memory/lock.js +121 -0
  90. package/src/memory/migrate.js +139 -0
  91. package/src/memory/recall-v2.js +223 -0
  92. package/src/memory/recall.js +65 -2
  93. package/src/memory/records.js +425 -0
  94. package/src/memory/retention.js +128 -0
  95. package/src/memory/review.js +124 -0
  96. package/src/memory/trust.js +88 -0
  97. package/src/memory/version-chain.js +264 -0
  98. package/src/memory/wal.js +137 -0
  99. package/src/memory/working-frame.js +516 -0
  100. package/src/metrics/classify.mjs +5 -3
  101. package/src/metrics/index.mjs +21 -1
  102. package/src/metrics/prestep-latency.mjs +300 -0
  103. package/src/metrics/store.mjs +25 -0
  104. package/src/policy-profile.js +18 -3
  105. package/src/recall/anaphora.mjs +87 -0
  106. package/src/recall/cards.mjs +7 -0
  107. package/src/recall/embedding.mjs +8 -8
  108. package/src/recall/entities.mjs +112 -0
  109. package/src/recall/index.js +235 -19
  110. package/src/recall/inject-order.mjs +10 -8
  111. package/src/recall/privacy.mjs +105 -16
  112. package/src/recall/recall-core.mjs +116 -10
  113. package/src/recall/shared-visibility.js +302 -0
  114. package/src/recall/time-normalizer.mjs +196 -0
  115. package/src/role/activation.js +191 -0
  116. package/src/role/attention.js +318 -0
  117. package/src/role/base.js +36 -0
  118. package/src/role/channels.js +423 -0
  119. package/src/role/index.js +425 -0
  120. package/src/role/interfaces.js +115 -0
  121. package/src/role/personality.js +370 -0
  122. package/src/role/readers.js +151 -0
  123. package/src/role/relationships.js +477 -0
  124. package/src/role/store.js +202 -0
  125. package/src/role/writeprotect.js +373 -0
  126. package/src/router/aliases.json +176 -25
  127. package/src/router/background/agent-runner.mjs +1 -1
  128. package/src/router/background/anchor.mjs +1 -1
  129. package/src/router/background/audit.mjs +2 -2
  130. package/src/router/background/budget-ledger.mjs +2 -2
  131. package/src/router/background/host-sim.mjs +1 -1
  132. package/src/router/background/memory.mjs +4 -4
  133. package/src/router/background/queue.mjs +1 -1
  134. package/src/router/background/retry.mjs +1 -1
  135. package/src/router/background/router.mjs +1 -1
  136. package/src/router/background/stream.mjs +1 -1
  137. package/src/router/background/tool-policy.mjs +1 -1
  138. package/src/router/design-headings.json +5 -5
  139. package/src/router/face/config.mjs +1 -1
  140. package/src/router/face/identity.mjs +3 -3
  141. package/src/router/judge.mjs +8 -7
  142. package/src/router/policies/generic.json +21 -4
  143. package/src/router/route.js +109 -22
  144. package/src/router/router.mjs +10 -6
  145. package/src/router/routing-rules.json +260 -445
  146. package/src/router/run-sim.mjs +8 -8
  147. package/src/router/runtime.js +23 -12
  148. package/src/router/service/board.mjs +95 -15
  149. package/src/router/service/config.mjs +5 -5
  150. package/src/router/service/context.mjs +1 -1
  151. package/src/router/service/hint.mjs +14 -0
  152. package/src/router/service/queue.mjs +1 -1
  153. package/src/router/service/service.mjs +27 -11
  154. package/src/router/shadow.mjs +4 -3
  155. package/src/surgery-recovery.js +2 -2
  156. package/src/tool-output.js +2 -2
  157. package/src/tools.js +39 -7
  158. package/src/truncate-visible.js +2 -2
  159. package/src/ui/actions.js +1312 -0
  160. package/src/ui/panel-api.js +367 -0
  161. package/src/ui/panel-auth.js +251 -0
  162. package/src/ui/panel-integrity.js +243 -0
  163. package/src/ui/routes-readonly.js +695 -0
  164. package/src/ui/routes.js +3 -0
  165. package/docs/DEV.md +0 -279
  166. package/docs/PRESENCE-BUS-WIRING.md +0 -491
  167. package/docs/PRESENCE-BUS.md +0 -694
  168. package/docs/SURGERY.md +0 -186
  169. package/scripts/mark-core-cards.mjs +0 -289
  170. package/scripts/pack.mjs +0 -392
  171. package/scripts/router-proposals.mjs +0 -386
  172. package/src/router/fixtures/M1.json +0 -16
  173. package/src/router/fixtures/M2.json +0 -16
  174. package/src/router/fixtures/M3.json +0 -20
  175. package/src/router/fixtures/M4.json +0 -20
  176. package/src/router/fixtures/M5.json +0 -45
  177. package/src/router/fixtures/M6.json +0 -53
  178. package/src/router/fixtures/M7.json +0 -46
  179. package/src/router/fixtures/S1.json +0 -20
  180. package/src/router/fixtures/S2.json +0 -23
  181. package/src/router/fixtures/S3.json +0 -20
  182. package/src/router/fixtures/S4.json +0 -34
  183. package/src/router/fixtures/S5.json +0 -43
  184. package/src/router/fixtures/S6.json +0 -47
  185. package/src/router/fixtures/T1.json +0 -23
  186. package/src/router/fixtures/T2.json +0 -16
  187. package/src/router/fixtures/T3.json +0 -19
  188. package/src/router/fixtures/T4.json +0 -16
  189. package/src/router/fixtures/X1.json +0 -17
  190. package/src/router/fixtures/X2.json +0 -20
  191. package/src/router/gen-design-headings.mjs +0 -107
  192. package/src/router/policies/owner-rulings-2026-11-03.json +0 -62
  193. package/test/auto-recall.test.mjs +0 -474
  194. package/test/auto-truncate.test.mjs +0 -931
  195. package/test/autobind.test.mjs +0 -385
  196. package/test/bus.test.mjs +0 -1572
  197. package/test/cli-guard.test.mjs +0 -198
  198. package/test/conclusion.test.mjs +0 -408
  199. package/test/config-schema.test.mjs +0 -204
  200. package/test/d6-output.test.mjs +0 -194
  201. package/test/d6.test.mjs +0 -395
  202. package/test/deps.test.mjs +0 -342
  203. package/test/doctor-setup.test.mjs +0 -297
  204. package/test/embedding-recall.test.mjs +0 -347
  205. package/test/feature-flags.test.mjs +0 -568
  206. package/test/filter-shadow.test.mjs +0 -170
  207. package/test/fixtures/baseline-0.8.0-registration.json +0 -556
  208. package/test/fixtures/d6-header-tools.json +0 -1
  209. package/test/fixtures/lock-child.mjs +0 -67
  210. package/test/fixtures/pre-step-container.mjs +0 -100
  211. package/test/fixtures/privacy-memory/topics/pii-unmarked.md +0 -9
  212. package/test/fixtures/privacy-memory/topics/secret-local-only.md +0 -11
  213. package/test/fixtures/profile-session-longlive-config.json +0 -20
  214. package/test/fixtures/proposal-cas-child.mjs +0 -66
  215. package/test/host-engine-status.test.mjs +0 -307
  216. package/test/hot-truncate.test.mjs +0 -1349
  217. package/test/identity-card-marker.test.mjs +0 -307
  218. package/test/identity-router/run.mjs +0 -721
  219. package/test/integration-pre-step.test.mjs +0 -553
  220. package/test/live.test.mjs +0 -1020
  221. package/test/maintenance-schedule.test.mjs +0 -538
  222. package/test/memory.test.mjs +0 -2828
  223. package/test/metrics.test.mjs +0 -478
  224. package/test/orchestrator.test.mjs +0 -266
  225. package/test/p1_probe.mjs +0 -97
  226. package/test/packaging.test.mjs +0 -182
  227. package/test/portability.test.mjs +0 -343
  228. package/test/rc4-regressions.test.mjs +0 -562
  229. package/test/rc5-regressions.test.mjs +0 -197
  230. package/test/rc6-chinese.test.mjs +0 -394
  231. package/test/router-1100/apply-off.test.mjs +0 -175
  232. package/test/router-1100/budget-reconcile.test.mjs +0 -215
  233. package/test/router-1100/config-context.test.mjs +0 -211
  234. package/test/router-1100/helpers.mjs +0 -129
  235. package/test/router-1100/hint-envelope.test.mjs +0 -150
  236. package/test/router-1100/lock-crossproc.test.mjs +0 -206
  237. package/test/router-1100/proposal-cas-crossproc.test.mjs +0 -184
  238. package/test/router-1100/router-apply.test.mjs +0 -372
  239. package/test/router-1100/router-fixb.test.mjs +0 -602
  240. package/test/router-1100/router-proposals.test.mjs +0 -405
  241. package/test/router-1100/router-queue-lease-wal.test.mjs +0 -355
  242. package/test/router-1100/router-security-cr.test.mjs +0 -333
  243. package/test/router-1100/service-lifecycle.test.mjs +0 -220
  244. package/test/router-1100/tools-contract.test.mjs +0 -164
  245. package/test/router-1100/turn-reflect-tick.test.mjs +0 -89
  246. package/test/router-1100/v6-contract.test.mjs +0 -158
  247. package/test/router-1100/v6b-contract.test.mjs +0 -293
  248. package/test/router-1100/v6c-contract.test.mjs +0 -249
  249. package/test/router-1100/wal-rotation.test.mjs +0 -375
  250. package/test/router-1100/wp1-config.test.mjs +0 -170
  251. package/test/router-1100/wp1-default-off.test.mjs +0 -77
  252. package/test/router-1100/wp1-model-status.test.mjs +0 -90
  253. package/test/router-1100/wp1-status.test.mjs +0 -220
  254. package/test/router-1100/wp1-tools.test.mjs +0 -146
  255. package/test/router-1100/wp5-cli.test.mjs +0 -240
  256. package/test/router-1100/wp5-model-auto.test.mjs +0 -418
  257. package/test/router-1100/wp6-merge.test.mjs +0 -386
  258. package/test/router-1100/wp6-wake.test.mjs +0 -502
  259. package/test/router-background/audit.test.mjs +0 -37
  260. package/test/router-background/budget-ledger.test.mjs +0 -330
  261. package/test/router-background/cross-process.test.mjs +0 -222
  262. package/test/router-background/fixtures/cross-child.mjs +0 -85
  263. package/test/router-background/fixtures/real-shapes.mjs +0 -239
  264. package/test/router-background/router.test.mjs +0 -1044
  265. package/test/router-background/stream-retry.test.mjs +0 -358
  266. package/test/router-background/tool-agent.test.mjs +0 -384
  267. package/test/router-face/bridge.test.mjs +0 -169
  268. package/test/router-face/face.test.mjs +0 -316
  269. package/test/router-failclosed.test.mjs +0 -466
  270. package/test/router-identity.test.mjs +0 -384
  271. package/test/router-l1-l2.contract.test.mjs +0 -1075
  272. package/test/router-memory-tools.test.mjs +0 -262
  273. package/test/router-policy.test.mjs +0 -225
  274. package/test/router-runtime.test.mjs +0 -438
  275. package/test/router-shadow.test.mjs +0 -287
  276. package/test/router.test.mjs +0 -903
  277. package/test/run-rc.mjs +0 -299
  278. package/test/run.mjs +0 -2469
  279. package/test/safety-defaults.test.mjs +0 -179
  280. package/test/seeded-load.test.mjs +0 -436
  281. package/test/session-original.test.mjs +0 -338
  282. package/test/surgery-recovery.test.mjs +0 -936
  283. package/test/t7_drive.mjs +0 -151
  284. package/test/tool-output.test.mjs +0 -393
  285. package/test/tool-schema.test.mjs +0 -177
  286. package/test/tools_contract.test.mjs +0 -716
  287. package/test/truncate-visible.test.mjs +0 -1150
  288. package/test/ui-flags.test.mjs +0 -477
  289. package/test/v4-hardening.test.mjs +0 -427
@@ -0,0 +1,370 @@
1
+ // src/role/personality.js — 角色内核 · personality projection(v2.8 §16.3 ④)
2
+ //
3
+ // 设计口径(§16.3):
4
+ // - `.longlive/role/personality.json` 快照
5
+ // `{snapshotId, version, retentionBias{kind:weight}, tone, createdAt}`;
6
+ // - 接口:`retentionBias → 遗忘阈值`(只影响衰减偏好,**不越权 protected/forbid**);
7
+ // - 1.8.0 只做快照生成与只读,不改写遗忘算法本体(所以这里只导出一个
8
+ // `applyRetentionBiasToRules()` 纯函数,forget.js 是否采用由调用方决定)。
9
+ //
10
+ // 快照来源(本地规则,不调模型):
11
+ // - 文件源:`role.personality.profilePaths`(默认 ['profile.md','AGENTS.md'],必须在
12
+ // memoryRoot 内;越界/缺失只记录 skipped,不崩);
13
+ // - 文本源:调用方直接用 `sources:[{kind:'text',name,text}]` 传入(例如宿主 profile 文案);
14
+ // - 偏好源:`preferences` 参数(键值对)可显式提高某类记忆的 retentionBias。
15
+ // 每个源都进 versions 审计(name/sha256/chars),快照版本单调递增。
16
+
17
+ import path from 'node:path';
18
+
19
+ import {
20
+ RoleError, ROLE_CODES, appendJsonl, ensureRoleDir, iso, nowMs, readInsideRoot, readJsonSafe, readJsonlSafe, rolePaths, tryRolePaths, sha256Hex, writeJsonAtomic,
21
+ } from './store.js';
22
+
23
+ export const PERSONALITY_SCHEMA = 'personality/v1';
24
+ export const RETENTION_KINDS = Object.freeze(['fact', 'preference', 'decision', 'episode', 'skill']);
25
+ export const PERSONALITY_TONES = Object.freeze(['neutral', 'warm', 'honest-direct', 'concise']);
26
+ export const PERSONALITY_DEFAULTS = Object.freeze({
27
+ tone: 'neutral',
28
+ retentionBias: Object.freeze({ fact: 1.0, preference: 1.0, decision: 1.0, episode: 1.0, skill: 1.0 }),
29
+ profilePaths: Object.freeze(['profile.md', 'AGENTS.md']),
30
+ biasMin: 0.8,
31
+ biasMax: 1.5,
32
+ biasPerHit: 0.1,
33
+ });
34
+ export const PERSONALITY_CODES = Object.freeze({
35
+ PARAMS: ROLE_CODES.PARAMS,
36
+ CORRUPT: ROLE_CODES.CORRUPT,
37
+ PROFILE_OUTSIDE: ROLE_CODES.PATH_OUTSIDE_ROOT,
38
+ });
39
+
40
+ /** tone 本地规则(命中次数最多的 tone 胜出;同分按 TONE_RULES 顺序)。 */
41
+ export const TONE_RULES = Object.freeze([
42
+ { tone: 'warm', keywords: ['人情味', '话可以长', '陪我', '聊天', '情绪', '不用端着', '伙伴'] },
43
+ { tone: 'honest-direct', keywords: ['不哄', '不许骗', '不骗', '直接', '说人话', '不端着'] },
44
+ { tone: 'concise', keywords: ['短一点', '精简', '别啰嗦', '一句话'] },
45
+ ]);
46
+
47
+ /** retentionBias 关键词规则:命中次数越多,该类记忆的衰减阈值保留得越久。 */
48
+ export const RETENTION_RULES = Object.freeze({
49
+ fact: ['事实', '数据', '来源', '出处', '证据'],
50
+ preference: ['偏好', '喜欢', '不喜欢', '习惯', '口味'],
51
+ decision: ['决定', '决策', '拍板', '规则', '铁律', '定下'],
52
+ episode: ['经历', '日记', 'journal', '发生过', '那晚', '当时'],
53
+ skill: ['方法', '流程', '步骤', 'skill', '技法', '怎么做'],
54
+ });
55
+
56
+ function clampBias(value) {
57
+ const number = Number(value);
58
+ if (!Number.isFinite(number)) return 1.0;
59
+ return Math.min(PERSONALITY_DEFAULTS.biasMax, Math.max(PERSONALITY_DEFAULTS.biasMin, Math.round(number * 100) / 100));
60
+ }
61
+
62
+ function emptySnapshot() {
63
+ return {
64
+ snapshotId: null,
65
+ version: 0,
66
+ retentionBias: { ...PERSONALITY_DEFAULTS.retentionBias },
67
+ tone: PERSONALITY_DEFAULTS.tone,
68
+ createdAt: null,
69
+ sources: [],
70
+ };
71
+ }
72
+
73
+ function normalizeSnapshot(raw) {
74
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
75
+ const bias = {};
76
+ const rawBias = raw.retentionBias && typeof raw.retentionBias === 'object' ? raw.retentionBias : {};
77
+ for (const kind of RETENTION_KINDS) bias[kind] = clampBias(rawBias[kind] ?? 1.0);
78
+ return {
79
+ snapshotId: typeof raw.snapshotId === 'string' ? raw.snapshotId : null,
80
+ version: Number.isInteger(raw.version) && raw.version >= 0 ? raw.version : 0,
81
+ retentionBias: bias,
82
+ tone: PERSONALITY_TONES.includes(raw.tone) ? raw.tone : PERSONALITY_DEFAULTS.tone,
83
+ createdAt: typeof raw.createdAt === 'string' && Number.isFinite(Date.parse(raw.createdAt)) ? raw.createdAt : null,
84
+ sources: Array.isArray(raw.sources)
85
+ ? raw.sources.filter((item) => item && typeof item === 'object').map((item) => ({
86
+ name: typeof item.name === 'string' ? item.name : 'source',
87
+ kind: typeof item.kind === 'string' ? item.kind : 'file',
88
+ sha256: typeof item.sha256 === 'string' ? item.sha256 : null,
89
+ chars: Number.isInteger(item.chars) ? item.chars : null,
90
+ skipped: item.skipped === true ? true : undefined,
91
+ code: typeof item.code === 'string' ? item.code : undefined,
92
+ }))
93
+ : [],
94
+ };
95
+ }
96
+
97
+ /** Read-only personality view (`personality/v1`); never throws. */
98
+ export function readPersonality({ memoryRoot, now = () => new Date(), caller = null, auditKey = null } = {}) {
99
+ const paths = tryRolePaths(memoryRoot);
100
+ if (paths === null) {
101
+ return {
102
+ schema: PERSONALITY_SCHEMA,
103
+ present: false,
104
+ degraded: true,
105
+ snapshot: null,
106
+ defaults: { ...emptySnapshot() },
107
+ code: 'E_PERSONALITY_ABSENT',
108
+ readAt: iso(nowMs(now())),
109
+ };
110
+ }
111
+ const read = readJsonSafe(paths.personality, { memoryRoot, auditKey, caller });
112
+ if (read.tampered === true || read.denied === true) {
113
+ return {
114
+ schema: PERSONALITY_SCHEMA,
115
+ present: false,
116
+ degraded: true,
117
+ tampered: read.tampered === true,
118
+ denied: read.denied === true,
119
+ subject: read.subject ?? null,
120
+ snapshot: null,
121
+ defaults: { ...emptySnapshot() },
122
+ code: read.code,
123
+ message: read.message ?? null,
124
+ readAt: iso(nowMs(now())),
125
+ };
126
+ }
127
+ if (!read.ok || !read.value || typeof read.value !== 'object') {
128
+ return {
129
+ schema: PERSONALITY_SCHEMA,
130
+ present: read.present === true,
131
+ degraded: read.present === true,
132
+ snapshot: null,
133
+ defaults: { ...emptySnapshot() },
134
+ code: read.present === true ? 'E_PERSONALITY_CORRUPT' : 'E_PERSONALITY_ABSENT',
135
+ readAt: iso(nowMs(now())),
136
+ };
137
+ }
138
+ const snapshot = normalizeSnapshot(read.value);
139
+ if (snapshot === null) {
140
+ return {
141
+ schema: PERSONALITY_SCHEMA,
142
+ present: true,
143
+ degraded: true,
144
+ snapshot: null,
145
+ defaults: { ...emptySnapshot() },
146
+ code: 'E_PERSONALITY_INVALID',
147
+ readAt: iso(nowMs(now())),
148
+ };
149
+ }
150
+ return {
151
+ schema: PERSONALITY_SCHEMA,
152
+ present: true,
153
+ degraded: false,
154
+ snapshot,
155
+ defaults: { ...emptySnapshot() },
156
+ code: 'OK',
157
+ readAt: iso(nowMs(now())),
158
+ };
159
+ }
160
+
161
+ /** Derive tone by keyword hits; unknown/empty text → neutral. */
162
+ export function extractTone(text) {
163
+ const haystack = String(text ?? '').toLowerCase();
164
+ if (haystack.trim() === '') return PERSONALITY_DEFAULTS.tone;
165
+ let bestTone = PERSONALITY_DEFAULTS.tone;
166
+ let bestHits = 0;
167
+ for (const rule of TONE_RULES) {
168
+ let hits = 0;
169
+ for (const keyword of rule.keywords) if (haystack.includes(keyword.toLowerCase())) hits += 1;
170
+ if (hits > bestHits) {
171
+ bestTone = rule.tone;
172
+ bestHits = hits;
173
+ }
174
+ }
175
+ return bestTone;
176
+ }
177
+
178
+ /** Derive retentionBias: keyword hits raise the kind's weight (bounded). */
179
+ export function extractRetentionBias(texts) {
180
+ const haystack = (Array.isArray(texts) ? texts : [texts]).map((item) => String(item ?? '')).join('\n').toLowerCase();
181
+ const bias = {};
182
+ for (const kind of RETENTION_KINDS) {
183
+ const keywords = RETENTION_RULES[kind] ?? [];
184
+ let hits = 0;
185
+ for (const keyword of keywords) if (haystack.includes(keyword.toLowerCase())) hits += 1;
186
+ bias[kind] = hits === 0 ? 1.0 : clampBias(1.0 + hits * PERSONALITY_DEFAULTS.biasPerHit);
187
+ }
188
+ return bias;
189
+ }
190
+
191
+ function nextAuditSeq(paths, options = {}) {
192
+ const read = readJsonlSafe(paths.audit, { limit: 10_000, memoryRoot: options.memoryRoot, auditKey: options.auditKey ?? null });
193
+ let max = 0;
194
+ for (let index = read.rows.length - 1; index >= 0; index -= 1) {
195
+ const seq = read.rows[index]?.seq;
196
+ if (Number.isInteger(seq) && seq > max) max = seq;
197
+ }
198
+ return max + 1;
199
+ }
200
+
201
+ function collectSources({ memoryRoot, sources = [], profilePaths = PERSONALITY_DEFAULTS.profilePaths } = {}) {
202
+ const collected = [];
203
+ const skipped = [];
204
+ const pushText = (name, kind, text) => {
205
+ const normalized = typeof text === 'string' ? text : '';
206
+ collected.push({
207
+ name,
208
+ kind,
209
+ text: normalized,
210
+ sha256: sha256Hex(normalized),
211
+ chars: Array.from(normalized).length,
212
+ });
213
+ };
214
+ for (const raw of Array.isArray(sources) ? sources : []) {
215
+ if (!raw || typeof raw !== 'object') continue;
216
+ if (raw.kind === 'text' || typeof raw.text === 'string') {
217
+ pushText(typeof raw.name === 'string' ? raw.name : 'inline', 'text', raw.text);
218
+ continue;
219
+ }
220
+ if (typeof raw.path === 'string') {
221
+ const read = readInsideRoot(memoryRoot, raw.path);
222
+ if (read.ok) pushText(typeof raw.name === 'string' ? raw.name : raw.path, 'file', read.text);
223
+ else skipped.push({ name: raw.name ?? raw.path, kind: 'file', skipped: true, code: read.code });
224
+ }
225
+ }
226
+ for (const rel of Array.isArray(profilePaths) ? profilePaths : []) {
227
+ if (typeof rel !== 'string' || rel.trim() === '') continue;
228
+ const read = readInsideRoot(memoryRoot, pathJoinSafe(memoryRoot, rel));
229
+ if (read.ok) pushText(rel, 'file', read.text);
230
+ else if (read.code !== 'ENOENT') skipped.push({ name: rel, kind: 'file', skipped: true, code: read.code });
231
+ }
232
+ return { collected, skipped };
233
+ }
234
+
235
+ function pathJoinSafe(memoryRoot, rel) {
236
+ // `readInsideRoot` re-checks containment; joining here only keeps absolute
237
+ // role file inputs out of the profile-path list.
238
+ if (path.isAbsolute(rel)) return rel;
239
+ return path.join(String(memoryRoot ?? ''), rel);
240
+ }
241
+
242
+ /**
243
+ * Generate the next personality snapshot from local sources (no LLM).
244
+ * Version is monotonic; every source is audited (name/sha256/chars).
245
+ */
246
+ export function generatePersonalitySnapshot({
247
+ memoryRoot,
248
+ sources = [],
249
+ profilePaths = PERSONALITY_DEFAULTS.profilePaths,
250
+ preferences = undefined,
251
+ now = () => new Date(),
252
+ auditKey = null,
253
+ actorKind = 'host',
254
+ subject = undefined,
255
+ userId = undefined,
256
+ projectId = undefined,
257
+ readers = undefined,
258
+ } = {}) {
259
+ const paths = rolePaths(memoryRoot);
260
+ const current = readPersonality({ memoryRoot, auditKey }).snapshot ?? emptySnapshot();
261
+ const { collected, skipped } = collectSources({ memoryRoot, sources, profilePaths });
262
+ const joined = collected.map((item) => item.text).join('\n');
263
+ const retentionBias = extractRetentionBias([joined, preferences ? JSON.stringify(preferences) : '']);
264
+ if (preferences && typeof preferences === 'object' && !Array.isArray(preferences)) {
265
+ for (const kind of RETENTION_KINDS) {
266
+ if (preferences[kind] !== undefined) retentionBias[kind] = clampBias(preferences[kind]);
267
+ }
268
+ }
269
+ const tone = extractTone(joined);
270
+ const createdAt = iso(nowMs(now()));
271
+ const version = (current.version ?? 0) + 1;
272
+ const sourceAudit = [
273
+ ...collected.map((item) => ({ name: item.name, kind: item.kind, sha256: item.sha256, chars: item.chars })),
274
+ ...skipped,
275
+ ];
276
+ const snapshotId = `psn_${sha256Hex(JSON.stringify({
277
+ version,
278
+ createdAt,
279
+ tone,
280
+ retentionBias,
281
+ sources: sourceAudit.map((item) => item.sha256 ?? item.code ?? item.name),
282
+ })).slice(0, 12)}`;
283
+ const snapshot = { snapshotId, version, retentionBias, tone, createdAt, sources: sourceAudit };
284
+ ensureRoleDir(memoryRoot);
285
+ const nextSubject = (subject !== undefined || userId !== undefined || projectId !== undefined || readers !== undefined)
286
+ ? {
287
+ sessionId: subject?.sessionId ?? null,
288
+ userId: subject?.userId ?? userId ?? null,
289
+ projectId: subject?.projectId ?? projectId ?? null,
290
+ readers: [
291
+ ...(Array.isArray(subject?.readers) ? subject.readers : []),
292
+ ...(Array.isArray(readers) ? readers : []),
293
+ ],
294
+ }
295
+ : undefined;
296
+ writeJsonAtomic(paths.personality, { v: 1, ...snapshot }, { memoryRoot, auditKey, actorKind, subject: nextSubject });
297
+ const audit = {
298
+ seq: nextAuditSeq(paths, { memoryRoot, auditKey }),
299
+ at: createdAt,
300
+ action: 'personality.snapshot',
301
+ actor: 'host',
302
+ reason: `snapshot v${version} 生成(tone=${tone},sources=${collected.length},skipped=${skipped.length})`,
303
+ before: { version: current.version ?? 0, tone: current.tone },
304
+ after: { version, tone, retentionBias },
305
+ undo: { previous: current.version ? { ...current } : null },
306
+ source: 'role.personality',
307
+ };
308
+ appendJsonl(paths.audit, audit, { memoryRoot, auditKey, actorKind });
309
+ return {
310
+ ok: true,
311
+ schema: PERSONALITY_SCHEMA,
312
+ snapshot,
313
+ sources: sourceAudit,
314
+ skipped,
315
+ auditSeq: audit.seq,
316
+ };
317
+ }
318
+
319
+ /** 三接口 #3(读侧):retentionBias weight for one memory kind (default 1.0). */
320
+ export function retentionBiasFor(kind, { snapshot = null } = {}) {
321
+ const key = String(kind ?? '');
322
+ const bias = snapshot?.retentionBias ?? PERSONALITY_DEFAULTS.retentionBias;
323
+ const value = bias[key];
324
+ return typeof value === 'number' && Number.isFinite(value) ? clampBias(value) : 1.0;
325
+ }
326
+
327
+ /**
328
+ * 三接口 #3(纯阈值调整器):只调整衰减阈值,不动 immune/protected 判定。
329
+ * base rules 形状 `{epochsMinAgeDays, tombstoneMinAgeDays, immuneSalience?}`;
330
+ * 返回每个 kind 的调整后阈值 + 原样保留的 immuneSalience。
331
+ */
332
+ export function applyRetentionBiasToRules(rules = {}, { snapshot = null } = {}) {
333
+ const base = {
334
+ epochsMinAgeDays: Number.isFinite(Number(rules.epochsMinAgeDays)) ? Math.max(1, Math.round(Number(rules.epochsMinAgeDays))) : 90,
335
+ tombstoneMinAgeDays: Number.isFinite(Number(rules.tombstoneMinAgeDays)) ? Math.max(1, Math.round(Number(rules.tombstoneMinAgeDays))) : 365,
336
+ immuneSalience: Number.isInteger(rules.immuneSalience) ? rules.immuneSalience : 5,
337
+ };
338
+ const perKind = {};
339
+ for (const kind of RETENTION_KINDS) {
340
+ const bias = retentionBiasFor(kind, { snapshot });
341
+ perKind[kind] = {
342
+ kind,
343
+ retentionBias: bias,
344
+ epochsMinAgeDays: Math.max(1, Math.round(base.epochsMinAgeDays * bias)),
345
+ tombstoneMinAgeDays: Math.max(1, Math.round(base.tombstoneMinAgeDays * bias)),
346
+ };
347
+ }
348
+ return {
349
+ schema: 'retention-bias/v1',
350
+ base,
351
+ perKind,
352
+ // 硬边界:protected/forbid/immune 不参与 bias(不越权)。
353
+ immuneSalience: base.immuneSalience,
354
+ protectedUnaffected: true,
355
+ };
356
+ }
357
+
358
+ /** 语气投影:给 systemPrompt.section 用的一行风格指引(neutral 不注入)。 */
359
+ export function toneProjection({ snapshot = null } = {}) {
360
+ const tone = snapshot?.tone ?? PERSONALITY_DEFAULTS.tone;
361
+ if (tone === 'neutral') return { tone, styleLine: '', inject: false };
362
+ const lines = {
363
+ warm: '语气:可以长一点、带人情味,不用端着;别用假话哄人。',
364
+ 'honest-direct': '语气:直接说真话,不哄不编;不确定就明说没查。',
365
+ concise: '语气:短、具体、先给结论,再给一两行依据。',
366
+ };
367
+ return { tone, styleLine: lines[tone] ?? '', inject: (lines[tone] ?? '') !== '' };
368
+ }
369
+
370
+ export { RoleError, ROLE_CODES };
@@ -0,0 +1,151 @@
1
+ // src/role/readers.js — 角色内核只读投影(供 §12.3 路由 #24–#27 使用)
2
+ //
3
+ // 只读:不建目录、不修复文件、不写审计;坏文件降级为 present/degraded 标记,
4
+ // 绝不让面板/注入因为一个坏行而崩。路由注册在 src/ui/routes-readonly.js:
5
+ // #24 attention/v1 -> readAttentionView
6
+ // #25 relationships/v1 -> readRelationshipsView
7
+ // #26 personality/v1 -> readPersonalityView
8
+ // #27 channels/v1 -> readChannelsView(生产者按 v2.8 归 release-check)
9
+
10
+ import { orderAttentionRows, ATTENTION_SCHEMA, normalizeAttentionRow } from './attention.js';
11
+ import { nowMs, readJsonlSafe, tryRolePaths } from './store.js';
12
+ import {
13
+ RELATIONSHIPS_SCHEMA, RELATIONSHIP_DEFAULTS, TIER_WEIGHTS, readRelationships,
14
+ } from './relationships.js';
15
+ import { PERSONALITY_SCHEMA, PERSONALITY_DEFAULTS, readPersonality } from './personality.js';
16
+ import { CHANNELS_SCHEMA, readChannels } from './channels.js';
17
+
18
+ function isoOrNull(value, fallbackMs) {
19
+ if (typeof value === 'string' && Number.isFinite(Date.parse(value))) return value;
20
+ return Number.isFinite(fallbackMs) ? new Date(fallbackMs).toISOString() : null;
21
+ }
22
+
23
+ /** `attention/v1`:items[]{id,priority,kind,subject,at,source,effectivePriority,aged} */
24
+ export function readAttentionView({ memoryRoot, limit = 50, now = () => new Date(), caller = null, auditKey = null } = {}) {
25
+ const paths = tryRolePaths(memoryRoot);
26
+ if (paths === null) {
27
+ return {
28
+ schema: ATTENTION_SCHEMA,
29
+ version: 1,
30
+ present: false,
31
+ degraded: false,
32
+ bad: 0,
33
+ count: 0,
34
+ total: 0,
35
+ items: [],
36
+ code: 'E_ATTENTION_ABSENT',
37
+ readAt: isoOrNull(null, nowMs(now())),
38
+ };
39
+ }
40
+ const read = readJsonlSafe(paths.attention, { limit: 10_000, memoryRoot, auditKey });
41
+ if (read.tampered === true) {
42
+ return {
43
+ schema: ATTENTION_SCHEMA,
44
+ present: false,
45
+ degraded: true,
46
+ tampered: true,
47
+ bad: 0,
48
+ count: 0,
49
+ total: 0,
50
+ items: [],
51
+ code: read.code ?? 'E_INTEGRITY_TAMPER',
52
+ readAt: isoOrNull(null, nowMs(now())),
53
+ };
54
+ }
55
+ const rows = [];
56
+ let bad = read.bad ?? 0;
57
+ for (const raw of read.rows) {
58
+ const row = normalizeAttentionRow(raw);
59
+ if (row) rows.push(row);
60
+ else bad += 1;
61
+ }
62
+ const ordered = orderAttentionRows(rows, { now: nowMs(now()) });
63
+ const items = ordered.slice(0, limit).map((row) => ({
64
+ id: row.id,
65
+ priority: row.priority,
66
+ kind: row.kind,
67
+ subject: row.subject,
68
+ at: row.at,
69
+ source: row.source,
70
+ effectivePriority: row.effectivePriority,
71
+ aged: row.aged,
72
+ }));
73
+ return {
74
+ schema: ATTENTION_SCHEMA,
75
+ version: 1,
76
+ present: read.present === true,
77
+ degraded: bad > 0,
78
+ bad,
79
+ count: items.length,
80
+ total: rows.length,
81
+ items,
82
+ code: bad > 0 ? 'E_ATTENTION_PARTIAL' : (read.present === false ? 'E_ATTENTION_ABSENT' : 'OK'),
83
+ readAt: isoOrNull(null, nowMs(now())),
84
+ };
85
+ }
86
+
87
+ /** `relationships/v1`:nodes[]{personId,tier,confidence,updatedAt,version,appellations},edges[] */
88
+ export function readRelationshipsView({ memoryRoot, now = () => new Date(), caller = null, auditKey = null } = {}) {
89
+ const graph = readRelationships({ memoryRoot, caller, auditKey });
90
+ return {
91
+ schema: RELATIONSHIPS_SCHEMA,
92
+ version: 1,
93
+ present: graph.present,
94
+ degraded: graph.degraded,
95
+ tampered: graph.tampered === true,
96
+ denied: graph.denied === true,
97
+ updatedAt: graph.updatedAt,
98
+ subject: graph.subject ?? null,
99
+ count: graph.count,
100
+ nodes: graph.nodes.map((node) => ({
101
+ personId: node.personId,
102
+ tier: node.tier,
103
+ confidence: node.confidence,
104
+ updatedAt: node.updatedAt,
105
+ version: node.version,
106
+ appellations: [...node.appellations],
107
+ })),
108
+ edges: graph.edges.map((edge) => ({ from: edge.from, to: edge.to, relation: edge.relation, lastSeenAt: edge.lastSeenAt })),
109
+ tierWeights: { ...TIER_WEIGHTS },
110
+ defaultTier: RELATIONSHIP_DEFAULTS.tier,
111
+ code: graph.code,
112
+ readAt: isoOrNull(null, nowMs(now())),
113
+ };
114
+ }
115
+
116
+ /** `personality/v1`:{snapshotId,version,retentionBias,tone,createdAt,sources} */
117
+ export function readPersonalityView({ memoryRoot, now = () => new Date(), caller = null, auditKey = null } = {}) {
118
+ const read = readPersonality({ memoryRoot, caller, auditKey });
119
+ const snapshot = read.snapshot;
120
+ return {
121
+ schema: PERSONALITY_SCHEMA,
122
+ version: 1,
123
+ present: read.present,
124
+ degraded: read.degraded,
125
+ tampered: read.tampered === true,
126
+ denied: read.denied === true,
127
+ subject: read.subject ?? snapshot?.subject ?? null,
128
+ snapshotId: snapshot?.snapshotId ?? null,
129
+ version: snapshot?.version ?? 0,
130
+ retentionBias: snapshot?.retentionBias ?? { ...PERSONALITY_DEFAULTS.retentionBias },
131
+ tone: snapshot?.tone ?? PERSONALITY_DEFAULTS.tone,
132
+ createdAt: snapshot?.createdAt ?? null,
133
+ sources: snapshot?.sources ?? [],
134
+ defaults: read.defaults,
135
+ code: read.code,
136
+ readAt: isoOrNull(null, nowMs(now())),
137
+ };
138
+ }
139
+
140
+ /** `channels/v1`(route #27;生产者按 v2.8 归 release-check,本函数供其复用)。 */
141
+ export function readChannelsView({ memoryRoot, now = () => new Date(), caller = null, auditKey = null } = {}) {
142
+ const view = readChannels({ memoryRoot, now, caller, auditKey });
143
+ return { ...view, schema: CHANNELS_SCHEMA, version: 1 };
144
+ }
145
+
146
+ export const ROLE_READERS = Object.freeze({
147
+ attention: readAttentionView,
148
+ relationships: readRelationshipsView,
149
+ personality: readPersonalityView,
150
+ channels: readChannelsView,
151
+ });