@jjh32456/longlive 0.0.0-stage → 2.0.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 (331) hide show
  1. package/CHANGELOG.md +235 -0
  2. package/LICENSE +21 -0
  3. package/QUICKSTART.md +362 -0
  4. package/README.en.md +64 -0
  5. package/README.md +256 -2
  6. package/SPEC.md +211 -0
  7. package/build-info.json +1665 -0
  8. package/cordis.patch.yml +208 -0
  9. package/docs/A1-MIGRATION.md +75 -0
  10. package/docs/ANSWER-GUARD.md +92 -0
  11. package/docs/ARCHITECTURE.md +128 -0
  12. package/docs/AUTO-RECALL-WIRING.md +115 -0
  13. package/docs/AUTO-RECALL.md +237 -0
  14. package/docs/CONCEPTS.md +143 -0
  15. package/docs/CONFIG.md +839 -0
  16. package/docs/ERRORS.md +271 -0
  17. package/docs/FAQ.md +186 -0
  18. package/docs/FEATURES.md +579 -0
  19. package/docs/INDEX-FRESHNESS.md +21 -0
  20. package/docs/METRICS.md +244 -0
  21. package/docs/MIGRATION-1.6.0.md +220 -0
  22. package/docs/OPERATIONS.md +439 -0
  23. package/docs/PANEL-INTEGRATION.md +190 -0
  24. package/docs/PRIVACY.md +88 -0
  25. package/docs/QUICKSTART.md +155 -0
  26. package/docs/RAW-INDEX-POLICY.md +7 -0
  27. package/docs/README.en.md +48 -0
  28. package/docs/RESIDENT-WATCHER.md +90 -0
  29. package/docs/SESSION-WATCH.md +214 -0
  30. package/docs/TOOLS.md +184 -0
  31. package/docs/TROUBLESHOOTING.md +329 -0
  32. package/icon.svg +11 -0
  33. package/lib/client.js +436 -0
  34. package/locale/en.json +6 -0
  35. package/locale/zh.json +6 -0
  36. package/package.json +163 -4
  37. package/runbook.md +343 -0
  38. package/scripts/archive-digest-build.mjs +668 -0
  39. package/scripts/auto-truncate-run.ps1 +752 -0
  40. package/scripts/backfill-auto-cards.mjs +98 -0
  41. package/scripts/edges-build.mjs +1003 -0
  42. package/scripts/index-maintain.mjs +39 -0
  43. package/scripts/index-reconcile.mjs +49 -0
  44. package/scripts/index-status.mjs +28 -0
  45. package/scripts/install-resident-watcher.ps1 +15 -0
  46. package/scripts/install-session-watch.ps1 +332 -0
  47. package/scripts/install-surgery-task.ps1 +174 -0
  48. package/scripts/lib/auto-truncate-run.ps1 +512 -0
  49. package/scripts/lib/session-watch-fixture.mjs +207 -0
  50. package/scripts/longlive-doctor.mjs +578 -0
  51. package/scripts/metrics-read.mjs +79 -0
  52. package/scripts/metrics-sample.mjs +215 -0
  53. package/scripts/migrate-180.mjs +163 -0
  54. package/scripts/migrate-200.mjs +8 -0
  55. package/scripts/migrate-a1-legacy.mjs +62 -0
  56. package/scripts/migrate-lifecycle.mjs +157 -0
  57. package/scripts/pack.mjs +392 -0
  58. package/scripts/recall-index-build.mjs +128 -0
  59. package/scripts/recall-links-build.mjs +420 -0
  60. package/scripts/rescore-cards.mjs +36 -0
  61. package/scripts/resident-watcher-status.ps1 +15 -0
  62. package/scripts/resident-watcher.ps1 +643 -0
  63. package/scripts/session-watch-drill.mjs +553 -0
  64. package/scripts/session-watch-status.ps1 +146 -0
  65. package/scripts/session-watch.mjs +1367 -0
  66. package/scripts/surgery-inspect.mjs +122 -0
  67. package/scripts/surgery-run.cmd +34 -0
  68. package/scripts/truncate-cli.mjs +279 -0
  69. package/scripts/unattended-surgery.ps1 +1019 -0
  70. package/scripts/uninstall-resident-watcher.ps1 +15 -0
  71. package/scripts/uninstall-session-watch.ps1 +192 -0
  72. package/scripts/verify-card-anchors.mjs +138 -0
  73. package/scripts/watch-loop.ps1 +916 -0
  74. package/src/actions/audit.js +125 -0
  75. package/src/actions/evidence.js +122 -0
  76. package/src/actions/fs.js +162 -0
  77. package/src/activity/index.js +873 -0
  78. package/src/activity/model.js +351 -0
  79. package/src/activity/store.js +786 -0
  80. package/src/activity/summary.js +180 -0
  81. package/src/activity/thinking.js +191 -0
  82. package/src/adapters/constants.js +11 -0
  83. package/src/adapters/engram/data/aliases.json +51 -0
  84. package/src/adapters/engram/data/policy.json +8 -0
  85. package/src/adapters/engram/data/routing-rules.json +546 -0
  86. package/src/adapters/engram/index.js +278 -0
  87. package/src/adapters/registry.js +315 -0
  88. package/src/answer/audit.js +238 -0
  89. package/src/answer/claim-guard.mjs +234 -0
  90. package/src/answer/evidence.js +30 -0
  91. package/src/answer/guard.js +1370 -0
  92. package/src/answer/index.js +1086 -0
  93. package/src/answer/query.js +111 -0
  94. package/src/answer/second-hop.mjs +101 -0
  95. package/src/auto-truncate-status.js +164 -0
  96. package/src/auto-truncate.js +1181 -0
  97. package/src/autoprocedure/candidate.js +342 -0
  98. package/src/autoprocedure/config.js +122 -0
  99. package/src/autoprocedure/evidence.js +345 -0
  100. package/src/autoprocedure/index.js +83 -0
  101. package/src/autoprocedure/ledger.js +329 -0
  102. package/src/autoprocedure/lint.js +232 -0
  103. package/src/autoprocedure/llm.js +409 -0
  104. package/src/autoprocedure/locks.js +102 -0
  105. package/src/autoprocedure/paths.js +39 -0
  106. package/src/autoprocedure/privacy.js +87 -0
  107. package/src/autoprocedure/rules.js +288 -0
  108. package/src/autoprocedure/runtime.js +718 -0
  109. package/src/autoprocedure/session-reader.js +328 -0
  110. package/src/backup.js +310 -0
  111. package/src/bus/bus.mjs +1446 -0
  112. package/src/codec.js +269 -0
  113. package/src/compaction/cut-engine.js +44 -0
  114. package/src/compaction/engine-core.js +1237 -0
  115. package/src/compaction/entry.js +228 -0
  116. package/src/compaction.js +230 -0
  117. package/src/conclusion.js +366 -0
  118. package/src/config.js +835 -0
  119. package/src/d6/runtime.js +517 -0
  120. package/src/d6/surface.js +181 -0
  121. package/src/deps.js +189 -0
  122. package/src/engine-status.js +141 -0
  123. package/src/features.js +1035 -0
  124. package/src/handoff/index.js +1077 -0
  125. package/src/handoff/model.js +1058 -0
  126. package/src/handoff/store.js +1233 -0
  127. package/src/heartbeat.js +385 -0
  128. package/src/home.js +16 -0
  129. package/src/host-version.js +280 -0
  130. package/src/hot-truncate-diag.js +98 -0
  131. package/src/identity/card-marker.js +281 -0
  132. package/src/identity/handover.js +845 -0
  133. package/src/identity/index.js +337 -0
  134. package/src/identity/inject-position.js +133 -0
  135. package/src/identity/writeback.js +344 -0
  136. package/src/identity.js +118 -0
  137. package/src/index.js +647 -0
  138. package/src/lifecycle/gap-clocks.js +364 -0
  139. package/src/lifecycle/index.js +269 -0
  140. package/src/lifecycle/proactive.js +1426 -0
  141. package/src/live-target.js +212 -0
  142. package/src/live.js +1603 -0
  143. package/src/log-rotation.js +153 -0
  144. package/src/memory/a1-migration.js +190 -0
  145. package/src/memory/activity-capture.js +229 -0
  146. package/src/memory/anchor-fallback.js +116 -0
  147. package/src/memory/anchors.js +194 -0
  148. package/src/memory/archive-cold-state.mjs +794 -0
  149. package/src/memory/archive-staging.mjs +305 -0
  150. package/src/memory/archive.mjs +415 -0
  151. package/src/memory/audit-records.js +222 -0
  152. package/src/memory/auto-cards.js +441 -0
  153. package/src/memory/capture-host.js +297 -0
  154. package/src/memory/capture.js +496 -0
  155. package/src/memory/card-anchors.js +203 -0
  156. package/src/memory/card-priority.js +110 -0
  157. package/src/memory/cards.js +425 -0
  158. package/src/memory/catchup.mjs +534 -0
  159. package/src/memory/conclusion-distill.js +381 -0
  160. package/src/memory/conclusion-drafts.js +243 -0
  161. package/src/memory/conflicts.js +1060 -0
  162. package/src/memory/consolidate.js +834 -0
  163. package/src/memory/decay.js +311 -0
  164. package/src/memory/distill.js +485 -0
  165. package/src/memory/event-index.js +1826 -0
  166. package/src/memory/evidence-chain.js +295 -0
  167. package/src/memory/evidence.js +213 -0
  168. package/src/memory/filter-runner.js +555 -0
  169. package/src/memory/filter.js +1035 -0
  170. package/src/memory/forget-v2.js +680 -0
  171. package/src/memory/forget.js +531 -0
  172. package/src/memory/frames-activation.js +249 -0
  173. package/src/memory/frontmatter.js +454 -0
  174. package/src/memory/fts-query.js +342 -0
  175. package/src/memory/governance.js +604 -0
  176. package/src/memory/index-freshness.js +234 -0
  177. package/src/memory/index.js +435 -0
  178. package/src/memory/l2-gate.js +169 -0
  179. package/src/memory/land.mjs +743 -0
  180. package/src/memory/lifecycle.js +235 -0
  181. package/src/memory/lock.js +121 -0
  182. package/src/memory/maintenance.js +1149 -0
  183. package/src/memory/manifest.js +245 -0
  184. package/src/memory/memory-health.mjs +607 -0
  185. package/src/memory/migrate-200.js +1681 -0
  186. package/src/memory/migrate-lifecycle.js +1808 -0
  187. package/src/memory/migrate.js +139 -0
  188. package/src/memory/paths.js +229 -0
  189. package/src/memory/procedure-candidate.mjs +377 -0
  190. package/src/memory/procedure.js +982 -0
  191. package/src/memory/prospective-memory.mjs +362 -0
  192. package/src/memory/provenance.js +119 -0
  193. package/src/memory/recall-feedback.mjs +406 -0
  194. package/src/memory/recall-v2.js +218 -0
  195. package/src/memory/recall.js +357 -0
  196. package/src/memory/reconcile.js +265 -0
  197. package/src/memory/records.js +433 -0
  198. package/src/memory/reinforce.js +281 -0
  199. package/src/memory/retention.js +162 -0
  200. package/src/memory/review.js +124 -0
  201. package/src/memory/state.js +279 -0
  202. package/src/memory/tiers.js +168 -0
  203. package/src/memory/topic-phrases.js +73 -0
  204. package/src/memory/trust.js +97 -0
  205. package/src/memory/turn-budget.mjs +290 -0
  206. package/src/memory/version-chain.js +264 -0
  207. package/src/memory/wake-bridge.mjs +2999 -0
  208. package/src/memory/wal.js +137 -0
  209. package/src/memory/working-frame.js +779 -0
  210. package/src/metrics/classify.mjs +191 -0
  211. package/src/metrics/estimate.mjs +108 -0
  212. package/src/metrics/index.mjs +204 -0
  213. package/src/metrics/measure.mjs +462 -0
  214. package/src/metrics/prestep-latency.mjs +307 -0
  215. package/src/metrics/store.mjs +264 -0
  216. package/src/original.js +294 -0
  217. package/src/policy/threshold-policy.js +224 -0
  218. package/src/policy-profile.js +463 -0
  219. package/src/recall/anaphora.mjs +87 -0
  220. package/src/recall/archive-config.mjs +130 -0
  221. package/src/recall/archive-fallback.mjs +390 -0
  222. package/src/recall/archive-search.mjs +428 -0
  223. package/src/recall/archive-state.mjs +588 -0
  224. package/src/recall/brain.mjs +501 -0
  225. package/src/recall/cards.mjs +202 -0
  226. package/src/recall/current-line.mjs +110 -0
  227. package/src/recall/edges.js +398 -0
  228. package/src/recall/embedding.mjs +698 -0
  229. package/src/recall/entities.mjs +112 -0
  230. package/src/recall/explain.mjs +443 -0
  231. package/src/recall/force-policy.mjs +138 -0
  232. package/src/recall/gate-log.mjs +280 -0
  233. package/src/recall/gate-metrics.mjs +191 -0
  234. package/src/recall/index.js +1337 -0
  235. package/src/recall/inject-order.mjs +279 -0
  236. package/src/recall/link-recall.mjs +183 -0
  237. package/src/recall/links.mjs +696 -0
  238. package/src/recall/privacy.mjs +208 -0
  239. package/src/recall/recall-core.mjs +810 -0
  240. package/src/recall/shared-visibility.js +302 -0
  241. package/src/recall/time-normalizer.mjs +196 -0
  242. package/src/recall/turn-budget-inject.mjs +154 -0
  243. package/src/retention/cold-gate.mjs +146 -0
  244. package/src/retention/config.js +163 -0
  245. package/src/retention/index.js +801 -0
  246. package/src/role/activation.js +191 -0
  247. package/src/role/attention.js +318 -0
  248. package/src/role/base.js +36 -0
  249. package/src/role/channels.js +423 -0
  250. package/src/role/index.js +425 -0
  251. package/src/role/interfaces.js +115 -0
  252. package/src/role/personality.js +370 -0
  253. package/src/role/readers.js +151 -0
  254. package/src/role/relationships.js +477 -0
  255. package/src/role/store.js +202 -0
  256. package/src/role/writeprotect.js +373 -0
  257. package/src/router/aliases.json +182 -0
  258. package/src/router/background/agent-runner.mjs +239 -0
  259. package/src/router/background/anchor.mjs +323 -0
  260. package/src/router/background/audit.mjs +337 -0
  261. package/src/router/background/budget-ledger.mjs +648 -0
  262. package/src/router/background/host-sim.mjs +451 -0
  263. package/src/router/background/index.mjs +81 -0
  264. package/src/router/background/memory.mjs +63 -0
  265. package/src/router/background/mock-llm.mjs +203 -0
  266. package/src/router/background/queue.mjs +224 -0
  267. package/src/router/background/retry.mjs +255 -0
  268. package/src/router/background/router.mjs +1459 -0
  269. package/src/router/background/stream.mjs +276 -0
  270. package/src/router/background/tool-policy.mjs +255 -0
  271. package/src/router/design-headings.json +221 -0
  272. package/src/router/face/config.mjs +155 -0
  273. package/src/router/face/context.mjs +284 -0
  274. package/src/router/face/face.mjs +466 -0
  275. package/src/router/face/identity.mjs +130 -0
  276. package/src/router/face/index.mjs +65 -0
  277. package/src/router/face/journal.mjs +119 -0
  278. package/src/router/face/llm.mjs +252 -0
  279. package/src/router/face/outbox.mjs +153 -0
  280. package/src/router/face/paths.mjs +54 -0
  281. package/src/router/judge.mjs +987 -0
  282. package/src/router/policies/generic.json +131 -0
  283. package/src/router/route.js +1766 -0
  284. package/src/router/router.mjs +535 -0
  285. package/src/router/routing-rules.json +816 -0
  286. package/src/router/run-sim.mjs +530 -0
  287. package/src/router/runtime.js +569 -0
  288. package/src/router/service/apply.mjs +1218 -0
  289. package/src/router/service/board.mjs +712 -0
  290. package/src/router/service/caller.mjs +131 -0
  291. package/src/router/service/config.mjs +361 -0
  292. package/src/router/service/context.mjs +314 -0
  293. package/src/router/service/hint.mjs +668 -0
  294. package/src/router/service/lease.mjs +494 -0
  295. package/src/router/service/live.mjs +251 -0
  296. package/src/router/service/lock.mjs +550 -0
  297. package/src/router/service/merge.mjs +255 -0
  298. package/src/router/service/model-resolve.mjs +350 -0
  299. package/src/router/service/paths.mjs +168 -0
  300. package/src/router/service/proposals.mjs +1461 -0
  301. package/src/router/service/queue.mjs +477 -0
  302. package/src/router/service/reconcile.mjs +271 -0
  303. package/src/router/service/service.mjs +2998 -0
  304. package/src/router/service/sources.mjs +352 -0
  305. package/src/router/service/status.mjs +520 -0
  306. package/src/router/service/store.mjs +476 -0
  307. package/src/router/service/ticklock.mjs +239 -0
  308. package/src/router/service/tokens.mjs +95 -0
  309. package/src/router/service/tools.mjs +248 -0
  310. package/src/router/service/wake.mjs +544 -0
  311. package/src/router/service/wal.mjs +685 -0
  312. package/src/router/shadow.mjs +821 -0
  313. package/src/surgery-recovery.js +1909 -0
  314. package/src/tool-output.js +485 -0
  315. package/src/tools.js +3262 -0
  316. package/src/truncate-visible.js +2416 -0
  317. package/src/truncate.js +999 -0
  318. package/src/ui/actions.js +1312 -0
  319. package/src/ui/flags.js +259 -0
  320. package/src/ui/panel-api.js +371 -0
  321. package/src/ui/panel-auth.js +251 -0
  322. package/src/ui/panel-integrity.js +243 -0
  323. package/src/ui/routes-readonly.js +759 -0
  324. package/src/ui/routes.js +284 -0
  325. package/src/util/append-store.js +368 -0
  326. package/src/util/local-day.js +30 -0
  327. package/src/util/redact.js +227 -0
  328. package/src/util/stale-locks.js +148 -0
  329. package/src/version.js +99 -0
  330. package/test/fixtures/pre-step-container.mjs +100 -0
  331. package/test/p1_probe.mjs +97 -0
@@ -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
+ });