@dabuliu_wsy/dsh-im 0.0.0-stage → 0.3.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 (145) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +204 -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 +213 -0
  45. package/dist/core/im.js +1640 -0
  46. package/dist/core/index.d.ts +34 -0
  47. package/dist/core/index.js +34 -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/trash.d.ts +110 -0
  87. package/dist/core/trash.js +56 -0
  88. package/dist/core/types.d.ts +400 -0
  89. package/dist/core/types.js +1 -0
  90. package/dist/core/window.d.ts +6 -0
  91. package/dist/core/window.js +7 -0
  92. package/dist/core/workspace-node.d.ts +28 -0
  93. package/dist/core/workspace-node.js +232 -0
  94. package/dist/core/workspace.d.ts +9 -0
  95. package/dist/core/workspace.js +45 -0
  96. package/dist/host/agent-session.d.ts +296 -0
  97. package/dist/host/agent-session.js +964 -0
  98. package/dist/host/attachment-gc.d.ts +37 -0
  99. package/dist/host/attachment-gc.js +97 -0
  100. package/dist/host/calibration-samples-store.d.ts +5 -0
  101. package/dist/host/calibration-samples-store.js +67 -0
  102. package/dist/host/capabilities.d.ts +45 -0
  103. package/dist/host/capabilities.js +67 -0
  104. package/dist/host/derived-store.d.ts +36 -0
  105. package/dist/host/derived-store.js +199 -0
  106. package/dist/host/dsh-llm.d.ts +143 -0
  107. package/dist/host/dsh-llm.js +395 -0
  108. package/dist/host/event-store.d.ts +47 -0
  109. package/dist/host/event-store.js +154 -0
  110. package/dist/host/fs-atomic.d.ts +1 -0
  111. package/dist/host/fs-atomic.js +26 -0
  112. package/dist/host/group-files.d.ts +26 -0
  113. package/dist/host/group-files.js +142 -0
  114. package/dist/host/im-api.d.ts +408 -0
  115. package/dist/host/im-api.js +1188 -0
  116. package/dist/host/index.d.ts +103 -0
  117. package/dist/host/index.js +509 -0
  118. package/dist/host/media-type.d.ts +10 -0
  119. package/dist/host/media-type.js +39 -0
  120. package/dist/host/memory-index.d.ts +65 -0
  121. package/dist/host/memory-index.js +181 -0
  122. package/dist/host/metrics-store.d.ts +7 -0
  123. package/dist/host/metrics-store.js +104 -0
  124. package/dist/host/models.d.ts +39 -0
  125. package/dist/host/models.js +67 -0
  126. package/dist/host/persona-tools.d.ts +57 -0
  127. package/dist/host/persona-tools.js +226 -0
  128. package/dist/host/preflight.d.ts +31 -0
  129. package/dist/host/preflight.js +29 -0
  130. package/dist/host/receipt-store.d.ts +26 -0
  131. package/dist/host/receipt-store.js +68 -0
  132. package/dist/host/run-check.d.ts +51 -0
  133. package/dist/host/run-check.js +190 -0
  134. package/dist/host/state-roots.d.ts +50 -0
  135. package/dist/host/state-roots.js +163 -0
  136. package/dist/host/tool-cache.d.ts +25 -0
  137. package/dist/host/tool-cache.js +90 -0
  138. package/dist/host/tool-call-budget.d.ts +29 -0
  139. package/dist/host/tool-call-budget.js +38 -0
  140. package/dist/host/trash-store.d.ts +32 -0
  141. package/dist/host/trash-store.js +316 -0
  142. package/dsh-plugin.json +25 -0
  143. package/lib/client.inner.cjs +3933 -0
  144. package/lib/client.js +3941 -0
  145. package/package.json +86 -6
@@ -0,0 +1,183 @@
1
+ /**
2
+ * 群级上下文预算(按群里**最小上下文**统一压)。
3
+ *
4
+ * 为什么按最小而不是按发言者各自:同一轮里不同成员如果看到不同长度的上下文,
5
+ * 会各说各话(1M 角色看到 150k tokens,256k 角色只看到 64k)。统一预算后,
6
+ * 同一轮所有人共享同一份"压缩后的上下文",一致性优先;1M 角色想看得更多,
7
+ * 用 memory_search / memory_expand 按需拉原文(推压缩 + 拉原文)。
8
+ *
9
+ * 预算 = min(
10
+ * 每个在场成员模型: min(上下文 × 档位份额, 档位绝对上限)
11
+ * )
12
+ * 再按固定份额分给四块:窗口 60% / 摘要 18% / 事实 10% / 记忆 12%。
13
+ * 全确定性:同一组输入永远算出同一预算,可回放、可 golden 对照。
14
+ */
15
+ import { BUDGET_SAFETY, DEFAULT_BUDGET_TIER, DEFAULT_RATIO, resolveTier, } from './budget-plan.js';
16
+ import { RATIO_MAX, RATIO_MIN } from './calibration-samples.js';
17
+ import { BUDGET_TIERS } from './budget-plan.js';
18
+ /** 四块份额;窗口用不完时记忆块上限内的余量回流窗口。 */
19
+ export const CONTEXT_BLOCK_SHARES = { window: 0.6, summary: 0.18, facts: 0.1, memory: 0.12 };
20
+ /** 摘要/记忆块的字符硬上限(防单块吃穿预算;数值来自实测成本与可读性)。 */
21
+ export const MAX_SUMMARY_BLOCK_CHARS = 32_000;
22
+ export const MAX_MEMORY_BLOCK_CHARS = 8_000;
23
+ export const MIN_MEMORY_BLOCK_CHARS = 1_400;
24
+ export const MIN_SUMMARY_BLOCK_CHARS = 2_000;
25
+ export const MAX_WINDOW_BLOCK_CHARS = 400_000;
26
+ export const MIN_WINDOW_BLOCK_CHARS = 4_000;
27
+ /** 群级 token 预算:取在场成员里最小上下文。 */
28
+ export function groupContextTokens(entries, tier = DEFAULT_BUDGET_TIER) {
29
+ const resolvedTier = resolveTier(tier);
30
+ const spec = BUDGET_TIERS[resolvedTier];
31
+ const known = entries
32
+ .filter((entry) => typeof entry.contextWindow === 'number' && (entry.contextWindow ?? 0) > 0)
33
+ .map((entry) => ({ ...entry, contextWindow: entry.contextWindow }));
34
+ if (known.length === 0) {
35
+ return { tokens: spec.tokens, tier: resolvedTier, knownWindows: 0, clampedBy: 'tier-cap' };
36
+ }
37
+ const smallest = known.reduce((left, right) => (right.contextWindow < left.contextWindow ? right : left));
38
+ const shareCap = Math.floor(smallest.contextWindow * spec.maxShare);
39
+ if (shareCap >= spec.tokens) {
40
+ return { tokens: spec.tokens, tier: resolvedTier, smallest, knownWindows: known.length, clampedBy: 'tier-cap' };
41
+ }
42
+ return { tokens: shareCap, tier: resolvedTier, smallest, knownWindows: known.length, clampedBy: 'member-window' };
43
+ }
44
+ function clampNumber(value, min, max) {
45
+ return Math.min(max, Math.max(min, Math.round(value)));
46
+ }
47
+ /** 把群级 token 预算按份额换成各块的字符/条数预算(确定性)。 */
48
+ export function allocateContextBudget(tokens, options = {}) {
49
+ const raw = typeof options.ratio === 'number' && Number.isFinite(options.ratio) ? options.ratio : DEFAULT_RATIO;
50
+ const ratio = Math.min(RATIO_MAX, Math.max(RATIO_MIN, raw));
51
+ const safeTokens = Number.isFinite(tokens) && tokens > 0 ? tokens : 0;
52
+ const charsFor = (share) => safeTokens * share * ratio * BUDGET_SAFETY;
53
+ const memoryRaw = clampNumber(charsFor(CONTEXT_BLOCK_SHARES.memory), MIN_MEMORY_BLOCK_CHARS, MAX_MEMORY_BLOCK_CHARS);
54
+ const memoryChars = memoryRaw;
55
+ // 记忆块吃不满预算时,余量回流窗口(摘要/事实按各自上限,不回流)。
56
+ const memoryBudgetChars = charsFor(CONTEXT_BLOCK_SHARES.memory);
57
+ const rollover = Math.max(0, memoryBudgetChars - memoryChars);
58
+ const windowChars = clampNumber(charsFor(CONTEXT_BLOCK_SHARES.window) + rollover, MIN_WINDOW_BLOCK_CHARS, MAX_WINDOW_BLOCK_CHARS);
59
+ const summaryChars = clampNumber(charsFor(CONTEXT_BLOCK_SHARES.summary), MIN_SUMMARY_BLOCK_CHARS, MAX_SUMMARY_BLOCK_CHARS);
60
+ const factsChars = charsFor(CONTEXT_BLOCK_SHARES.facts);
61
+ const factsMax = clampNumber(options.factsMax ?? 60, 12, 120);
62
+ const factsCount = clampNumber(factsChars / 50, 12, factsMax);
63
+ return {
64
+ tokens: safeTokens,
65
+ ratio: Math.round(ratio * 1000) / 1000,
66
+ windowChars,
67
+ summaryChars,
68
+ factsCount,
69
+ memoryChars,
70
+ notes: rollover > 0 ? ['memory-rollover-to-window'] : [],
71
+ };
72
+ }
73
+ /** 一次性算出群级预算 + 四块分配;没有任何窗口信息时返回 undefined(调用方回退)。 */
74
+ export function groupContextBudget(entries, options = {}) {
75
+ const decision = groupContextTokens(entries, options.tier);
76
+ if (decision.knownWindows === 0)
77
+ return undefined;
78
+ return { ...decision, ...allocateContextBudget(decision.tokens, { ratio: options.ratio }) };
79
+ }
80
+ /** 在场成员(排除禁言)→ 群级预算条目;按 personaId 排序保证同一群签名稳定。 */
81
+ export function groupEntriesForThread(thread, policy = {}) {
82
+ const members = [...(thread.members ?? [])]
83
+ .filter((member) => member.activity !== 'muted')
84
+ .sort((left, right) => left.personaId.localeCompare(right.personaId));
85
+ return members.map((member) => {
86
+ const window = policy.contextWindowForPersona?.(member.personaId)
87
+ ?? (policy.fallback && policy.fallback.personaId === member.personaId ? policy.fallback.contextWindow : undefined);
88
+ const model = policy.modelForPersona?.(member.personaId);
89
+ return {
90
+ personaId: member.personaId,
91
+ ...(model ? { model } : {}),
92
+ ...(window === undefined ? {} : { contextWindow: window }),
93
+ };
94
+ });
95
+ }
96
+ /** 群级预算(thread 版本);没有成员的窗口信息时返回 undefined(调用方回退旧估算)。 */
97
+ export function groupBudgetForThread(thread, policy = {}) {
98
+ return groupContextBudget(groupEntriesForThread(thread, policy), {
99
+ ...(policy.tier === undefined ? {} : { tier: policy.tier }),
100
+ ...(policy.ratio === undefined ? {} : { ratio: policy.ratio }),
101
+ });
102
+ }
103
+ /** 预算输入签名:只有成员集合 / 模型窗口 / 档位变化才会变(消息条数、时间不参与)。 */
104
+ export function groupBudgetSignature(entries, tier) {
105
+ const resolved = resolveTier(tier);
106
+ const members = [...entries]
107
+ .map((entry) => `${entry.personaId}:${entry.model ?? ''}:${entry.contextWindow ?? ''}`)
108
+ .sort()
109
+ .join('|');
110
+ return `${resolved}#${members}`;
111
+ }
112
+ /** 回执里的预算快照(结构化、可 diff;不含正文/时间)。 */
113
+ export const CONTEXT_BUDGET_VERSION = 'context-budget-v1';
114
+ export function budgetViewOf(budget, input) {
115
+ const group = 'clampedBy' in budget ? budget : undefined;
116
+ const tier = resolveTier(input.tier);
117
+ return {
118
+ version: CONTEXT_BUDGET_VERSION,
119
+ source: input.source ?? (group ? 'group' : 'fallback'),
120
+ tier: group?.tier ?? tier,
121
+ tokens: group ? group.tokens : null,
122
+ ratio: budget.ratio,
123
+ windowChars: budget.windowChars,
124
+ summaryChars: budget.summaryChars,
125
+ digestChars: 0,
126
+ chapterChars: 0,
127
+ memoryChars: budget.memoryChars,
128
+ factsCount: budget.factsCount,
129
+ ...(group?.smallest
130
+ ? {
131
+ groupMinModel: {
132
+ personaId: group.smallest.personaId,
133
+ ...(group.smallest.model ? { model: group.smallest.model } : {}),
134
+ contextWindow: group.smallest.contextWindow,
135
+ },
136
+ }
137
+ : {}),
138
+ signature: input.signature ?? groupBudgetSignature([], input.tier),
139
+ };
140
+ }
141
+ function comparableBudget(receipt) {
142
+ return {
143
+ tokens: receipt.tokens,
144
+ tier: receipt.tier,
145
+ windowChars: receipt.windowChars,
146
+ summaryChars: receipt.summaryChars,
147
+ ...(receipt.groupMinModel ? { groupMinModel: receipt.groupMinModel } : {}),
148
+ };
149
+ }
150
+ /**
151
+ * 预算变更事件:**只有显式输入变化**(成员集合 / 模型窗口 / 档位 / ratio)才会返回。
152
+ * 消息条数、时间、轮次都不在判据里;同输入必然返回 undefined(单测锁死)。
153
+ */
154
+ export function budgetChangeOf(input) {
155
+ const { previous, next } = input;
156
+ if (!previous)
157
+ return undefined;
158
+ const same = previous.tokens === next.tokens
159
+ && previous.tier === next.tier
160
+ && previous.windowChars === next.windowChars
161
+ && previous.summaryChars === next.summaryChars
162
+ && JSON.stringify(previous.groupMinModel ?? null) === JSON.stringify(next.groupMinModel ?? null);
163
+ if (same)
164
+ return undefined;
165
+ let reason = 'ratio';
166
+ const before = input.previousInputs;
167
+ if (before) {
168
+ const tierChanged = resolveTier(before.tier) !== resolveTier(input.nextInputs.tier);
169
+ const memberIdsBefore = before.entries.map((entry) => entry.personaId).sort().join('|');
170
+ const memberIdsAfter = input.nextInputs.entries.map((entry) => entry.personaId).sort().join('|');
171
+ const windowsBefore = before.entries.map((entry) => `${entry.personaId}:${entry.model ?? ''}:${entry.contextWindow ?? ''}`).sort().join('|');
172
+ const windowsAfter = input.nextInputs.entries.map((entry) => `${entry.personaId}:${entry.model ?? ''}:${entry.contextWindow ?? ''}`).sort().join('|');
173
+ if (tierChanged)
174
+ reason = 'tier';
175
+ else if (memberIdsBefore !== memberIdsAfter)
176
+ reason = 'members';
177
+ else if (windowsBefore !== windowsAfter)
178
+ reason = 'model';
179
+ else
180
+ reason = 'ratio';
181
+ }
182
+ return { from: comparableBudget(previous), to: comparableBudget(next), reason };
183
+ }
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Curator(共识整理器)的提示词与输出解析。
3
+ *
4
+ * 位置:替换现有「每轮一次事实抽取」的那一次调用——同一份 facts 交给模型整理成
5
+ * 三栏聚类草稿(A/B/C/D + derived),再交给 consensus builder 做契约校验与物化。
6
+ * 解析器只做形状校验;事实覆盖、来源错栏、能力自述归档由 builder 强校验。
7
+ */
8
+ import { type ConsensusDraft } from './consensus.ts';
9
+ export interface CuratorFact {
10
+ factId: string;
11
+ owner: string;
12
+ kind: string;
13
+ text: string;
14
+ }
15
+ export interface CuratorPrompt {
16
+ system: string;
17
+ prompt: string;
18
+ }
19
+ export declare function buildCuratorPrompt(input: {
20
+ threadTitle: string;
21
+ facts: readonly CuratorFact[];
22
+ }): CuratorPrompt;
23
+ export interface CuratorParseResult {
24
+ ok: boolean;
25
+ errors: string[];
26
+ draft?: ConsensusDraft;
27
+ }
28
+ export declare function parseCuratorOutput(raw: string): CuratorParseResult;
@@ -0,0 +1,190 @@
1
+ /**
2
+ * Curator(共识整理器)的提示词与输出解析。
3
+ *
4
+ * 位置:替换现有「每轮一次事实抽取」的那一次调用——同一份 facts 交给模型整理成
5
+ * 三栏聚类草稿(A/B/C/D + derived),再交给 consensus builder 做契约校验与物化。
6
+ * 解析器只做形状校验;事实覆盖、来源错栏、能力自述归档由 builder 强校验。
7
+ */
8
+ import { CONSENSUS_LANES, CONSENSUS_MAX_TEXT, CONSENSUS_STATUSES, normalizeConsensusKind, } from './consensus.js';
9
+ export function buildCuratorPrompt(input) {
10
+ const system = [
11
+ '你是群聊共识整理器(curator)。只整理给出的 facts,不新增事实,不改写事实含义。',
12
+ '每条 fact 必须且只能放进一个簇;lane 含义:A 用户指令/验收,B 群共识(决定/立场/承诺/约束),C 任务,D 环境或能力自述。',
13
+ '硬规则:用户 fact 只能进 A 或 C;角色 fact 只能进 B 或 D;角色陈述自己“没有 shell / 跑不了 / 只能在群里”等能力或环境限制时必须进 D;同一内容合并进同一簇。',
14
+ 'kind 必须从这套里选一个:约束、变更、决定、验收、判定、分工、承诺、约定、立场、任务、能力自述、事实。',
15
+ 'status 可选,缺省 A/B/C=active、D=archived。取值:candidate(待确认)/ active(当前有效)/ applied(已落实的变更记录)/ done(已完成任务)/ resolved(已解决的历史结论)/ superseded(被更新结论取代,必须给 supersededByKey 指向新簇)/ expired(过期或一次性)/ archived(环境能力自述)。',
16
+ 'lane 与 status 约束:A 只允许 active/applied/candidate;B 只允许 active/candidate/resolved/superseded/expired;C 只允许 active/done/candidate;D 只允许 archived。',
17
+ '簇正文单行、不超过 80 字,不要以“角色名:”开头,不得包含 [当前消息]、[最近群聊]、[本轮群聊摘要]、收到:、开发预览 这类 prompt 回声。',
18
+ 'derived 只能从 C 簇拆出,lane 固定为 C,factIds 必须是来源簇 factIds 的子集。',
19
+ '只输出 JSON 对象,不要解释、不要 Markdown 代码块:',
20
+ '{"clusters":[{"key":"A1","lane":"A","kind":"约束","status":"active","factIds":["f_..."],"text":"一句话"},{"key":"B1","lane":"B","kind":"立场","status":"superseded","supersededByKey":"B2","factIds":["f_..."],"text":"旧结论"}],"derived":[{"key":"C2","lane":"C","kind":"任务","fromKey":"C1","factIds":["f_..."],"text":"一句话"}]}',
21
+ ].join('\n');
22
+ const lines = input.facts.map((fact) => `- ${fact.factId} | ${fact.owner} | ${fact.kind} | ${fact.text}`);
23
+ const prompt = [
24
+ `群名:${input.threadTitle}`,
25
+ `fact 数量:${input.facts.length}`,
26
+ 'facts:',
27
+ ...lines,
28
+ '',
29
+ `输出要求:clusters 覆盖全部 ${input.facts.length} 条 factId;没有内容可派生时 derived 输出空数组。`,
30
+ ].join('\n');
31
+ return { system, prompt };
32
+ }
33
+ function extractJson(raw) {
34
+ const text = raw.trim();
35
+ const start = text.indexOf('{');
36
+ const end = text.lastIndexOf('}');
37
+ if (start < 0 || end <= start)
38
+ return undefined;
39
+ return text.slice(start, end + 1);
40
+ }
41
+ function readText(record, label, errors) {
42
+ const text = typeof record.text === 'string' ? record.text.trim() : '';
43
+ if (!text) {
44
+ errors.push(`${label} 缺 text`);
45
+ return '';
46
+ }
47
+ if (text.length > CONSENSUS_MAX_TEXT) {
48
+ errors.push(`${label} text 超长:${text.length} > ${CONSENSUS_MAX_TEXT}`);
49
+ }
50
+ return text;
51
+ }
52
+ function readFactIds(record, label, errors) {
53
+ const value = record.factIds;
54
+ if (!Array.isArray(value)) {
55
+ errors.push(`${label} factIds 必须是数组`);
56
+ return [];
57
+ }
58
+ const factIds = value
59
+ .filter((item) => typeof item === 'string')
60
+ .map((item) => item.trim())
61
+ .filter(Boolean);
62
+ if (factIds.length === 0)
63
+ errors.push(`${label} factIds 为空`);
64
+ return factIds;
65
+ }
66
+ function readLane(record, label, errors) {
67
+ const lane = typeof record.lane === 'string' ? record.lane.trim().toUpperCase() : '';
68
+ if (!CONSENSUS_LANES.includes(lane)) {
69
+ errors.push(`${label} lane 非法:${String(record.lane)}`);
70
+ return 'A';
71
+ }
72
+ return lane;
73
+ }
74
+ function readKind(record, label, errors) {
75
+ const raw = typeof record.kind === 'string' ? record.kind.trim() : '';
76
+ if (!raw) {
77
+ errors.push(`${label} 缺 kind`);
78
+ return '事实';
79
+ }
80
+ const kind = normalizeConsensusKind(raw);
81
+ if (!kind) {
82
+ errors.push(`${label} kind 未知:${raw}`);
83
+ return '事实';
84
+ }
85
+ return kind;
86
+ }
87
+ function readStatus(record, label, errors) {
88
+ if (record.status === undefined || record.status === null)
89
+ return undefined;
90
+ const raw = typeof record.status === 'string' ? record.status.trim() : '';
91
+ if (!CONSENSUS_STATUSES.includes(raw)) {
92
+ errors.push(`${label} status 非法:${String(record.status)}`);
93
+ return undefined;
94
+ }
95
+ return raw;
96
+ }
97
+ export function parseCuratorOutput(raw) {
98
+ const json = extractJson(raw ?? '');
99
+ if (!json)
100
+ return { ok: false, errors: ['输出里没有 JSON 对象'] };
101
+ let data;
102
+ try {
103
+ data = JSON.parse(json);
104
+ }
105
+ catch (error) {
106
+ return { ok: false, errors: [`JSON 解析失败:${error instanceof Error ? error.message : String(error)}`] };
107
+ }
108
+ if (!data || typeof data !== 'object' || Array.isArray(data)) {
109
+ return { ok: false, errors: ['JSON 顶层必须是对象'] };
110
+ }
111
+ const record = data;
112
+ if (!Array.isArray(record.clusters))
113
+ return { ok: false, errors: ['clusters 必须是数组'] };
114
+ const errors = [];
115
+ const keys = new Set();
116
+ const seenFactIds = new Set();
117
+ const clusters = [];
118
+ record.clusters.forEach((item, index) => {
119
+ const label = `clusters[${index}]`;
120
+ if (!item || typeof item !== 'object' || Array.isArray(item)) {
121
+ errors.push(`${label} 不是对象`);
122
+ return;
123
+ }
124
+ const cluster = item;
125
+ const key = typeof cluster.key === 'string' ? cluster.key.trim() : '';
126
+ if (!key)
127
+ errors.push(`${label} 缺 key`);
128
+ else if (keys.has(key))
129
+ errors.push(`${label} key 重复:${key}`);
130
+ else
131
+ keys.add(key);
132
+ const lane = readLane(cluster, label, errors);
133
+ const kind = readKind(cluster, label, errors);
134
+ const status = readStatus(cluster, label, errors);
135
+ const text = readText(cluster, label, errors);
136
+ const factIds = readFactIds(cluster, label, errors);
137
+ const supersededByKey = typeof cluster.supersededByKey === 'string' ? cluster.supersededByKey.trim() : '';
138
+ for (const factId of factIds) {
139
+ if (seenFactIds.has(factId))
140
+ errors.push(`${label} factId 重复使用:${factId}`);
141
+ else
142
+ seenFactIds.add(factId);
143
+ }
144
+ clusters.push({
145
+ key,
146
+ lane,
147
+ kind,
148
+ text,
149
+ factIds,
150
+ ...(status === undefined ? {} : { status }),
151
+ ...(supersededByKey ? { supersededByKey } : {}),
152
+ });
153
+ });
154
+ const derived = [];
155
+ if (record.derived !== undefined && record.derived !== null) {
156
+ if (!Array.isArray(record.derived)) {
157
+ errors.push('derived 必须是数组');
158
+ }
159
+ else {
160
+ record.derived.forEach((item, index) => {
161
+ const label = `derived[${index}]`;
162
+ if (!item || typeof item !== 'object' || Array.isArray(item)) {
163
+ errors.push(`${label} 不是对象`);
164
+ return;
165
+ }
166
+ const entry = item;
167
+ const key = typeof entry.key === 'string' ? entry.key.trim() : '';
168
+ if (!key)
169
+ errors.push(`${label} 缺 key`);
170
+ else if (keys.has(key))
171
+ errors.push(`${label} key 重复:${key}`);
172
+ else
173
+ keys.add(key);
174
+ const lane = readLane(entry, label, errors);
175
+ if (lane !== 'C')
176
+ errors.push(`${label} lane 必须为 C`);
177
+ const kind = readKind(entry, label, errors);
178
+ const text = readText(entry, label, errors);
179
+ const factIds = readFactIds(entry, label, errors);
180
+ const fromKey = typeof entry.fromKey === 'string' ? entry.fromKey.trim() : '';
181
+ if (!fromKey)
182
+ errors.push(`${label} 缺 fromKey`);
183
+ derived.push({ key, lane: 'C', kind, text, factIds, fromKey });
184
+ });
185
+ }
186
+ }
187
+ if (errors.length > 0)
188
+ return { ok: false, errors };
189
+ return { ok: true, errors: [], draft: { clusters, derived } };
190
+ }
@@ -0,0 +1,86 @@
1
+ /**
2
+ * 双层窗口(热区最近窗口 + 冷区章节目录)。
3
+ *
4
+ * 设计口径:
5
+ * - **热区** = 原有 `selectWindow` 的结果(保持既有不变量:最新一条、@我的、被 @ 的、
6
+ * 自身最后发言都在热区);
7
+ * - **冷区** = 热区之前的消息,压成章节树/目录(`chapter-tree.ts`),只放 `#seq` 句柄;
8
+ * - **跨层 seq 去重**:同一 seq 只能出现一次,热区优先;冷区目录只引用热区外的 seq。
9
+ * 这条不变量是"prompt 里同一条历史不重复占预算"的硬保证。
10
+ *
11
+ * 纯函数、确定性(不依赖时间/随机),可进黄金回放。
12
+ */
13
+ import { type ChapterClaim, type ChapterTree } from './chapter-tree.ts';
14
+ import { type PromptMessage } from './prompt.ts';
15
+ export interface DualWindowInput {
16
+ /** 已分配 seq 的全部可见消息(`assignSeqs` 之后)。 */
17
+ messages: readonly PromptMessage[];
18
+ personaId: string;
19
+ personaName: string;
20
+ currentId?: string;
21
+ summaryUntilSeq?: number;
22
+ /** 热区字符预算(context-budget 的 `windowChars`)。 */
23
+ windowChars: number;
24
+ /** 群级 summary 总预算(冷区目录从这里分 40%)。 */
25
+ summaryChars: number;
26
+ /** 冷区目录占比(默认 40%);0 = 不建冷区(例如记忆模式 off/shadow 不注入时省算力)。 */
27
+ chapterShare?: number;
28
+ /** 单章目标大小(默认 summaryChars/3)。 */
29
+ targetChapterChars?: number;
30
+ claims?: ReadonlyMap<number, ChapterClaim>;
31
+ keep?: number;
32
+ /** 已算好的热区(避免重复 selectWindow;与回执是同一份)。 */
33
+ hot?: PromptMessage[];
34
+ /**
35
+ * 冷区额外排除的 seq:L1 摘要行 / memoryBlock 句柄 / 检索块已经引用过的 seq。
36
+ * 跨层去重是"任何 seq 在最终 prompt 里最多出现一次"的硬保证(热区 + 摘要 + 目录 + 句柄)。
37
+ */
38
+ excludeSeqs?: ReadonlySet<number>;
39
+ }
40
+ export interface DualWindowMeta {
41
+ hotCount: number;
42
+ hotChars: number;
43
+ coldMessages: number;
44
+ coldChapters: number;
45
+ coldBullets: number;
46
+ directoryChars: number;
47
+ chapterChars: number;
48
+ /** 跨层去重审计:目录里若仍出现热区 seq 会在这里(正常必须为空)。 */
49
+ dedupedSeqs: number[];
50
+ /** 热区第一条的 seq(冷区严格早于它)。 */
51
+ hotFromSeq: number;
52
+ }
53
+ export interface DualWindow {
54
+ hot: PromptMessage[];
55
+ cold: ChapterTree;
56
+ /** 冷区章节目录(已序列化,长度 ≤ chapterChars)。 */
57
+ directory: string;
58
+ meta: DualWindowMeta;
59
+ }
60
+ /**
61
+ * 构建双层窗口。
62
+ *
63
+ * `chapterShare = 0` 时只算热区(冷区返回空树),用于 shadow/off 档:
64
+ * 记忆层不注入时不该为目录付算力(但热区语义与 on 档完全一致)。
65
+ */
66
+ export declare function buildDualWindow(input: DualWindowInput): DualWindow;
67
+ /**
68
+ * 最终 prompt 的跨层 seq 去重审计:窗口行 / 目录句柄 / facts / memoryBlock 行里的 `#seq`
69
+ * 各出现一次。返回重复项(空 = 通过),供单测与回执断言。
70
+ *
71
+ * 注意:facts 行与 memoryBlock 行是**语义引用**(不是窗口行原文),这里只检查
72
+ * 「同一个 seq 在多个块里被重复引用」的情况,重复即视为预算浪费/不一致。
73
+ */
74
+ export declare function auditSeqUniqueness(input: {
75
+ windowSeqs: readonly number[];
76
+ directoryHandleSeqs: readonly number[];
77
+ factSeqs?: readonly number[];
78
+ memoryBlockSeqs?: readonly number[];
79
+ l1Seqs?: readonly number[];
80
+ segmentRefs?: readonly number[];
81
+ }): {
82
+ duplicateSeqs: number[];
83
+ bySource: Record<string, string[]>;
84
+ };
85
+ /** 章节目录里的 `#seq` 引用(用于回执/审计,不含正文)。 */
86
+ export declare function directoryRefs(directory: string): number[];
@@ -0,0 +1,175 @@
1
+ /**
2
+ * 双层窗口(热区最近窗口 + 冷区章节目录)。
3
+ *
4
+ * 设计口径:
5
+ * - **热区** = 原有 `selectWindow` 的结果(保持既有不变量:最新一条、@我的、被 @ 的、
6
+ * 自身最后发言都在热区);
7
+ * - **冷区** = 热区之前的消息,压成章节树/目录(`chapter-tree.ts`),只放 `#seq` 句柄;
8
+ * - **跨层 seq 去重**:同一 seq 只能出现一次,热区优先;冷区目录只引用热区外的 seq。
9
+ * 这条不变量是"prompt 里同一条历史不重复占预算"的硬保证。
10
+ *
11
+ * 纯函数、确定性(不依赖时间/随机),可进黄金回放。
12
+ */
13
+ import { buildChapterTree, splitSummaryBudget } from './chapter-tree.js';
14
+ import { selectWindow } from './prompt.js';
15
+ function seqOf(message) {
16
+ return typeof message.seq === 'number' && Number.isFinite(message.seq) && message.seq > 0 ? message.seq : 0;
17
+ }
18
+ /**
19
+ * 构建双层窗口。
20
+ *
21
+ * `chapterShare = 0` 时只算热区(冷区返回空树),用于 shadow/off 档:
22
+ * 记忆层不注入时不该为目录付算力(但热区语义与 on 档完全一致)。
23
+ */
24
+ export function buildDualWindow(input) {
25
+ const windowChars = Math.max(200, Math.floor(input.windowChars));
26
+ const hot = input.hot ?? selectWindow({
27
+ messages: input.messages,
28
+ personaId: input.personaId,
29
+ personaName: input.personaName,
30
+ ...(input.currentId ? { currentId: input.currentId } : {}),
31
+ ...(input.summaryUntilSeq === undefined ? {} : { summaryUntilSeq: input.summaryUntilSeq }),
32
+ ...(input.keep === undefined ? {} : { keep: input.keep }),
33
+ charBudget: windowChars,
34
+ });
35
+ const hotSeqs = new Set(hot.map((message) => seqOf(message)).filter((seq) => seq > 0));
36
+ const currentMessage = input.currentId ? input.messages.find((message) => message.id === input.currentId) : undefined;
37
+ const currentSeq = currentMessage ? seqOf(currentMessage) : 0;
38
+ const hotFromSeq = hot.length
39
+ ? Math.min(...hot.map(seqOf).filter((seq) => seq > 0))
40
+ : (currentSeq > 0 ? currentSeq : Number.POSITIVE_INFINITY);
41
+ const chapterShare = input.chapterShare ?? 0.4;
42
+ const hotChars = hot.reduce((sum, message) => sum + message.text.length, 0);
43
+ if (chapterShare <= 0 || !Number.isFinite(chapterShare)) {
44
+ return {
45
+ hot,
46
+ cold: emptyTree(input.summaryChars, chapterShare),
47
+ directory: '',
48
+ meta: {
49
+ hotCount: hot.length,
50
+ hotChars,
51
+ coldMessages: 0,
52
+ coldChapters: 0,
53
+ coldBullets: 0,
54
+ directoryChars: 0,
55
+ chapterChars: 0,
56
+ dedupedSeqs: [],
57
+ hotFromSeq: Number.isFinite(hotFromSeq) ? hotFromSeq : 0,
58
+ },
59
+ };
60
+ }
61
+ // 冷区 = 热区第一条之前、不在热区、非当前、非系统、且没被 L1/句柄块引用过。
62
+ // 这样目录引用的 seq 天然不与热区/摘要/句柄重叠(任何 seq 在最终 prompt 里最多出现一次)。
63
+ const extraExclude = input.excludeSeqs ?? new Set();
64
+ const coldMessages = input.messages.filter((message) => {
65
+ const seq = seqOf(message);
66
+ if (!seq || hotSeqs.has(seq) || extraExclude.has(seq))
67
+ return false;
68
+ if (input.currentId && message.id === input.currentId)
69
+ return false;
70
+ if (message.kind === 'system')
71
+ return false;
72
+ return seq < hotFromSeq;
73
+ });
74
+ const tree = buildChapterTree({
75
+ messages: coldMessages,
76
+ summaryChars: input.summaryChars,
77
+ chapterShare,
78
+ ...(input.targetChapterChars === undefined ? {} : { targetChapterChars: input.targetChapterChars }),
79
+ ...(input.claims === undefined ? {} : { claims: input.claims }),
80
+ excludeSeqs: hotSeqs,
81
+ });
82
+ // 跨层去重(防御性):`excludeSeqs` 已经让冷区天然不含热区 seq;这里再做一次集合审计,
83
+ // 若仍有交集(输入不合契约)记录下来,交给回执/测试暴露,而不是静默重复。
84
+ const dedupedSeqs = [];
85
+ for (const chapter of tree.chapters) {
86
+ for (const seq of chapter.handles)
87
+ if (hotSeqs.has(seq))
88
+ dedupedSeqs.push(seq);
89
+ for (const bullet of chapter.bullets)
90
+ if (hotSeqs.has(bullet.seq))
91
+ dedupedSeqs.push(bullet.seq);
92
+ }
93
+ if (dedupedSeqs.length)
94
+ tree.meta.backpressure.push('dual-window: 目录里出现热区 seq(违反跨层去重)');
95
+ return {
96
+ hot,
97
+ cold: tree,
98
+ directory: tree.directory,
99
+ meta: {
100
+ hotCount: hot.length,
101
+ hotChars,
102
+ coldMessages: tree.meta.messageCount,
103
+ coldChapters: tree.meta.chapterCount,
104
+ coldBullets: tree.meta.bulletCount,
105
+ directoryChars: tree.directory.length,
106
+ chapterChars: tree.meta.chapterChars,
107
+ dedupedSeqs: [...new Set(dedupedSeqs)].sort((left, right) => left - right),
108
+ hotFromSeq: Number.isFinite(hotFromSeq) ? hotFromSeq : 0,
109
+ },
110
+ };
111
+ }
112
+ function emptyTree(summaryChars, chapterShare) {
113
+ const split = splitSummaryBudget(summaryChars, { chapterShare });
114
+ return {
115
+ chapters: [],
116
+ directory: '',
117
+ meta: {
118
+ version: 'chapter-tree-v1',
119
+ chapterChars: split.chapterChars,
120
+ digestChars: split.digestChars,
121
+ chapterCount: 0,
122
+ bulletCount: 0,
123
+ directoryChars: 0,
124
+ messageCount: 0,
125
+ trimmedBullets: 0,
126
+ droppedChapters: 0,
127
+ backpressure: ['cold-zone-disabled'],
128
+ },
129
+ };
130
+ }
131
+ /**
132
+ * 最终 prompt 的跨层 seq 去重审计:窗口行 / 目录句柄 / facts / memoryBlock 行里的 `#seq`
133
+ * 各出现一次。返回重复项(空 = 通过),供单测与回执断言。
134
+ *
135
+ * 注意:facts 行与 memoryBlock 行是**语义引用**(不是窗口行原文),这里只检查
136
+ * 「同一个 seq 在多个块里被重复引用」的情况,重复即视为预算浪费/不一致。
137
+ */
138
+ export function auditSeqUniqueness(input) {
139
+ const owners = new Map();
140
+ const add = (source, seqs) => {
141
+ for (const seq of seqs) {
142
+ if (!Number.isFinite(seq) || seq <= 0)
143
+ continue;
144
+ const list = owners.get(seq) ?? [];
145
+ list.push(source);
146
+ owners.set(seq, list);
147
+ }
148
+ };
149
+ add('window', input.windowSeqs);
150
+ add('directory', input.directoryHandleSeqs);
151
+ add('facts', input.factSeqs ?? []);
152
+ add('memoryBlock', input.memoryBlockSeqs ?? []);
153
+ add('l1', input.l1Seqs ?? []);
154
+ add('segments', input.segmentRefs ?? []);
155
+ const duplicateSeqs = [];
156
+ const bySource = {};
157
+ for (const [seq, sources] of owners) {
158
+ if (sources.length <= 1)
159
+ continue;
160
+ duplicateSeqs.push(seq);
161
+ bySource[String(seq)] = sources;
162
+ }
163
+ duplicateSeqs.sort((left, right) => left - right);
164
+ return { duplicateSeqs, bySource };
165
+ }
166
+ /** 章节目录里的 `#seq` 引用(用于回执/审计,不含正文)。 */
167
+ export function directoryRefs(directory) {
168
+ const out = [];
169
+ for (const match of directory.matchAll(/#(\d+)/g)) {
170
+ const seq = Number(match[1]);
171
+ if (Number.isFinite(seq) && seq > 0)
172
+ out.push(seq);
173
+ }
174
+ return [...new Set(out)].sort((left, right) => left - right);
175
+ }