@dabuliu_wsy/dsh-im 0.0.0-stage → 0.2.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 (137) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +197 -3
  3. package/cordis.patch.yml +4 -0
  4. package/dist/core/agent-state.d.ts +38 -0
  5. package/dist/core/agent-state.js +59 -0
  6. package/dist/core/arbiter-bridge.d.ts +25 -0
  7. package/dist/core/arbiter-bridge.js +20 -0
  8. package/dist/core/arbiter.d.ts +29 -0
  9. package/dist/core/arbiter.js +59 -0
  10. package/dist/core/avatar-brands.d.ts +23 -0
  11. package/dist/core/avatar-brands.js +75 -0
  12. package/dist/core/avatar-presets.d.ts +21 -0
  13. package/dist/core/avatar-presets.js +38 -0
  14. package/dist/core/avatar.d.ts +1 -0
  15. package/dist/core/avatar.js +18 -0
  16. package/dist/core/blocked.d.ts +12 -0
  17. package/dist/core/blocked.js +23 -0
  18. package/dist/core/budget-plan.d.ts +41 -0
  19. package/dist/core/budget-plan.js +69 -0
  20. package/dist/core/calibration-samples.d.ts +77 -0
  21. package/dist/core/calibration-samples.js +168 -0
  22. package/dist/core/calibrator.d.ts +57 -0
  23. package/dist/core/calibrator.js +125 -0
  24. package/dist/core/chapter-tree.d.ts +128 -0
  25. package/dist/core/chapter-tree.js +400 -0
  26. package/dist/core/consensus.d.ts +135 -0
  27. package/dist/core/consensus.js +394 -0
  28. package/dist/core/context-budget.d.ts +153 -0
  29. package/dist/core/context-budget.js +183 -0
  30. package/dist/core/curator.d.ts +28 -0
  31. package/dist/core/curator.js +190 -0
  32. package/dist/core/dual-window.d.ts +86 -0
  33. package/dist/core/dual-window.js +175 -0
  34. package/dist/core/events.d.ts +110 -0
  35. package/dist/core/events.js +117 -0
  36. package/dist/core/facts.d.ts +114 -0
  37. package/dist/core/facts.js +400 -0
  38. package/dist/core/fence.d.ts +34 -0
  39. package/dist/core/fence.js +129 -0
  40. package/dist/core/floor.d.ts +18 -0
  41. package/dist/core/floor.js +80 -0
  42. package/dist/core/ids.d.ts +11 -0
  43. package/dist/core/ids.js +29 -0
  44. package/dist/core/im.d.ts +167 -0
  45. package/dist/core/im.js +1307 -0
  46. package/dist/core/index.d.ts +33 -0
  47. package/dist/core/index.js +33 -0
  48. package/dist/core/log.d.ts +21 -0
  49. package/dist/core/log.js +63 -0
  50. package/dist/core/memory-claims.d.ts +67 -0
  51. package/dist/core/memory-claims.js +164 -0
  52. package/dist/core/memory-context.d.ts +121 -0
  53. package/dist/core/memory-context.js +303 -0
  54. package/dist/core/memory-visibility.d.ts +58 -0
  55. package/dist/core/memory-visibility.js +36 -0
  56. package/dist/core/memory.d.ts +12 -0
  57. package/dist/core/memory.js +73 -0
  58. package/dist/core/metrics.d.ts +49 -0
  59. package/dist/core/metrics.js +89 -0
  60. package/dist/core/multi-hop.d.ts +116 -0
  61. package/dist/core/multi-hop.js +278 -0
  62. package/dist/core/persist.d.ts +21 -0
  63. package/dist/core/persist.js +94 -0
  64. package/dist/core/proactive.d.ts +54 -0
  65. package/dist/core/proactive.js +108 -0
  66. package/dist/core/prompt.d.ts +82 -0
  67. package/dist/core/prompt.js +164 -0
  68. package/dist/core/receipt.d.ts +107 -0
  69. package/dist/core/receipt.js +86 -0
  70. package/dist/core/retrieval.d.ts +69 -0
  71. package/dist/core/retrieval.js +260 -0
  72. package/dist/core/role-state.d.ts +16 -0
  73. package/dist/core/role-state.js +65 -0
  74. package/dist/core/runtime.d.ts +137 -0
  75. package/dist/core/runtime.js +574 -0
  76. package/dist/core/summary.d.ts +19 -0
  77. package/dist/core/summary.js +96 -0
  78. package/dist/core/text.d.ts +10 -0
  79. package/dist/core/text.js +45 -0
  80. package/dist/core/time.d.ts +22 -0
  81. package/dist/core/time.js +84 -0
  82. package/dist/core/tool-schema.d.ts +12 -0
  83. package/dist/core/tool-schema.js +92 -0
  84. package/dist/core/tools.d.ts +137 -0
  85. package/dist/core/tools.js +348 -0
  86. package/dist/core/types.d.ts +400 -0
  87. package/dist/core/types.js +1 -0
  88. package/dist/core/window.d.ts +6 -0
  89. package/dist/core/window.js +7 -0
  90. package/dist/core/workspace-node.d.ts +28 -0
  91. package/dist/core/workspace-node.js +232 -0
  92. package/dist/core/workspace.d.ts +9 -0
  93. package/dist/core/workspace.js +45 -0
  94. package/dist/host/agent-session.d.ts +279 -0
  95. package/dist/host/agent-session.js +935 -0
  96. package/dist/host/attachment-gc.d.ts +37 -0
  97. package/dist/host/attachment-gc.js +97 -0
  98. package/dist/host/calibration-samples-store.d.ts +5 -0
  99. package/dist/host/calibration-samples-store.js +67 -0
  100. package/dist/host/capabilities.d.ts +45 -0
  101. package/dist/host/capabilities.js +67 -0
  102. package/dist/host/derived-store.d.ts +36 -0
  103. package/dist/host/derived-store.js +199 -0
  104. package/dist/host/dsh-llm.d.ts +143 -0
  105. package/dist/host/dsh-llm.js +395 -0
  106. package/dist/host/event-store.d.ts +47 -0
  107. package/dist/host/event-store.js +154 -0
  108. package/dist/host/fs-atomic.d.ts +1 -0
  109. package/dist/host/fs-atomic.js +26 -0
  110. package/dist/host/im-api.d.ts +352 -0
  111. package/dist/host/im-api.js +1137 -0
  112. package/dist/host/index.d.ts +103 -0
  113. package/dist/host/index.js +453 -0
  114. package/dist/host/memory-index.d.ts +65 -0
  115. package/dist/host/memory-index.js +181 -0
  116. package/dist/host/metrics-store.d.ts +7 -0
  117. package/dist/host/metrics-store.js +104 -0
  118. package/dist/host/models.d.ts +39 -0
  119. package/dist/host/models.js +67 -0
  120. package/dist/host/persona-tools.d.ts +57 -0
  121. package/dist/host/persona-tools.js +226 -0
  122. package/dist/host/preflight.d.ts +31 -0
  123. package/dist/host/preflight.js +29 -0
  124. package/dist/host/receipt-store.d.ts +26 -0
  125. package/dist/host/receipt-store.js +68 -0
  126. package/dist/host/run-check.d.ts +51 -0
  127. package/dist/host/run-check.js +190 -0
  128. package/dist/host/state-roots.d.ts +50 -0
  129. package/dist/host/state-roots.js +163 -0
  130. package/dist/host/tool-cache.d.ts +25 -0
  131. package/dist/host/tool-cache.js +90 -0
  132. package/dist/host/tool-call-budget.d.ts +29 -0
  133. package/dist/host/tool-call-budget.js +38 -0
  134. package/dsh-plugin.json +25 -0
  135. package/lib/client.inner.cjs +3346 -0
  136. package/lib/client.js +3354 -0
  137. package/package.json +86 -6
@@ -0,0 +1,33 @@
1
+ export * from './types.ts';
2
+ export * from './avatar.ts';
3
+ export * from './ids.ts';
4
+ export * from './workspace.ts';
5
+ export * from './fence.ts';
6
+ export * from './tools.ts';
7
+ export * from './tool-schema.ts';
8
+ export * from './persist.ts';
9
+ export * from './memory.ts';
10
+ export * from './floor.ts';
11
+ export * from './blocked.ts';
12
+ export * from './window.ts';
13
+ export * from './prompt.ts';
14
+ export * from './events.ts';
15
+ export * from './receipt.ts';
16
+ export * from './facts.ts';
17
+ export * from './summary.ts';
18
+ export * from './chapter-tree.ts';
19
+ export * from './dual-window.ts';
20
+ export * from './multi-hop.ts';
21
+ export * from './context-budget.ts';
22
+ export * from './budget-plan.ts';
23
+ export * from './role-state.ts';
24
+ export * from './retrieval.ts';
25
+ export * from './proactive.ts';
26
+ export * from './metrics.ts';
27
+ export * from './agent-state.ts';
28
+ export * from './arbiter.ts';
29
+ export * from './arbiter-bridge.ts';
30
+ export * from './runtime.ts';
31
+ export * from './im.ts';
32
+ export * from './consensus.ts';
33
+ export * from './curator.ts';
@@ -0,0 +1,33 @@
1
+ export * from './types.js';
2
+ export * from './avatar.js';
3
+ export * from './ids.js';
4
+ export * from './workspace.js';
5
+ export * from './fence.js';
6
+ export * from './tools.js';
7
+ export * from './tool-schema.js';
8
+ export * from './persist.js';
9
+ export * from './memory.js';
10
+ export * from './floor.js';
11
+ export * from './blocked.js';
12
+ export * from './window.js';
13
+ export * from './prompt.js';
14
+ export * from './events.js';
15
+ export * from './receipt.js';
16
+ export * from './facts.js';
17
+ export * from './summary.js';
18
+ export * from './chapter-tree.js';
19
+ export * from './dual-window.js';
20
+ export * from './multi-hop.js';
21
+ export * from './context-budget.js';
22
+ export * from './budget-plan.js';
23
+ export * from './role-state.js';
24
+ export * from './retrieval.js';
25
+ export * from './proactive.js';
26
+ export * from './metrics.js';
27
+ export * from './agent-state.js';
28
+ export * from './arbiter.js';
29
+ export * from './arbiter-bridge.js';
30
+ export * from './runtime.js';
31
+ export * from './im.js';
32
+ export * from './consensus.js';
33
+ export * from './curator.js';
@@ -0,0 +1,21 @@
1
+ /**
2
+ * 统一日志出口:业务代码不直接调 `console.*`。
3
+ *
4
+ * - 浏览器里默认输出到 console;`localStorage['dsh-im:log'] = 'off'` 可静默,
5
+ * `= 'debug'` 打开调试输出。
6
+ * - 宿主可以把 DSH 的 logger 通过 `setLogSink()` 接进来,日志跟着宿主走(不再走 console)。
7
+ * - 本文件是纯函数式小工具:不 import node 模块,客户端/宿主都能用。
8
+ */
9
+ export interface LogSink {
10
+ info: (message: string) => void;
11
+ warn: (message: string, detail?: unknown) => void;
12
+ debug: (message: string, detail?: unknown) => void;
13
+ }
14
+ export type LogLevel = 'off' | 'warn' | 'debug';
15
+ /** 当前日志级别;宿主/Node 环境没有 localStorage 时按 warn。 */
16
+ export declare function logLevel(): LogLevel;
17
+ /** 注销时传 undefined 恢复 console 输出。 */
18
+ export declare function setLogSink(next: LogSink | undefined): void;
19
+ export declare function logInfo(message: string, detail?: unknown): void;
20
+ export declare function logWarn(message: string, detail?: unknown): void;
21
+ export declare function logDebug(message: string, detail?: unknown): void;
@@ -0,0 +1,63 @@
1
+ const LEVEL_KEY = 'dsh-im:log';
2
+ /** 当前日志级别;宿主/Node 环境没有 localStorage 时按 warn。 */
3
+ export function logLevel() {
4
+ try {
5
+ const raw = typeof localStorage === 'undefined' ? null : localStorage.getItem(LEVEL_KEY);
6
+ return raw === 'off' || raw === 'debug' ? raw : 'warn';
7
+ }
8
+ catch {
9
+ return 'warn';
10
+ }
11
+ }
12
+ let sink;
13
+ /** 注销时传 undefined 恢复 console 输出。 */
14
+ export function setLogSink(next) {
15
+ sink = next;
16
+ }
17
+ function detailText(detail) {
18
+ if (detail === undefined || detail === null)
19
+ return '';
20
+ if (detail instanceof Error)
21
+ return ` ${detail.message}`;
22
+ try {
23
+ return ` ${typeof detail === 'string' ? detail : JSON.stringify(detail)}`;
24
+ }
25
+ catch {
26
+ return ` ${String(detail)}`;
27
+ }
28
+ }
29
+ function emit(call, message, detail) {
30
+ if (sink) {
31
+ if (call === 'info')
32
+ sink.info(message);
33
+ else if (call === 'warn')
34
+ sink.warn(message, detail);
35
+ else
36
+ sink.debug(message, detail);
37
+ return;
38
+ }
39
+ const configured = logLevel();
40
+ if (configured === 'off')
41
+ return;
42
+ if (call === 'debug' && configured !== 'debug')
43
+ return;
44
+ const target = call === 'info' ? console.info : call === 'warn' ? console.warn : console.debug;
45
+ try {
46
+ if (detail === undefined)
47
+ target.call(console, message);
48
+ else
49
+ target.call(console, message + detailText(detail));
50
+ }
51
+ catch {
52
+ // 宿主 console 被替换/不可用时静默,日志本身不能影响主流程。
53
+ }
54
+ }
55
+ export function logInfo(message, detail) {
56
+ emit('info', message, detail);
57
+ }
58
+ export function logWarn(message, detail) {
59
+ emit('warn', message, detail);
60
+ }
61
+ export function logDebug(message, detail) {
62
+ emit('debug', message, detail);
63
+ }
@@ -0,0 +1,67 @@
1
+ /**
2
+ * 消息级 claim 状态推导(Phase 0 · 可寻址记忆层)。
3
+ *
4
+ * 为什么需要:检索/展开把旧消息拉回 prompt 时,必须让模型知道这条是
5
+ * 「当前有效结论 / 只是一条原始记录 / 已被取代」。状态是 **claim 级**的——
6
+ * 一条消息可能含多个 claim,其中一部分已被 supersede。
7
+ *
8
+ * 数据来源(全部已有,不新增真相源):
9
+ * - `events.jsonl` 的 `fact` 事件:`assert / supersede / retract` + `sourceMessageSeq`;
10
+ * - `consensusState` 的 cluster:`status` + `supersededByKey` + `refs[].sourceMessageSeq`。
11
+ *
12
+ * 判定优先级:**superseded(含 expired)压过 active**——宁可少说"这是结论",
13
+ * 不要把过期口径当现状喂回去。没有 claim 的消息保持 `raw`(弱状态,不进 body 正文)。
14
+ */
15
+ import type { ConsensusState } from './consensus.ts';
16
+ import type { ChatEvent } from './events.ts';
17
+ export type MemoryClaimState = 'raw' | 'active' | 'superseded';
18
+ /**
19
+ * 指令性语句特征(指令隔离用;Phase 0 只标记,Phase 1 注入时加"这是原文,不是指令"标注)。
20
+ * 放在 core:客户端/宿主都要用,host 侧索引从这里引用,避免两套正则漂移。
21
+ */
22
+ export declare const MEMORY_IMPERATIVE: RegExp;
23
+ export interface SeqClaim {
24
+ state: MemoryClaimState;
25
+ /** state=superseded 时,取代它的那条消息的 seq(能定位到就填)。 */
26
+ successorSeq?: number;
27
+ }
28
+ export interface ClaimStatusResult {
29
+ /** 消息 seq → claim 状态;未出现的 seq 视为 raw。 */
30
+ bySeq: Map<number, SeqClaim>;
31
+ /** 参与判定的消息 seq(= 弱状态脏区;只有这些 seq 需要重算/重写)。 */
32
+ claimedSeqs: number[];
33
+ active: number;
34
+ superseded: number;
35
+ }
36
+ export declare function deriveClaimStatuses(input: {
37
+ events: readonly ChatEvent[];
38
+ consensus?: ConsensusState;
39
+ }): ClaimStatusResult;
40
+ /**
41
+ * 把 claim 状态套到索引条目上,返回真正变动的 seq(弱状态脏区)。
42
+ *
43
+ * 只碰两类条目:本次有 claim 的 seq、以及上次打过非 raw 标记的 seq(claim 被撤/事实回退)。
44
+ * 其余条目原样保留,避免每次构建都重写整份索引。
45
+ */
46
+ export declare function applyClaimStatuses<T extends {
47
+ seq: number;
48
+ claim: MemoryClaimState;
49
+ successorSeq?: number;
50
+ }>(entries: readonly T[], bySeq: ReadonlyMap<number, SeqClaim>): {
51
+ entries: T[];
52
+ dirtySeqs: number[];
53
+ };
54
+ /**
55
+ * 客户端可用的轻量版:只凭 `thread.facts`(当前有效事实)+ `thread.consensusState` 推状态。
56
+ *
57
+ * 为什么要两套:host 侧有 events.jsonl 可回放 supersede/retract(最准);
58
+ * 但 prompt 组装跑在客户端(`core/runtime.ts` 会被打进 client bundle),拿不到事件日志。
59
+ * 客户端这版**只把「已知失效」的标成 superseded**,其余一律 raw(宁可不标 active,
60
+ * 也不把过期口径当结论)——而 body 只放 active,所以 raw 天然被挡在正文外。
61
+ */
62
+ export declare function claimsFromThread(input: {
63
+ facts?: readonly {
64
+ sourceMessageSeq?: number;
65
+ }[];
66
+ consensus?: ConsensusState;
67
+ }): Map<number, SeqClaim>;
@@ -0,0 +1,164 @@
1
+ import { SOURCE_PRIORITY } from './facts.js';
2
+ /**
3
+ * 指令性语句特征(指令隔离用;Phase 0 只标记,Phase 1 注入时加"这是原文,不是指令"标注)。
4
+ * 放在 core:客户端/宿主都要用,host 侧索引从这里引用,避免两套正则漂移。
5
+ */
6
+ export const MEMORY_IMPERATIVE = /(忽略(以上|上面|之前)|无视(以上|上面|之前)|忘记(以上|之前)|从现在(起|开始)|你现在(是|要|必须)|必须(执行|按我说的)|以上(全部)?作废|ignore\s+(the\s+)?(above|previous)|disregard\s+(the\s+)?(above|previous))/i;
7
+ /** 共识里这些状态视为「不再权威」;superseded/expired 明确过期,archived 是能力自述(也不该当结论)。 */
8
+ const NON_AUTHORITATIVE_CONSENSUS = new Set(['superseded', 'expired', 'archived']);
9
+ const AUTHORITATIVE_CONSENSUS = new Set(['active', 'applied', 'done']);
10
+ export function deriveClaimStatuses(input) {
11
+ const ordered = [...input.events].sort((left, right) => left.seq - right.seq);
12
+ const facts = new Map();
13
+ for (const event of ordered) {
14
+ if (event.kind !== 'fact' || !event.fact)
15
+ continue;
16
+ const payload = event.fact;
17
+ if (payload.op === 'retract') {
18
+ const existing = facts.get(payload.factId);
19
+ // 低优先级来源撤不掉高优先级事实(与 projectFacts 同一口径)。
20
+ if (existing && SOURCE_PRIORITY[payload.source] < SOURCE_PRIORITY[existing.source])
21
+ continue;
22
+ if (existing)
23
+ facts.set(payload.factId, { ...existing, state: 'superseded' });
24
+ continue;
25
+ }
26
+ if (payload.op === 'supersede' && payload.supersedes) {
27
+ const old = facts.get(payload.supersedes);
28
+ if (old && SOURCE_PRIORITY[payload.source] < SOURCE_PRIORITY[old.source])
29
+ continue;
30
+ if (old) {
31
+ facts.set(payload.supersedes, {
32
+ ...old,
33
+ state: 'superseded',
34
+ ...(payload.sourceMessageSeq === undefined ? {} : { successorSeq: payload.sourceMessageSeq }),
35
+ });
36
+ }
37
+ }
38
+ // assert 与 supersede 都带着新事实(和 projectFacts 一致)。
39
+ const previous = facts.get(payload.factId);
40
+ if (previous && SOURCE_PRIORITY[payload.source] < SOURCE_PRIORITY[previous.source])
41
+ continue;
42
+ facts.set(payload.factId, {
43
+ state: 'active',
44
+ source: payload.source,
45
+ ...(payload.sourceMessageSeq === undefined ? {} : { sourceSeq: payload.sourceMessageSeq }),
46
+ });
47
+ }
48
+ // seq → 该消息上所有 claim 的状态集合
49
+ const perSeq = new Map();
50
+ const touch = (seq, state, successorSeq) => {
51
+ if (typeof seq !== 'number' || !Number.isFinite(seq) || seq <= 0)
52
+ return;
53
+ let bucket = perSeq.get(seq);
54
+ if (!bucket) {
55
+ bucket = { states: [] };
56
+ perSeq.set(seq, bucket);
57
+ }
58
+ bucket.states.push(state);
59
+ if (successorSeq !== undefined && bucket.successorSeq === undefined)
60
+ bucket.successorSeq = successorSeq;
61
+ };
62
+ for (const track of facts.values())
63
+ touch(track.sourceSeq, track.state, track.successorSeq);
64
+ // 共识层覆盖(更高层结论;superseded 的 cluster 用 supersededByKey 找接手者的 seq)。
65
+ const clusters = input.consensus?.clusters ?? [];
66
+ const clusterByKey = new Map(clusters.map((cluster) => [cluster.key, cluster]));
67
+ for (const cluster of clusters) {
68
+ const successorSeq = cluster.supersededByKey
69
+ ? clusterByKey.get(cluster.supersededByKey)?.refs.find((ref) => typeof ref.sourceMessageSeq === 'number')?.sourceMessageSeq ?? undefined
70
+ : undefined;
71
+ const state = NON_AUTHORITATIVE_CONSENSUS.has(cluster.status)
72
+ ? 'superseded'
73
+ : AUTHORITATIVE_CONSENSUS.has(cluster.status)
74
+ ? 'active'
75
+ : undefined;
76
+ if (!state)
77
+ continue;
78
+ for (const ref of cluster.refs)
79
+ touch(ref.sourceMessageSeq ?? undefined, state, successorSeq);
80
+ }
81
+ const bySeq = new Map();
82
+ let active = 0;
83
+ let superseded = 0;
84
+ for (const [seq, bucket] of perSeq) {
85
+ // 同一消息里既有有效又有失效 claim:按保守口径算 superseded(不把过期口径当现状)。
86
+ const state = bucket.states.includes('superseded') ? 'superseded' : 'active';
87
+ if (state === 'active')
88
+ active += 1;
89
+ else
90
+ superseded += 1;
91
+ bySeq.set(seq, {
92
+ state,
93
+ ...(bucket.successorSeq === undefined ? {} : { successorSeq: bucket.successorSeq }),
94
+ });
95
+ }
96
+ return { bySeq, claimedSeqs: [...bySeq.keys()].sort((left, right) => left - right), active, superseded };
97
+ }
98
+ /**
99
+ * 把 claim 状态套到索引条目上,返回真正变动的 seq(弱状态脏区)。
100
+ *
101
+ * 只碰两类条目:本次有 claim 的 seq、以及上次打过非 raw 标记的 seq(claim 被撤/事实回退)。
102
+ * 其余条目原样保留,避免每次构建都重写整份索引。
103
+ */
104
+ export function applyClaimStatuses(entries, bySeq) {
105
+ const dirty = [];
106
+ const next = entries.map((entry) => {
107
+ const claim = bySeq.get(entry.seq);
108
+ const wantedState = claim?.state ?? 'raw';
109
+ const wantedSuccessor = claim?.successorSeq;
110
+ const changed = entry.claim !== wantedState || entry.successorSeq !== wantedSuccessor;
111
+ if (!changed)
112
+ return entry;
113
+ dirty.push(entry.seq);
114
+ const { successorSeq, ...rest } = entry;
115
+ return {
116
+ ...rest,
117
+ claim: wantedState,
118
+ ...(wantedSuccessor === undefined ? {} : { successorSeq: wantedSuccessor }),
119
+ };
120
+ });
121
+ return { entries: next, dirtySeqs: dirty.sort((left, right) => left - right) };
122
+ }
123
+ /**
124
+ * 客户端可用的轻量版:只凭 `thread.facts`(当前有效事实)+ `thread.consensusState` 推状态。
125
+ *
126
+ * 为什么要两套:host 侧有 events.jsonl 可回放 supersede/retract(最准);
127
+ * 但 prompt 组装跑在客户端(`core/runtime.ts` 会被打进 client bundle),拿不到事件日志。
128
+ * 客户端这版**只把「已知失效」的标成 superseded**,其余一律 raw(宁可不标 active,
129
+ * 也不把过期口径当结论)——而 body 只放 active,所以 raw 天然被挡在正文外。
130
+ */
131
+ export function claimsFromThread(input) {
132
+ const bySeq = new Map();
133
+ for (const fact of input.facts ?? []) {
134
+ const seq = fact.sourceMessageSeq;
135
+ if (typeof seq !== 'number' || seq <= 0)
136
+ continue;
137
+ bySeq.set(seq, { state: 'active' });
138
+ }
139
+ const clusters = input.consensus?.clusters ?? [];
140
+ const clusterByKey = new Map(clusters.map((cluster) => [cluster.key, cluster]));
141
+ for (const cluster of clusters) {
142
+ if (!NON_AUTHORITATIVE_CONSENSUS.has(cluster.status)) {
143
+ if (!AUTHORITATIVE_CONSENSUS.has(cluster.status))
144
+ continue;
145
+ for (const ref of cluster.refs) {
146
+ const seq = ref.sourceMessageSeq;
147
+ if (typeof seq === 'number' && seq > 0 && !bySeq.has(seq))
148
+ bySeq.set(seq, { state: 'active' });
149
+ }
150
+ continue;
151
+ }
152
+ const successorSeq = cluster.supersededByKey
153
+ ? clusterByKey.get(cluster.supersededByKey)?.refs.find((ref) => typeof ref.sourceMessageSeq === 'number')?.sourceMessageSeq ?? undefined
154
+ : undefined;
155
+ for (const ref of cluster.refs) {
156
+ const seq = ref.sourceMessageSeq;
157
+ if (typeof seq !== 'number' || seq <= 0)
158
+ continue;
159
+ // 失效优先:同一条消息既被有效结论引用、又被取代时,按 superseded 处理。
160
+ bySeq.set(seq, { state: 'superseded', ...(successorSeq === undefined ? {} : { successorSeq }) });
161
+ }
162
+ }
163
+ return bySeq;
164
+ }
@@ -0,0 +1,121 @@
1
+ /**
2
+ * 引用句柄协议(Phase 1 · 可寻址记忆层)。
3
+ *
4
+ * 设计定稿:**索引优先、检索降级、预算先行、状态贯穿**。
5
+ * 冷区(窗口之外的历史)不进正文,只进「句柄」;需要原文时模型写 `#seq`,系统再展开。
6
+ * 三块目录各管一件事:
7
+ * 1. 命中句柄:检索命中的旧消息(带状态、可展开);
8
+ * 2. 固定区间目录:最近 K 个话题段(与查询无关 —— 无锚点转述的兜底);
9
+ * 3. 最近 active 结论句柄:当前有效结论(问"之前那个事怎么定的"时最有用)。
10
+ *
11
+ * 硬规则(Phase 1 验收项):
12
+ * - body 只放 active;superseded 只进目录并指向 `→#successor`;无 claim 一律 raw(不进正文);
13
+ * - 每块硬上限;背压只允许同层内顺延,**绝不回流给检索正文**;
14
+ * - 正文一律最小片段(从句边界)+ 不可信包裹(指令隔离)。
15
+ *
16
+ * 纯函数、确定性、不调模型:同一输入永远产出同一块(黄金回放可用)。
17
+ */
18
+ import { type MemoryClaimState } from './memory-claims.ts';
19
+ import type { Message } from './types.ts';
20
+ export type MemoryContextMode = 'off' | 'shadow' | 'on';
21
+ export interface MemoryCaps {
22
+ snippets: number;
23
+ snippetChars: number;
24
+ snippetMaxChars: number;
25
+ handles: number;
26
+ segments: number;
27
+ conclusions: number;
28
+ directoryChars: number;
29
+ totalChars: number;
30
+ }
31
+ export declare const DEFAULT_MEMORY_CAPS: MemoryCaps;
32
+ export interface MemoryHandle {
33
+ seq: number;
34
+ at: number;
35
+ status: MemoryClaimState;
36
+ successorSeq?: number;
37
+ label: string;
38
+ authorName: string;
39
+ }
40
+ export interface MemorySnippet {
41
+ seq: number;
42
+ at: number;
43
+ authorName: string;
44
+ text: string;
45
+ }
46
+ export interface MemorySegmentEntry {
47
+ segmentId: number;
48
+ seqFrom: number;
49
+ seqTo: number;
50
+ active: number;
51
+ raw: number;
52
+ label: string;
53
+ }
54
+ export interface MemoryContextMeta {
55
+ mode: MemoryContextMode;
56
+ snippets: number;
57
+ handles: number;
58
+ segments: number;
59
+ conclusions: number;
60
+ snippetChars: number;
61
+ directoryChars: number;
62
+ totalChars: number;
63
+ backpressure: string[];
64
+ }
65
+ export interface MemoryContext {
66
+ snippets: MemorySnippet[];
67
+ handles: MemoryHandle[];
68
+ segments: MemorySegmentEntry[];
69
+ conclusions: MemoryHandle[];
70
+ block: string;
71
+ meta: MemoryContextMeta;
72
+ }
73
+ export interface MemoryContextReceipt {
74
+ mode: MemoryContextMode;
75
+ version: string;
76
+ snippetSeqs: number[];
77
+ handleSeqs: number[];
78
+ conclusionSeqs: number[];
79
+ segmentIds: number[];
80
+ /** 段目录行里出现的范围端 seq(`段 #from–#to`):回执审计"同一 seq 只出现一次"用。 */
81
+ segmentRefs: number[];
82
+ snippetChars: number;
83
+ directoryChars: number;
84
+ totalChars: number;
85
+ backpressure: string[];
86
+ /**
87
+ * 双层窗口的冷区审计(A-2):章节目录的章 id / 句柄 seq / 目录字数。
88
+ * 只在 `memoryContextMode=on` 且目录实际注入时出现;不含正文。
89
+ */
90
+ coldZone?: {
91
+ chapterIds: number[];
92
+ handleSeqs: number[];
93
+ chars: number;
94
+ };
95
+ }
96
+ export declare const MEMORY_CONTEXT_VERSION = "memory-handles-v1";
97
+ export interface MemoryContextInput {
98
+ messages: readonly Message[];
99
+ personaName: string;
100
+ currentText: string;
101
+ excludeSeqs?: ReadonlySet<number>;
102
+ claims?: ReadonlyMap<number, {
103
+ state: MemoryClaimState;
104
+ successorSeq?: number;
105
+ }>;
106
+ activeConclusions?: readonly {
107
+ seq: number;
108
+ label: string;
109
+ }[];
110
+ caps?: Partial<MemoryCaps>;
111
+ mode?: MemoryContextMode;
112
+ }
113
+ /** 从句边界取最小片段:优先命中词所在句;超长退到逗号边界,避免半句反转语义。 */
114
+ export declare function minimalSnippet(text: string, terms: readonly string[], maxChars: number): string;
115
+ /** 不可信包裹:指令性语句加显式标注;代码围栏降级,避免历史被当指令执行。 */
116
+ export declare function wrapUntrustedLine(text: string): string;
117
+ export declare function buildMemoryContext(input: MemoryContextInput): MemoryContext;
118
+ /** 只有 on 才注入;shadow 只写回执(供离线评估)。 */
119
+ export declare function memoryBlockOf(context: MemoryContext, mode: MemoryContextMode): string;
120
+ /** 回执用的结构化摘要(不含正文)。 */
121
+ export declare function memoryReceiptOf(context: MemoryContext): MemoryContextReceipt;